postgresqlcolumn-alias

Is it possible to label group conditions in postgres?


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


Solution

  • 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)