sqlpostgresql

NULL Values For Unmatched WHERE


Say I have a table with dates and associated data for each date. I want to select every date, but only show the associated data if it matches a WHERE clause, otherwise just fill it with NULL. The goal is to have a result with a row for each date, but only cool rows have the associated data.

Table:

Date Data
1 Not Cool
2 Cool
3 Cool
4 Not Cool

I want a query that returns:

Date Data
1 NULL
2 Cool
3 Cool
4 NULL

Is this possible?


Solution

  • If you just want to view your data this way, then use the following query:

    SELECT Date, CASE Data WHEN 'Cool' THEN 'Cool' END AS Data
    FROM yourTable;
    

    If you want to actually update your table then use:

    UPDATE yourTable
    SET Data = NULL
    WHERE Data <> 'Cool';