Last active
November 27, 2020 11:22
-
-
Save fritzy/12839ab1049ada82c75d 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 sometable | |
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 |
You'll need Postgresql 9.4+
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could cast the whole thing to text with ::text to keep from having to deserialize and re-serialize, passing it to the http response raw.