LIMIT restricts the number of rows returned by a query and can be used inside a derived table before a JOIN.
It is useful when only a limited subset of records should participate in a JOIN.
Select the five most recent orders and display their customer names.
SELECT
c.CustomerName,
x.OrderID,
x.OrderDate
FROM Customers c
INNER JOIN (
SELECT
OrderID,
CustomerID,
OrderDate
FROM Orders
ORDER BY OrderDate DESC
LIMIT 5
) x
ON c.CustomerID = x.CustomerID;
Used in dashboards, recent-activity reports, testing, and targeted analysis.
- LIMIT is common in MySQL, PostgreSQL, and some other systems.
- ORDER BY should define the desired subset.
- Syntax varies between databases.
- Limiting rows before a JOIN changes the business result.
- Use carefully when global versus per-group limits are involved.
What does LIMIT do?
LIMIT restricts the number of rows returned by a query in SQL dialects that support it.
Can LIMIT be used inside a JOIN subquery?
Yes. A derived table can use LIMIT before its result is JOINed.