SQL ORDER BY LIMIT
The ORDER BY LIMIT clause is used to sort the result set and limit the number of rows returned. This is helpful when you need to retrieve the top or bottom results from a sorted dataset. For example, you can use this clause to get the top 5 highest-paid employees or the bottom 3 lowest-priced products.
The LIMIT keyword specifies the maximum number of rows to return. When used with ORDER BY, it helps in displaying a subset of sorted data.
Common use cases:
- Fetching the top 10 most expensive items.
- Displaying the 5 newest records.
- Fetching the first N rows from a dataset.
Example
This query retrieves the top 2 most expensive products.
Code Example
-- Fetch the top 2 most expensive products
SELECT Product, Price
FROM Orders
ORDER BY Price DESC
LIMIT 2;
Output
Product | Price |
---|---|
Laptop | 1200.00 |
Phone | 800.00 |
Explanation
- The query selects the Product and Price columns from the Orders table.
- The ORDER BY Price DESC sorts the data in descending order by price, and the LIMIT 2 fetches only the top 2 rows.
This is an efficient way to retrieve a subset of data when dealing with large datasets or when you only need the top or bottom results.