SQL TOP clause |
SQL Sample Code - SQL TOP clause |
| SELECT TOP [number][percent] column_name(s) FROM table_name; |
Note: The TOP clause is supported by SQL Server. Use other alternatives for other databases that do not support LIMIT;
- LIMIT - MySQL
- ROWNUM - Oracle
See the SQL samples section below for an explanation of the TOP clause.
What does the TOP clause do? |
The SQL TOP clause simply retrieves a specified number of rows as part of a select statement.
The TOP clause is particularly useful in SQL queries where the data-set values change on a regular basis.
Sample 1 – SQL TOP clause. |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we simply want to limit the table of results to show the first 2 rows.
Use the SELECT statement below:
| SELECT TOP 2 * FROM tblCompany; |
The result will look like this:
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
Sample 2 – SQL TOP clause using ORDER BY. |
In this SQL sample we will use the database table ‘tblCompany’.
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 2 | SQL Code Land | 2 Code Rd | Hamburg | 20000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
In this SQL sample we simply want to limit the table of results to show the first 3 rows after we have arranged the Sales column in ascending order (ASC).
Use the SELECT statement below:
| SELECT TOP 3 * FROM tblCompany ORDER BY Sales ASC |
The result will look like this:
| Company_ID | CompanyName | Address | Town | Sales |
| 1 | SQL Sample | 1 Sample St | Hamburg | 10000 |
| 4 | SQL Reference Ltd | 34 Reference St | Pisa | 17000 |
| 3 | Sample Code World | 66 SQL St | Curry | 18000 |
Note: To learn more about ordering records go to the ORDER BY section.
Related SQL Sample Code:
|
|