Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created August 9, 2021 04:33
Show Gist options
  • Save bagus2x/3cb1c09d4c9505084a9868a021460fba to your computer and use it in GitHub Desktop.
Save bagus2x/3cb1c09d4c9505084a9868a021460fba to your computer and use it in GitHub Desktop.
cursor based pagination example + non unique column
// Keunggulannya bisa untuk nonunique column timestamp
CREATE TABLE cek (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL,
created_at INT NOT NULL
);
INSERT INTO cek VALUES (DEFAULT, 'satu', 1);
INSERT INTO cek VALUES (DEFAULT, 'dua', 2);
INSERT INTO cek VALUES (DEFAULT, 'tiga', 3);
INSERT INTO cek VALUES (DEFAULT, 'empat', 4);
INSERT INTO cek VALUES (DEFAULT, 'lima', 4);
INSERT INTO cek VALUES (DEFAULT, 'enam', 5);
INSERT INTO cek VALUES (DEFAULT, 'enam2', 6);
INSERT INTO cek VALUES (DEFAULT, 'tuju', 6);
INSERT INTO cek VALUES (DEFAULT, 'delapan', 6);
INSERT INTO cek VALUES (DEFAULT, 'sembilan', 7);
INSERT INTO cek VALUES (DEFAULT, 'sepuluh', 8);
// Dari latest ke oldest
// Next
SELECT * FROM cek WHERE (created_at, id) < (input_tgl, input_id) ORDER BY created_at DESC, id DESC LIMIT 2;
// Previous
SELECT * FROM cek WHERE (created_at, id) > (input_tgl, input_id) ORDER BY created_at ASC, id ASC LIMIT 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment