Is it redundant to use LIMIT in a QUERY whose ID is a primary key?

8

My question is if using LIMIT will there be some performance gain in QUERY .

Example:

SELECT descricao FROM produto WHERE id = 9999 LIMIT 1

Has better performance than?

SELECT descricao FROM produto WHERE id = 9999

Since it would be generic to not specify any tool, I'd like to answer the best known SQlite , SQL Server , PostgreSQL , MySQL , Oracle .

It does not necessarily have to be all, but I have preference in SQlite since it runs on mobile devices where performance / optimization is more complex.

    
asked by anonymous 17.05.2015 / 01:57

2 answers

5

If the query uses the primary key as the criterion, yes, it is redundant.

If the query uses as an index an index that is not the primary key and whose value is not unique, it may be, but not always. For example, if the value is at the end of the index (worst case), having LIMIT is not nearly the same in terms of performance.

Now, if the query uses a non-indexed column, it may not be essentially if the query does not return results. It pays to see how the SQLite optimizer works . LIMIT is referenced when dealing with subqueries. In any case, with no results, there will be TABLE SCAN anyway.

SQL Server and Oracle do not have LIMIT :

  • SQL Server uses TOP :

    SELECT TOP 1 descricao FROM produto WHERE id = 9999
    
  • Oracle uses ROWNUM :

    SELECT descricao FROM produto WHERE id = 9999 AND ROWNUM <= 1;
    
17.05.2015 / 03:09
1

I've never stopped to think about this but I think the best way to find out if it's faster is by using a feature to measure time when executing a query.

See an example below, in case using sql server:

USE AdventureWorks2012;
GO       
SET STATISTICS TIME ON;
GO
SELECT ProductID, StartDate, EndDate, StandardCost 
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
GO
SET STATISTICS TIME OFF;
GO

For more information see: link

    
03.07.2015 / 20:30