Skip to content

Instantly share code, notes, and snippets.

@fritzy
Last active November 27, 2020 11:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fritzy/12839ab1049ada82c75d to your computer and use it in GitHub Desktop.
Save fritzy/12839ab1049ada82c75d to your computer and use it in GitHub Desktop.
Getting JSON paginated results of a table SELECT
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
@fritzy
Copy link
Author

fritzy commented Sep 29, 2015

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.

@fritzy
Copy link
Author

fritzy commented Sep 29, 2015

You'll need Postgresql 9.4+

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment