Search code examples
postgresqlcase

PostgreSQL CASE ... END with multiple conditions


Here is an extract of my table:

  gid    |    datepose    |    pvc
---------+----------------+------------
 1       |  1961          | 01
 2       |  1949          |
 3       |  1990          | 02
 1       |  1981          |
 1       |                | 03
 1       |                |

I want to fill the PVC column using a SELECT CASE as bellow:

SELECT

 gid,

 CASE
  WHEN (pvc IS NULL OR pvc = '') AND datpose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND datpose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datpose IS NULL OR datpose = 0) THEN '03'
 END AS pvc

FROM my_table ;

The result is the same content as source table, nothing has happened and I get no error message in pg_log files. It might be a syntax error, or a problem with using multiple conditions within WHEN clauses?

Thanks for help and advice!


Solution

  • This kind of code perhaps should work for You

    SELECT
     *,
     CASE
      WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
      WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
      WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
      ELSE '00'
     END AS modifiedpvc
    FROM my_table;
    
    
     gid | datepose | pvc | modifiedpvc 
    -----+----------+-----+-------------
       1 |     1961 | 01  | 00
       2 |     1949 |     | 01
       3 |     1990 | 02  | 00
       1 |     1981 |     | 02
       1 |          | 03  | 00
       1 |          |     | 03
    (6 rows)