use of top statements in different databases
Syntax for SQL Server:
SELECT
Top number|percentCOLUMN_NAME (s) from table_name
The SQL SELECT top in MySQL and Oracle is 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
The original table (in the example):
Persons table:
Id |
LastName |
FirstName |
| Address
| City
1 |
Adams |
John |
Oxford Street |
London |
2 |
Bush |
George |
Fifth Avenue |
New York |
3 |
Carter |
Thomas |
Changan Street |
Beijing |
4 |
Obama |
Barack |
Pennsylvania Avenue |
Washington |
SQL Top Instance
Now we want to select the first two records from the "Persons" table above.
We can use the following SELECT statement:
SELECT Top 2 * from Persons
Results:
Id |
LastName |
FirstName |
| Address
| City
1 |
Adams |
John |
Oxford Street |
London |
2 |
Bush |
George |
Fifth Avenue |
New York |
SQL Top PERCENT instance
Now, we want to select 50% of the records from the "Persons" table above.
We can use the following SELECT statement:
SELECT Top PERCENT * from Persons
Results:
Id |
LastName |
FirstName |
| Address
| City
1 |
Adams |
John |
Oxford Street |
London |
2 |
Bush |
George |
Fifth Avenue |
New York |
Add:
Limit can implement top N query, also can implement m to N ( a paragraph) of the record query, the specific syntax is as follows:
LIMIT Offset, Recnum
Where offset is started from the first few (m+1) Records, Recnum is the number of record bars returned. Cases:
Limit 2, 5