0

Want a null row where no data exist

Hello. This is in regards to MySQL Workbench 6.3.

I'm trying to return a list of results for every item listed in my select statement, which would include those items that don't actually exist. So if i list 5 items in my select statement and only 3 exist, i'd like to get 5 rows returned, 3 actual rows with data and 2 more rows that only show null. Can someone please show me how to edit my query below to show this ? Thank you !

select emails from table where email in (dog, frog, cat, tiger, lizard);

Actual Result (only the 3 emails that actual exist show)

dog
cat
tiger

Desired Result

dog
null
cat
tiger
null
2
  • why not select emails from table Commented Feb 8, 2019 at 16:04
  • The desired results are not possible.. You can't expect MySQL to return the selected records in the order they went in the IN() operator. Commented Feb 8, 2019 at 16:14

2 Answers 2

1

The desired results are not possible.. You can't expect MySQL to return the selected records in the order they went in the IN() operator.

So i think you better off when you change the desired result to something you know sometiming was not found in the table, i think you are looking for.

Query

 SELECT 
    search_emails.email 
  , (
      CASE
         WHEN t.email IS NOT NULL
         THEN 'true' ELSE 'false' 
      END
    ) AS found
FROM (
  SELECT 'dog' AS email
  UNION
  SELECT 'frog' AS email
  UNION 
  SELECT 'cat' AS email
  UNION 
  SELECT 'tiger' AS email
  UNION 
  SELECT 'lizard' AS email
) AS search_emails 
LEFT JOIN 
 t
ON
 t.email = search_emails.email

Result

| email  | found |
| ------ | ----- |
| dog    | true  |
| cat    | true  |
| tiger  | true  |
| frog   | false |
| lizard | false |

see demo

Sign up to request clarification or add additional context in comments.

Comments

0
select emails from table where email in (dog, frog, cat, tiger, lizard) OR email IS NULL

be sure that the values provided for IN (...) are provided as strings.

4 Comments

why? it's valid SQL. yes "table" is a keyword. but I copied that from the question assuming it is a placeholder
in (dog, frog, cat, tiger, lizard) is not valid SQL.. will give unknown column errors ..
also copied from the question... assuiming they are placeholders
"be sure that the values provided for IN (...) are provided as strings" Besides the query won't generate the non matching results for 'frog' and 'lizard' the added OR will not change that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.