Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set LIMIT within a conditional statement; POSTGRESQL

I want to order the result by id in descending order and then LIMIT the number of rows obtained based on a @condition

ORDER BY id DESC
IF @condition is TRUE THEN  LIMIT 1
ELSE nothing
END IF
like image 587
Himank Jog Avatar asked Mar 05 '23 22:03

Himank Jog


1 Answers

You could use CASE:

ORDER BY id DESC
LIMIT CASE WHEN @condition THEN 1 END;

DBFiddle Demo

LIMIT NULL is the same as omitting the LIMIT clause

like image 110
Lukasz Szozda Avatar answered Mar 08 '23 23:03

Lukasz Szozda