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

Code

sql

### SELECT * FROM Customers

### LIMIT 3;

Returns only the first 3 rows.

SQL Server / MS Access: SELECT TOP

Code

sql

### SELECT TOP 3 * FROM Customers;

Same idea: only 3 rows.

Oracle: ROWNUM

Code

sql

### SELECT * FROM Customers

### WHERE ROWNUM <= 3;

Combine with ORDER BY

To get the &quot;top 3&quot; by value, always sort first:

Code

sql

### SELECT * FROM Products

### ORDER BY Price DESC

### LIMIT 3;

This returns the 3 most expensive products.

Why order matters

Code

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 &lt;= n.
  • Sort with ORDER BY first, then limit.