SQL LIMIT Function |
SQL Sample Code - SQL LIMIT Function |
| SELECT * FROM table_name LIMIT [number]; |
Note: The LIMIT function is supported by MySQL. Use other alternatives for other databases that do not support LIMIT;
- TOP - SQL Server
- ROWNUM - Oracle
See the examples section below for an explanation of the LIMIT function.
What does the LIMIT Function do? |
The SQL LIMIT function simply retrieves a specified number of rows as part of a select statement.
The LIMIT function is particularly useful in SQL queries where the data-set values change on a regular basis.
Example 1 – SQL LIMIT Function |
In this example 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 example we simply want to limit the table of results to show the first 2 rows.
Use the SELECT statement below:
| SELECT * FROM tblCompany LIMIT 2; |
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 |
Example 2 – SQL LIMIT Function using ORDER BY. |
In this example 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 example 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 * FROM tblCompany ORDER BY Sales ASC LIMIT 3; |
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:
|
|