Is it possible to label group conditions in postgres?

64 Views Asked by At

example pseudo-sql

SELECT *, condlabel FROM tbl WHERE cond1:(col1 = 1) OR cond2:(col2 = 2 and col3 = 4)

so the results will have additional column with exact condition label which they are satisfy

2

There are 2 best solutions below

0
Abyss On

as AymDev commented, perfect solution is to add conditions in select block with as aliasing

0
Bergi On

No, you can only label (create aliased expressions) in a SELECT clause, and you cannot use those in a WHERE clause, but you can use a subquery to achieve this:

SELECT *
FROM (
   SELECT *, (col1 = 1) AS cond1, (col2 = 2 and col3 = 4) AS cond2
   FROM tbl
) AS tmp
WHERE cond1 OR cond2

Alternatively just repeat them:

SELECT *, (col1 = 1) AS cond1, (col2 = 2 and col3 = 4) AS cond2
FROM tbl
WHERE (col1 = 1) OR (col2 = 2 and col3 = 4)