Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Top and Limit Keyword in SQL

Tags:

sql

A quick Question. Suppose I have the following two queries:

SELECT TOP 2 * FROM Persons; 

and

SELECT * FROM Persons limit 2; 

I want to know the difference between the execution of the above 2 queries? Basically, I want to know when should I use the limit keyword and when it is appropriate to use the top keyword. Also, How does the database return results based on the above 2 queries.

like image 461
reggie Avatar asked Apr 14 '11 19:04

reggie


People also ask

What is top keyword in SQL?

The SQL SELECT TOP Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance. Note: Not all database systems support the SELECT TOP clause.

What is the use of LIMIT keyword in SQL?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

What can I use instead of top in SQL?

There is an alternative to TOP clause, which is to use ROWCOUNT. Use ROWCOUNT with care, as it can lead you into all sorts of problems if it's not turned off.


2 Answers

If you are using SQL Server use TOP if you are using MySQL or Postgres use Limit!

AFAIK there is no product that currently supports both. Here's one list of current implementations and here's another (covers more products but in less detail)

like image 156
Martin Smith Avatar answered Sep 29 '22 13:09

Martin Smith


As stated in my comment for Martin Smith's answer above, there are products that support both, LIMIT and TOP (as you can see here). The difference is that TOP only selects the first n records, but LIMIT allows the definition of an offset to retrieve a specific range of records:

SELECT * FROM ... LIMIT 5 OFFSET 10 

This statement selects the first 5 records, after skipping 10 records and this isn't possible with TOP.

The example I posted is only checked against the DBS I linked above. I didn't check a SQL standard, because of a lack of time.

like image 32
rene Avatar answered Sep 29 '22 11:09

rene