Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with "not exists" not working

Tags:

sql

exists

where

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!

like image 531
markus Avatar asked Sep 19 '13 20:09

markus


People also ask

How not exists works in SQL?

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.

How do you check if record not exists in SQL?

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.

What to use instead of not exists in SQL?

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.

When to use not in and not exists in SQL?

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.


1 Answers

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

like image 55
Robert Avatar answered Sep 20 '22 02:09

Robert