1

I have this query

SELECT 
    count(*) filter(where condition) as cond_cnt
FROM table
LIMIT 100

But count happening on all table, not respecting LIMIT at all

If I do it with a subquery:

SELECT 
    count(*) filter(where condition) as cond_cnt
FROM
(SELECT *
 FROM table
 LIMIT 100
) as sub

Then it works fine. What I am missing?

6
  • 3
    Remember that in query execution LIMIT is the last thing that runs. Having that in mind, in your first query, 'Limit 100' has no impact as it always returns a single value. But, in the second query, you are first limiting your data set to only 100 rows. Commented Dec 18, 2021 at 19:57
  • Yes, that seems right, but is there still a way to avoid subquery? Commented Dec 18, 2021 at 20:01
  • 1
    Limiting without ordering rarely makes sense. Commented Dec 18, 2021 at 20:10
  • Ordering doesn't belong to this question Commented Dec 18, 2021 at 20:20
  • 1
    A technical alternative would be a CTE. But your logic does require a second query. Even in natural language pseudocode, from the first 100 records of a table (a query) count those that meet a condition (another query). Commented Dec 18, 2021 at 23:40

1 Answer 1

1

But count happening on all table, not respecting LIMIT at all
What I am missing?

You are missing the well-defined order of events in a SELECT query. LIMIT happens after window-functions are applied. So you need a subquery or CTE to apply the LIMIT first.

See:

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

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.