SQL SELECT TOP
The SELECT TOP clause in SQL is used to limit the number of rows returned by a query. It is commonly used with the SELECT statement to retrieve a specified number of rows from the result set. The syntax varies slightly between different database management systems (DBMS), but I’ll provide a general overview.
In SQL Server and MS Access, the syntax is:
|
1 2 3 |
SELECT TOP (number) column1, column2, ... FROM table_name WHERE condition; |
For example, if you want to retrieve the top 5 rows from a table named employees, you can use:
|
1 2 |
SELECT TOP 5 * FROM employees; |
In MySQL, you can use the LIMIT clause:
|
1 2 3 4 |
SELECT column1, column2, ... FROM table_name WHERE condition LIMIT number; |
For example:
|
1 2 3 |
SELECT * FROM employees LIMIT 5; |
It’s important to note that the exact syntax may vary, and some database systems may have their own ways of achieving similar results (e.g., using FETCH FIRST in some cases). Always refer to the documentation of the specific database management system you are working with for precise details on syntax and functionality.
FETCH FIRST
The FETCH FIRST clause in SQL is used to limit the number of rows returned by a query. It is similar to the LIMIT clause in MySQL and PostgreSQL. The FETCH FIRST clause is often used in conjunction with the ORDER BY clause to specify the ordering of the result set before limiting the number of rows.
|
1 2 3 4 5 6 |
-- Retrieve the top 3 orders with the highest total amount SELECT OrderID, CustomerID, TotalAmount FROM Orders ORDER BY TotalAmount DESC FETCH FIRST 3 ROWS ONLY; |
