Performance with Exists

Asked

Viewed 213 times

2

A colleague mentioned that by making a EXISTS in SQL, it is recommended to use DISTINCT 1 to improve performance.
For example, instead of doing:

SELECT *  
  FROM CLIENTES  
 WHERE NOT EXISTS (SELECT CODCLI 
                     FROM VENDAS 
                    WHERE VENDAS.CODCLI = CLIENTES.CODCLI)  

He suggested to do:

SELECT *  
  FROM CLIENTES  
 WHERE NOT EXISTS (SELECT DISTINCT 1
                     FROM VENDAS 
                    WHERE VENDAS.CODCLI = CLIENTES.CODCLI)  

There is difference (performance) in the execution of SQL s above?
Which would be recommended?

Banks: Oracle and Firebird (ATM system).

  • Sql-Server or Mysql?

  • 2

    In the newer versions of Oracle is indifferent , in any case I use the "select null from" in subselect , in some cases in Oracle a hint is useful

  • @Sveen I edited the question

  • 1

    Depending on the Data volume I think you have an improved SQL performance.

1 answer

2

In some tables, when you use Joins, some values can be duplicated in some relationships, so he has to search multiple lines within that same guy, but if you use distinct, he’ll just look for the first time that guy, no matter if that same guy could have another version in some field, then in tables with large numbers of records, it ends up being faster.

Let’s assume, you want to make a select on the sales chart, that sale belongs to a customer who has two different types of contracts, but the customer contract has no direct link to the sale, only to the customer, if you make a joins up the contracts, he will duplicate the lines of the same sale, one for each contract, and with the distinct he will search only in the first contract and will "skip" the second not to duplicate the same sale, now imagine making a select on all sales that goes into all customers and goes through all customers' contracts... would be much faster.

  • This does not answer the question. When you have reputation enough, you’ll be able to leave comments on any post but until then, write only answer that no depend on more information of who asked. - Of Revision

  • 1

    It’s complicated, when a new question comes up that is of a lower level, the analysts sr already answer perfectly, the Stack Overflow does not give space for beginner programmers to create reputations, I answered because no one was helping the guy and I had a good knowledge of the subject.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.