Lesson 9 +10 XP

SELECT TOP / LIMIT

Sometimes you only want the first few rows of a result. Different databases use different keywords for this.

MySQL / PostgreSQL / SQLite: LIMIT


sql

### SELECT * FROM Customers

### LIMIT 3;

Returns only the first 3 rows.

SQL Server / MS Access: SELECT TOP


sql

### SELECT TOP 3 * FROM Customers;

Same idea: only 3 rows.

Oracle: ROWNUM


sql

### SELECT * FROM Customers

### WHERE ROWNUM <= 3;

Combine with ORDER BY

To get the "top 3" by value, always sort first:


sql

### SELECT * FROM Products

### ORDER BY Price DESC

### LIMIT 3;

This returns the 3 most expensive products.

Why order matters


sql

### SELECT * FROM Products

### LIMIT 3

### ORDER BY Price DESC;

The rows above are picked before sorting, so the result is wrong. Always put ORDER BY before LIMIT.

TL;DR

  • MySQL/PostgreSQL/SQLite: LIMIT n.
  • SQL Server: SELECT TOP n.
  • Oracle: ROWNUM <= n.
  • Sort with ORDER BY first, then limit.