LIMIT & OFFSET SQL practice problemEasyVerified answer

The "First" Trap — LIMIT Always Needs ORDER BY

List 5 employees with employee_id 1-5. The natural-but-wrong way is to write `SELECT … LIMIT 5` and hope the engine returns the lowest IDs. The right way is to ORDER BY first. Show employee_id, first_name, last_name — sorted by employee_id ascending — first 5 only.

  • CTEs
  • Sorting
  • Top-N

Interview brief

Understand the request

List 5 employees with employee_id 1-5. The natural-but-wrong way is to write `SELECT … LIMIT 5` and hope the engine returns the lowest IDs. The right way is to ORDER BY first. Show employee_id, first_name, last_name — sorted by employee_id ascending — first 5 only.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

employees

  • employee_idINTEGER
  • first_nameTEXT
  • last_nameTEXT

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

There is no implicit ordering in SQL. 'First 5 rows' has no meaning until you tell the engine what 'first' is.

Hint 2

Common antipattern: relying on insertion order or primary-key order. Both happen to work today, neither is guaranteed.

Hint 3

Always: ORDER BY <unique-column> LIMIT N.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT employee_id, first_name, last_name FROM employees ORDER BY employee_id LIMIT 5;

Why this works

Storage engines reorder rows for many reasons — heap reorganisation, index choice changes, parallel scans, vacuum operations. A query that 'works' without ORDER BY is a latent bug waiting for the next migration.

Expected result

Use this output to verify values, aliases, ordering, and row count.

employee_idfirst_namelast_name
1JohnDoe
2JaneSmith
3MikeJohnson
4SarahWilliams
5DavidBrown

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics: