Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude Statement in SQL

Tags:

sql

database

How to exclude data from an SQL database using an SQL statement? My situation is I have a user login to their profile page where they will be able to friend people. I want to display all users except themselves that are found in the SQL database.

like image 644
Rohan Avatar asked Nov 07 '09 15:11

Rohan


4 Answers

Maybe just

SELECT *
FROM 
    Users
WHERE
    UserId <> @ThisUserId

Or using a Difference Union (The EXCEPT keyword in SQL Server, not sure about other RDBMS implementations)

SELECT *
FROM 
    Users

EXCEPT

SELECT *
FROM 
    Users
WHERE
    UserId = @ThisUserId
like image 145
Russ Cam Avatar answered Sep 23 '22 17:09

Russ Cam


How about:

SELECT * FROM people WHERE person_id != $current_user_id
like image 40
AJ. Avatar answered Sep 26 '22 17:09

AJ.


Yes I know Im late with this one.

Anyhow as I stumpled over those comments here while looking for an answer to a question similare to the one ask here ("how to exlcude data from a query") I was a bit confused.

Confused because I knew the answer I was looking for was not only more simple, but even more elegant then the ones proposed here. I once knew the answer, but forgot it. I came here because I was too lazy to remember...

So I struggled hard to remember the easy solution and then it came back to my mind.

So assume you have the two tables "Email" and "UnwantedEmail" with both carring the one column "Address". The query to only get the wanted email addresses, those addresses which are in "Email" but not in "UnwantedEmail" could look like the following:

SELECT Email.Address FROM UnwantedEmail
RIGHT JOIN Email ON UnwantedEmail.Address=Email.Address
WHERE UnwantedEmail.Address Is Null;
like image 45
alk Avatar answered Sep 24 '22 17:09

alk


select * from Foo where UserName not in ('Rohan', 'Rohan's friend', .....)

Is this useful?

like image 31
Saar Avatar answered Sep 25 '22 17:09

Saar