0

Is there a way in POSTGRESQL to limit a resulting query given a condition?

I have tried something like this:

SELECT * 
FROM table 
LIMIT CASE 
       WHEN extract(hour from now())=9 then 143
       WHEN extract(hour from now())=10 then 178 ETC.`

I need to use this because depending on the current hour and the hour in the table, dinamically limit with the condition.

Any thoughts or ideas?

11
  • What you wrote should work. What's the issue? Commented May 3, 2018 at 9:33
  • Without an ORDER BY the LIMIT makes little sense. Commented May 3, 2018 at 9:33
  • @eurotrash gives me the following error: SQL Error [4856] [42601] Syntax error. LIMIT CASE WHEN extract(hour from now())=11 and replace(to_char(now(),'day'),' ','')='thursday' then 109 end Commented May 3, 2018 at 9:38
  • @joop I have an order by clause. Commented May 3, 2018 at 9:39
  • 1
    Wait a minute - Vertica? Why did you use the PostgreSQL tag then? Commented May 3, 2018 at 9:54

2 Answers 2

1

You can use row_number():

SELECT t.* 
FROM (SELECT t.*, ROW_NUMBER() OVER (ORDER BY ?) as seqnum
      FROM table t
     ) t
WHERE (extract(hour from now()) = 9 AND seqnum <= 143) OR
      (extract(hour from now()) = 10 AND seqnum <= 178) OR
      . . . 

The more likely solution would be to handle this at the application layer.

Note the ?: this represents the column to use for ordering the data. Normally when using LIMIT, you want ORDER BY.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, I think this is the best I can do, even with a CASE statement. Thanks.
1

https://www.postgresql.org/docs/current/static/queries-limit.html

LIMIT { number | ALL }

you can't use expression here, like you do with ORDER BY

https://www.postgresql.org/docs/current/static/queries-order.html

ORDER BY sort_expression1 [ASC | DESC] [NULLS { FIRST | LAST }] [, sort_expression2 [ASC | DESC] [NULLS { FIRST | LAST }] ...]

you need dynamic SQL here, for examplelook at PostgreSQL parameterized Order By / Limit in table function

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.