Table of Contents
ToggleThe SQL TOP clause, along with its alternatives LIMIT, FETCH FIRST, or ROWNUM, is used to limit the number of records returned by a query. This is especially useful for handling large datasets efficiently.
The SELECT TOP clause is supported by SQL Server and MS Access. Here’s the syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
Example: Select the first 3 records from the “Customers” table:
SELECT TOP 3 * FROM Customers;
In MySQL, the LIMIT clause is used to limit the number of records:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Example: Select the first 3 records from the “Customers” table:
SELECT * FROM Customers
LIMIT 3;
Oracle uses the FETCH FIRST clause for similar functionality:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
Example: Select the first 3 records from the “Customers” table:
SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
In older versions of Oracle, ROWNUM is used to limit records:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example: Select the first 3 records from the "Customers" table:
SELECT * FROM Customers
WHERE ROWNUM <= 3;
You can combine these clauses with a WHERE condition to further filter the results:
SELECT TOP 3 * FROM Customers
WHERE Country = 'Germany';
Equivalent in MySQL:
SELECT * FROM Customers
WHERE Country = 'Germany'
LIMIT 3;
To return records in a specific order, use the ORDER BY keyword:
SELECT TOP 3 * FROM Customers
ORDER BY CustomerName DESC;
Equivalent in MySQL:
SELECT * FROM Customers
ORDER BY CustomerName DESC
LIMIT 3;
Equivalent in Oracle:
SELECT * FROM Customers
ORDER BY CustomerName DESC
FETCH FIRST 3 ROWS ONLY;
