SQL SELECT TOP, LIMIT, ROWNUM
Clause
SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.
The SELECT TOP clause is useful on large tables with thousands of records.
Note: Not all database systems support the SELECT TOP statement. MySQL supports the LIMIT statement to select a specified number of records, while Oracle uses ROWNUM.
SQL Server / MS Access Syntax
SELECT TOP number|percent column_name(s)
FROM table_name;
MySQL Syntax
SELECT column_name(s)
FROM table_name
LIMIT number;
Example
SELECT *
FROM Persons
LIMIT 5;
Oracle Syntax
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
Example
SELECT *
FROM Persons
WHERE ROWNUM <= 5;
Demo Database
In this tutorial, we will use the tutorialpro sample database.
Below is the data from the "Websites" table:
mysql> SELECT * FROM Websites;
+----+---------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+---------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | tutorialpro.org | http://www.tutorialpro.org/ | 5000 | USA |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
MySQL SELECT LIMIT Example
The following SQL statement selects the first two records from the "Websites" table:
Example
SELECT * FROM Websites LIMIT 2;
Executing the above SQL, the data is as follows:
SQL SELECT TOP PERCENT Example
In Microsoft SQL Server, you can also use a percentage as a parameter.
The following SQL statement selects the top 50% of records from the websites table:
Example
This operation can be executed in the Microsoft SQL Server database.
SELECT TOP 50 PERCENT * FROM Websites;