SQL - Select Top
In SQL, the SELECT TOP statement is used to retrieve a specified number of rows from a table. It allows you to limit the result set to a specific number of records based on a specified condition.
SELECT TOP n column1, column2, ...
FROM table_name
WHERE condition;
Let's break down the components of the SELECT TOP statement:
- SELECT TOP n: This specifies the number of rows you want to retrieve from the table, where n is the desired number.
- column1, column2, ...: These are the names of the columns you want to retrieve from the table.
- FROM table_name: This specifies the name of the table from which you want to retrieve the data.
- WHERE condition: This is an optional clause that allows you to specify conditions to filter the rows.
SELECT TOP 5 ProductName, Price
FROM Products
WHERE Category = 'Electronics'
ORDER BY Price DESC;
This query retrieves the top 5 products' names and prices from the Products table where the category is 'Electronics', ordered by price in descending order.