Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Table orders(id bigint, customer_id bigint, status text, total numeric(12,2), created_at timestamptz). Write a query that returns the 20 most recent orders over 100.00 with status PAID or SHIPPED placed in the last 30 days, newest first, and explain why your result is stable between runs.

We filter with status IN ('PAID','SHIPPED') AND total > 100.00 AND created_at >= now() - interval '30 days', then sort with ORDER BY created_at DESC, id DESC and take LIMIT 20. The result is stable because id is unique, so the sort defines exactly one order even when two orders share the same created_at; without that tiebreaker, LIMIT may return different rows for ties from one run to the next.

Why this question is asked

Queries like this appear on almost every order history page, admin list and API endpoint we build. They look trivial, and that is why interviewers like them: a small detail, the sort tiebreaker, separates a query that works in a demo from one that behaves correctly in production, where pages sometimes show the same row twice or skip one. In this answer, we will write the query step by step, see why the order must be total for the result to be stable, look at how to keep it index friendly, and then note the MySQL and standard SQL spellings.

1A Quick Recap of the Table and the Requirement

Our table is orders(id bigint, customer_id bigint, status text, total numeric(12,2), created_at timestamptz). The type timestamptz in PostgreSQL stores an exact instant, and numeric(12,2) stores exact decimal amounts with two digits after the point, so comparing total with 100.00 is exact and has no rounding surprises.

The requirement has four parts: only orders whose status is PAID or SHIPPED, only totals over 100.00 (strictly greater), only orders created in the last 30 days, and only the 20 newest. The first three are filters, so they go into WHERE. The last one is an ordering plus a row limit.

2Writing the Query

Here is the query in PostgreSQL. Each line maps to one part of the requirement.

SQL
SELECT id, customer_id, status, total, created_at
FROM orders
WHERE status IN ('PAID', 'SHIPPED') -- only these two statuses
AND total > 100.00 -- strictly over 100.00
AND created_at >= now() - interval '30 days' -- the last 30 days, as an instant
ORDER BY created_at DESC, id DESC -- newest first, id breaks ties
LIMIT 20; -- at most 20 rows

Notice that we use IN for the statuses. It is shorter than two OR conditions and it avoids the classic precedence bug where AND binds tighter than OR. Notice also that now() - interval '30 days' means exactly 30 times 24 hours before the current instant. If the business meant calendar days in a particular time zone, we would compute the start of that day instead, for example date_trunc('day', now() AT TIME ZONE 'Europe/Berlin') - interval '29 days', converted back to an instant.

We also list the columns we need instead of SELECT *. That keeps the query readable, sends less data over the network, and does not break when someone adds a column.

3Why the Tiebreaker Makes the Result Stable

SQL tables have no built-in order. The database returns rows in whatever order its plan produces, and ORDER BY is the only promise we get. If we sort only by created_at, and two orders were created in the same microsecond (common with batch imports or tests that insert many rows at once), the database is free to put either one first. When those tied rows sit right at the cut-off of LIMIT 20, one run may return order 501 and the next run order 502.

This is not a theoretical worry. A different plan after statistics change, a parallel scan, or simply data being on different pages can change the order of tied rows. The fix is to make the ordering total, meaning no two rows can compare as equal. Adding id DESC does that, because id is unique.

SQL
-- Two orders share the same created_at at the cut-off
-- id | created_at
-- 502 | 2026-11-04 10:00:00+00
-- 501 | 2026-11-04 10:00:00+00
ORDER BY created_at DESC LIMIT 20 -- row 20 may be 501 on one run and 502 on the next
ORDER BY created_at DESC, id DESC LIMIT 20 -- row 20 is always 502, then 501 comes on the next page

So the answer to why the result is stable between runs is: because the sort key (created_at, id) is unique for every row, the order is fully defined, and LIMIT always cuts at the same place for the same data.

4Keeping the Query Index Friendly

On a large table we want an index to do the work. An index on (status, created_at) lets PostgreSQL jump to the PAID rows from the last 30 days and the SHIPPED rows from the last 30 days, already sorted by time. An index on (created_at) alone also works well when recent orders are a small part of the table. Adding id to the end of the index, (created_at, id), lets the index return rows already in our exact sort order, so the database can stop after finding 20 matching rows.

