Postgresql – Can a `Select` Subquery be conditionally returned?

conditionpostgresqlsubquery

Is it possible in Postgres to return a column(Resulting from a subquery) only when a condition matches?

Query:

SELECT
  (SELECT NOW()) AS FIRST,

  (SELECT NOW()) AS SECOND

Outputs:

| first      | second      |
|:-----------|------------:|
| timestamp  | timestamp   |

I would like something along those lines:
(Pseudo-code)

IF (variable =! 'something') {
  SELECT FIRST, SECOND
} ELSE {
 SELECT FIRST
}
| first      |
|:-----------|
| timestamp  |

Best Answer

In general no. A relation (a table or the result of a query) consists of a header and a set of tuples. Once the header is declared, all tuples must conform to that declaration. That said, null is the bottom of all types, so you can use that instead of a value:

SELECT FIRST, CASE WHEN variable <> 'something' then SECOND else NULL END

NULL is the default for a case, so it can be shortened to:

SELECT FIRST, CASE WHEN variable <> 'something' then SECOND END