9
I am making a query using NOT EXISTS on a college job. The situation is as follows:
1.14 - Designing the CPF and the amount to pay in rentals by customers who have rented media and have not made any payment yet.
The consultation carried out and that worked, follows below:
SELECT A.CPF_Cliente,
SUM(ValorPagar) AS TotalValorPagar
FROM Aluguel A
WHERE NOT EXISTS (SELECT 1
FROM Pagamentos B
WHERE A.CPF_Cliente = B.CPF_Cliente
AND A.ID_Midia = B.ID_Midia
AND A.DataLocacao = B.DataLocacao)
GROUP BY A.CPF_Cliente;
Researching how to use NOT EXISTS
, I found that in several examples they used the SELECT 1
. I would like to know how it works and where I should use it.
I liked the answer. Although doing a quick search here, I found that some tests performed using SELECT 1 and SELECT * in Queries, did not give much difference in performance.But it answered well what I wanted to know, thank you!
– William Pereira
@williamhk2 for this I wrote the "try to", This can only be felt when you have a very high number of records. However today most bank engines have optimization techniques :)
– Guilherme Nascimento
good William, thank you!
– William Pereira
Basically it will return the existing values, as if it were "SELECT true FROM table", it is right work with
booleano
in a query, and is not recommended.– Edilson
Sorry, I do not know if it is recommended or not @Edilson, could quote some source, just out of curiosity. Thank you
– Guilherme Nascimento
Because basically it will select everything, which has any value. So it has its own cases to use. Although not an example related to the current question, imagine, a table
usuarios
with a fieldusuario
propertyunique
, and run a query,update usuarios set usuario = 'teste' where true
. For this consultation will fail, because the fieldusuario
has a unique reference, but for a select query, it would return true for any and all values in it.– Edilson
@Edilson you’re reversing logic, I’m sorry, but the case here is not with
WHERE
rather withSELECT
. I think they are two very different situations and the question here talks about 1 in SELECT and not in WHERE. I believe your comment would only be an addition to the use of 1 but is not linked to the situation :)– Guilherme Nascimento
Okay, but it’s well known that one thing leads to another, that’s one of the reasons I made reference to it. Although I have not invented any logic, it is true that they are different situations, although I have already mentioned this also in the other comment.
– Edilson
@Edilson I was referring to the logic of the question and not the code :)
– Guilherme Nascimento
It is also widely used in a
EXISTS
. Example:WHERE
 EXISTS( SELECT 
 1
 FROM
 customers
 WHERE id > 1)
. Just commented above, performance.– Rogers Corrêa