There is one rule to keep: leave the column bare on the left side of the comparison. If we write date(created_at) >= current_date - 30 or created_at + interval '30 days' >= now(), the database must compute an expression for every row, and a plain index on created_at can no longer be used for the range. Putting the arithmetic on the constant side, as we did, keeps the condition sargable, a term that means the database can use an index to search for it.

Conditions and whether an index on created_at can serve them
ConditionIndex usable?Why
created_at >= now() - interval '30 days'Yescolumn is bare, the right side is computed once
date(created_at) >= current_date - 30Nofunction applied to the column for every row
created_at + interval '30 days' >= now()Noarithmetic on the column side

5The Same Query in MySQL and Standard SQL

In MySQL 8.4 the interval syntax is slightly different, and the rest stays the same.

SQL
-- MySQL 8.4
SELECT id, customer_id, status, total, created_at
FROM orders
WHERE status IN ('PAID', 'SHIPPED')
AND total > 100.00
AND created_at >= NOW() - INTERVAL 30 DAY
ORDER BY created_at DESC, id DESC
LIMIT 20;
-- Standard SQL spelling of the row limit (PostgreSQL accepts it too)
ORDER BY created_at DESC, id DESC
FETCH FIRST 20 ROWS ONLY;

LIMIT is not part of the SQL standard, but PostgreSQL, MySQL and SQLite all support it. FETCH FIRST n ROWS ONLY is the standard form and also works in PostgreSQL, Oracle and SQL Server, so it is worth knowing when a team works across engines.

6Follow-up questions

How would you page to the next 20 rows without OFFSET?

We use keyset pagination. We remember the created_at and id of the last row on the current page and ask for rows that come after it in the sort order: AND (created_at, id) < (:lastCreatedAt, :lastId) with the same ORDER BY created_at DESC, id DESC LIMIT 20. PostgreSQL compares row values element by element, so this condition matches exactly the rows after the cut-off, and with an index on (created_at, id) each page costs the same no matter how deep we go. OFFSET 10000, by contrast, reads and throws away 10,000 rows every time, and rows shift when new orders arrive.

What index would you create for this query?

If most orders are PAID or SHIPPED and the 30-day window is a small part of the table, I would create an index on (created_at DESC, id DESC), or simply (created_at, id), since PostgreSQL can scan an index backwards. If those two statuses are a small fraction of rows, a partial index such as CREATE INDEX ON orders (created_at, id) WHERE status IN ('PAID','SHIPPED') is smaller and more selective. I would confirm the choice with EXPLAIN (ANALYZE, BUFFERS) on realistic data.

Why not use BETWEEN for the date range?

BETWEEN includes both ends, which is fine here, but for ranges between two dates it tends to cause off-by-one errors at midnight. A half-open range, created_at >= start AND created_at < end, is clearer and never double counts a row on the boundary.

7Conclusion

In this answer, we wrote the query with IN for the statuses, a strict comparison on total and a time range computed on the constant side, then sorted by created_at DESC with id DESC as a tiebreaker and limited to 20 rows. The tiebreaker makes the order total, so the same data always produces the same 20 rows. We also saw how to keep the filter index friendly and how to spell the query in MySQL and in standard SQL.

What to say in the interviewAbout 80 seconds aloud

Open with

I would write SELECT with the needed columns from orders WHERE status IN PAID and SHIPPED, AND total greater than 100.00, AND created_at greater than or equal to now() minus interval 30 days, ORDER BY created_at DESC, id DESC, LIMIT 20.

Then, if they want more

The important part is the id tiebreaker. Rows in SQL have no natural order, so if two orders have the same created_at at the cut-off, a sort on created_at alone lets the database return either one, and the twentieth row can change between runs or after a plan change.

Because id is unique, the sort on created_at and id is total, so the result is deterministic and also safe for keyset pagination on the next page. I keep created_at bare on the left of the comparison so an index on created_at, or on status and created_at, can be used; wrapping it in a function would force a scan.

In MySQL I would write NOW() minus INTERVAL 30 DAY, and the standard spelling of LIMIT is FETCH FIRST 20 ROWS ONLY. For an index I would start with created_at and id, or a partial index on those statuses if they are rare.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.4
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Table orders(id bigint, customer_id bigint, status text, total numeric(12,2), created_at...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/fb93361a59/