Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Case statement in Postgresql?

This is my SQL Query

CASE WHEN (1>2) THEN(
    select * from rate limit 10
    )
    ELSE
    (
    select * from rate limit 1
    )

When I use Case statement like above , I can get error like below.

ERROR:  syntax error at or near "CASE"
LINE 2: CASE WHEN (1>2) THEN(
        ^
SQL state: 42601
Character: 2

Can anyone help me to solve this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Put a SELECT in front of the CASE statement. Also, you need an END after the last statement of the CASE. You need a place for the result of the CASE expression to be stored. The examples in the documentation are not executing statements that return a value; just variable assignment. So you don’t need a SELECT there. If you don’t care about the return from the overall query, you can use PERFORM instead of SELECT.

SELECT CASE 
       WHEN 1 > 2 -- always false
       THEN (SELECT * FROM rate LIMIT 10)
       ELSE (SELECT * FROM rate LIMIT 1)
        END
;

You can also assign the result of the subqueries to a variable if this CASE is defined inside of a function.

DO
$$
DECLARE
    rec RECORD;
BEGIN
    CASE WHEN 1 > 2
    THEN (SELECT * INTO rec FROM rate LIMIT 10)
    ELSE (SELECT * INTO rec FROM rate LIMIT 1)
     END
    ;
END;
$$ LANGUAGE PLPGSQL;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading