Select Top in SQL
SELECT TOP in SQL
The SELECT TOP clause is used to limit the number of rows returned by a query, commonly used in SQL Server and some other databases.
Syntax:
SELECT TOP number [PERCENT] column1, column2, ...FROM table_nameWHERE conditionORDER BY column_name;number: Specifies how many rows to return.PERCENT(optional): Returns the top percentage of rows instead of a fixed number.
Examples:
Get the top 5 highest salaries from employees:
SELECT TOP 5 *FROM employeesORDER BY salary DESC;Get the top 10% of orders by amount:
SELECT TOP 10 PERCENT *FROM ordersORDER BY order_amount DESC;Notes:
TOPis primarily used in SQL Server and MS Access.In MySQL and PostgreSQL, use
LIMITinstead:
-- MySQL/PostgreSQL equivalent:SELECT * FROM employeesORDER BY salary DESCLIMIT 5;Need help with TOP in a specific SQL dialect or combining it with other clauses?