SQL query with “not exists” not working

[Originally Posted By]: http://stackoverflow.com/questions/18904778/sql-query-with-not-exists-not-working

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!

shareedit

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

shareedit
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s