LIMIT and TOP are used in databases to restrict the number of records returned in a query result. They help when we only need a specific number of rows instead of the complete data.
TOP
TOP is mostly used in Microsoft SQL Server and MS Access. It returns the first specified number of records from a table.
Example
SELECT TOP 5 * FROM Students
This query will display only the first 5 records from the Students table.
TOP with ORDER BY
TOP is often used with ORDER BY to get the highest or lowest values.
Example
SELECT TOP 3 Name, Marks FROM Students
ORDER BY Marks DESC
This query shows the top 3 students with the highest marks.
LIMIT
LIMIT is used in MySQL and PostgreSQL to control how many records are returned.
Example
SELECT * FROM Students
LIMIT 5
This query will return only 5 records from the Students table.
LIMIT with ORDER BY
LIMIT can also be used with ORDER BY to get specific results.
Example
SELECT Name, Marks FROM Students
ORDER BY Marks DESC
LIMIT 3
This query will display the 3 students with the highest marks.
Difference between LIMIT and TOP
TOP is used in SQL Server.
LIMIT is used in MySQL and PostgreSQL.
Both are used to restrict the number of records returned by a query.