I'm on Postgres 13.5.
Records always have a number (type: integer) and optionally a single letter A-Z (type: varchar(1) – not char for framework reasons).
Records are typically sorted number ASC, letter ASC NULLS FIRST. The sequence may have gaps. Missing letters are represented as NULL.
For example, you might get this order: 1, 1A, 1B, 2, 10, 10A, 10C
Now, I want to do stuff like finding the two records "to the right" of a given record. So if the given record is number 2, I want to find 10 and 10A in the above example.
it would be convenient if I could query for a condition like (pseudo code): number > $given_number OR (number = $given_number AND letter > $given_letter NULLS FIRST)
This doesn't work as written, of course. What are ways I could achieve this?
I'd prefer not to merge the columns or to add new columns.
Solutions I can think of:
- Select a list of record IDs in SQL, use application logic outside the DB to find IDs of the next two records, then make a second query to find only those.
- A longer condition that explicitly accounts for NULLs, something like
WHERE number > $given_number OR (number = $given_number AND (($given_letter IS NULL AND letter IS NOT NULL) OR letter > $given_letter)) ORDER BY number ASC, letter ASC NULLS FIRST LIMIT 2 - Coalescing NULLs, something like
WHERE number > $given_number OR (number = $given_number AND letter > COALESCE($given_letter, '')) ORDER BY number ASC, letter ASC NULLS FIRST LIMIT 2
Any better ideas? Or any thoughts on these?