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.
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With