I have a table called profile
containing user information. I need to do a filtered query on this table and get:
- The count of rows that matched this query.
- The data for the top 5000 matching rows only.
I am looking for an optimal way to do this. Obviously there will need to be at least one scan to do the count, but ideally the DB could be fetching the top matching whilst it does the count.
The following query gives me the correct result, but it looks a bit hacky. I'm wondering if it can be done better?
WITH total AS (
SELECT COUNT(*) AS total FROM profile
WHERE project_id = 1 and some_prop = 100)
SELECT total.total, full_name, other_prop
FROM profile
INNER JOIN total ON 1 = 1
WHERE project_id = 1 and some_prop = 100
ORDER BY full_name ASC
LIMIT 5000
Is there a more efficient way to do this?