Search code examples
sqlpostgresqlsql-order-bygreatest-n-per-groupsql-limit

How to make conditional LIMIT in SELECT query?


I want to make conditional order by with limit and offset. If the count is 1 then I want the latest date otherwise I want latest but one record. I was trying the below query,

If the count of a select query is 1 then,

Select * from table_name
ORDER BY date_column LIMIT 1;

Otherwise,

Select * from table_name
ORDER BY date_column LIMIT 1 OFFSET 1;

Is there any other way to implement the logic?


Solution

  • select * from (
        Select * from table_name
        ORDER BY date_column LIMIT 2
     ) as foo ORDER BY date_column DESC LIMIT 1