WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

SQL SELECT TOP Clause


SQL SELECT TOP clause

SELECT TOP clause specifies the number of records to return.

SELECT TOP clause is very useful for large tables with thousands of records.

Note: Not all database systems support SELECT TOP statements. MySQL supports the LIMIT statement to select a specified number of data, and Oracle can use ROWNUM to select.

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;

Examples

SELECT *
FROM Persons
WHERE ROWNUM <=5;


Demo database

In this tutorial, we will use the zomato sample database.

Here is the data from the "Websites" table:

mysql> SELECT * FROM Websites;
+----+---------------+---------------------------+-------+---------+
| id | name          | url                       | alexa | country |
+----+---------------+---------------------------+-------+---------+
|  1 | Google        | https://www.google.com/  |     1 | USA     |
|  2 | Taobao          | https://www.taobao.com/ |    9 | IN            |
|  3 | zomato       | http://www.zomato.com/  |  83     | IN           |
|  4 | indiamart           | http://indiamart.com/       |    20 | CN      |
|  5 | Facebook      | https://www.facebook.com/|     3 | USA     |
|  7 | stackoverflow | http://stackoverflow.com/|     0 | IND     |
+----+---------------+---------------------------+-------+---------+


MySQL SELECT LIMIT instance

The following SQL statement selects the first two records from the "Websites" table:

Example

SELECT * FROM Websites LIMIT 2;

Execute the above SQL, the data is as follows:



SQL SELECT TOP PERCENT instance

Percentage can also be used as a parameter in Microsoft SQL Server.

The following SQL statement selects the first 50 percent of records from the websites table:

Example

The following operations can be performed in a Microsoft SQL Server database.

SELECT TOP 50 PERCENT * FROM Websites;