Data Engineering

SQL LIMIT without ORDER BY: Which Five Rows Did You Mean?

Huwell Consultancy editorial2 min read

A query that returns five rows has not necessarily returned the five rows you intended. LIMIT controls how many rows are returned, but it does not define their order. This matters when building reports and paginated screens.

Make the order explicit

SELECT ticket_id, created_at
FROM tickets
ORDER BY created_at DESC, ticket_id DESC
LIMIT 5;

This teaching query asks for the newest timestamps first and uses ticket_id to break ties. Assume ticket_id is unique. PostgreSQL recommends a predictable unique ordering when using LIMIT. Without it, you cannot rely on a particular subset simply because it looked stable in one test.

Try a tie

Create six invented tickets, including two with the same timestamp. Predict which five should appear. Then remove the ID tie-breaker and explain what is no longer fully specified. The timestamp alone does not choose between rows with equal values.

Ordering is not a frozen snapshot

Even with a clear order, rows can be inserted or removed between separate page requests. An offset-based page may therefore shift. Decide what consistency the product needs rather than assuming an ORDER BY clause solves every pagination issue.

Useful review checks

  • Is the sort direction clear?
  • Can two rows tie on every ordering field?
  • What happens when the source changes between pages?
  • Does a large offset create work worth investigating?

For a Malta data or backend interview, explain the requested subset in words before writing syntax. That makes the intended behaviour easier to test.

Sources and further reading

Browse current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision