Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT that returns list of values not occurring in any row

Tags:

mysql

Query:

select id from users where id in (1,2,3,4,5) 

If the users table contains ids 1, 2, 3, this would return 1, 2, and 3. I want a query that would return 4 and 5. In other words, I don't want the query to return any rows that exist in the table, I want to give it a list of numbers and get the values from that list that don't appear in the table.

(updated to clarify question following several inapplicable answers)

like image 653
Riz Avatar asked Apr 04 '12 14:04

Riz


People also ask

How do you SELECT all records from one table that do not exist in another table SQL?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do I SELECT all rows except one in SQL?

The SQL EXCEPT operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The EXCEPT operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.

Which SQL command returns all records from one table and only matched records from a second table?

Outer joins return all rows from one table and matching rows from the second table.


1 Answers

If you don't want to (explicitly) use temporary tables, this will work:

SELECT id FROM (   (SELECT 1 AS id) UNION ALL   (SELECT 2 AS id) UNION ALL   (SELECT 3 AS id) UNION ALL   (SELECT 4 AS id) UNION ALL   (SELECT 5 AS id) ) AS list LEFT JOIN users USING (id) WHERE users.id IS NULL 

However, it is quite ugly, quite long, and I am dubious about how it would perform if the list of IDs is long.

like image 115
Austin Avatar answered Sep 27 '22 22:09

Austin