208

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!

2
  • 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 Commented Jan 6, 2015 at 14:03
  • 4
    You also have an issue with brackets. Why is there a closing bracket after 1980 ? (in both places) Commented Jan 6, 2015 at 14:05

2 Answers 2

324

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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!
Can I skip ELSE?
The ELSE is optional. Without an ELSE, the expression will return NULL when none of ten WHEN clauses match.
-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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.