194

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!

wiltomap
  • 3,933
  • 8
  • 37
  • 54
  • Can you display a NULL value where it is null (so we can see the difference between NULL and empty string)? As in, a string containing `NULL` for example – Paco Jan 06 '15 at 14:03
  • 4
    You also have an issue with brackets. Why is there a closing bracket after 1980 ? (in both places) – Paco Jan 06 '15 at 14:05

2 Answers2

296

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)
Soni Harriz
  • 3,378
  • 1
  • 12
  • 8
  • 3
    Nearly perfect ;-) ! I would just replace `ELSE '00'` with `ELSE pvc` so that I can keep the existing values in `pvc` column, otherwise they are scratched with '00' (case `pvc IS NOT NULL`). Thanks a lot! – wiltomap Jan 06 '15 at 14:33
  • Can I skip ELSE? – Zon Aug 22 '19 at 12:24
  • 3
    The ELSE is optional. Without an ELSE, the expression will return NULL when none of ten WHEN clauses match. – Klaws Oct 15 '19 at 13:43
-1

You must CAST before the value passed as parameter and insert after the parameter the VARCHAR(50) Example: WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN cast ('01' as varchar(50))