SQL Getting Sta...login
SQL Getting Started Tutorial Manual
author:php.cn  update time:2022-04-12 14:15:40

SQL SELECT TOP


SQL SELECT TOP, LIMIT, ROWNUM Clause


SQL SELECT TOP Clause

SELECT TOP clause is used Specifies the number of records to be returned.

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

Note: Not all database systems support the SELECT TOP clause.

SQL Server / MS Access Syntax

SELECT TOP number|percent column_name(s)
FROM table_name;


SQL SELECT TOP in MySQL and Oracle are equivalent

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 php sample database.

The following is the data selected from the "Websites" table:

mysql> SELECT * FROM Websites;
+----+-------- -------+--------------------------+-------+------ ---+
| id | name | url | alexa | country |
+----+---------------+------- --------------------+-------+---------+
| 1 | Google | https:/ /www.google.cm/ | 1 | USA |
| 2 | Taobao | https://www.taobao.com/ | 13 | CN |
| 3 | php Chinese website | http://www .php.cn/ | 5000 | USA |
| 4 | Weibo | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+-------------- +--------------------------+-------+---------+

SQL SELECT TOP Example

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

You can also use percentages as parameters in Microsoft SQL Server.

The following SQL statement selects the first 50% of the records from the "Customers" table:

Example

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

SELECT TOP 50 PERCENT * FROM Websites;