I'm trying to use a simple query but I'm not getting anywhere. The objective is to "learn" how "not exists" works. I have a simple table with "idUsuario" as default ID for users and a name.
SELECT * FROM usuario
WHERE NOT EXISTS (
SELECT * FROM usuario
WHERE u.idUsuario =16
)
Here i'm trying to get ALL the users from the table where the ID IS NOT 16. But it just get all of them.. What am I doing wrong?
Thanks in advance!
The SQL NOT EXISTS Operator will perform quite opposite to the EXISTS Operator. It is helpful in restricting the number of rows returned by the SELECT Statement. The NOT EXISTS in SQL Server will check the Subquery for rows existence. If there are no rows then it will return TRUE, otherwise FALSE.
The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.
Using Joins Instead of IN or EXISTS An alternative for IN and EXISTS is an INNER JOIN, while a LEFT OUTER JOIN with a WHERE clause checking for NULL values can be used as an alternative for NOT IN and NOT EXISTS.
The most important thing to note about NOT EXISTS and NOT IN is that, unlike EXISTS and IN, they are not equivalent in all cases. Specifically, when NULLs are involved they will return different results. To be totally specific, when the subquery returns even one null, NOT IN will not match any rows.
You should join result from your query with result from the subquery as below
SELECT * FROM usuario u
WHERE NOT EXISTS (
SELECT * FROM usuario u1
WHERE u1.idUsuario = u.idUsuario
and u1.idUsuario =16
)
SQL Fiddle DEMO
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