-
-
Save aregee/907110eda47bbf0386a2 to your computer and use it in GitHub Desktop.
Getting JSON paginated results of a table SELECT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT json_build_object( | |
'total', (SELECT n_live_tup FROM pg_stat_user_tables WHERE relname='sometable'), | |
'count', count(sometable_rows.*), | |
'offset', 0, | |
'results', json_agg(row_to_json(sometable_rows)) | |
) | |
FROM (SELECT * FROM test_log_clj) | |
ORDER BY "time" | |
LIMIT 10 OFFSET 0) | |
sometable_rows; | |
-- {"total": 2, "offset": 0, "count": 2, "results": [{"id": 1, "name": "Ogden Wernstrom"}, {"id": 2, "name": "Hubert Farnsworth"}]} | |
-- | |
-- total is only accurate after VACUUM, | |
-- but much faster than selecting the whole table to get a count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment