0

I have 2 queries like this:

SELECT c.id FROM component c, base_vee bv
 WHERE
 c.id IN (SELECT component_id FROM registry_row WHERE registry_id = 199) 
 AND
 c.id = bv.component_id
 AND 
 (bv.affidavit IS NULL OR bv.affidavit = '')
SELECT c.id FROM component c, base_vee bv
 WHERE
 c.id IN (SELECT component_id FROM registry_row WHERE registry_id = 199) 
 AND
 c.id = bv.component_id
 AND 
 (bv.affidavit IS NOT NULL AND bv.affidavit != '')

What I need to get is a list of component IDs with False if bv.affidavit is emptyish or True if it's not emptyish.

Right now I'm obviously getting two lists of component IDs for each case.

It works, but one query like described above would be nicer.

asked Nov 25, 2015 at 17:40

2 Answers 2

3

Use the CASE function:

SELECT c.id,
 CASE WHEN COALESCE(bv.affidavit, '') = '' THEN False
 ELSE True
 END
FROM component c, base_vee bv
WHERE c.id IN (SELECT component_id FROM registry_row WHERE registry_id = 199) 
AND c.id = bv.component_id;
answered Nov 25, 2015 at 17:53
2
  • heh. Our answers are basically identical now. Commented Nov 25, 2015 at 17:58
  • Marked your answer over Joishi's answer purely for more readable formatting. ;-) Commented Nov 25, 2015 at 19:00
1

COALESCE will let you get away with a lot of interesting things when you're dealing with the situation of "if it's null do one thing, otherwise do something else"..

SELECT
 c.id, CASE WHEN COALESCE(bv.affidavit, '') = '' THEN FALSE ELSE TRUE END AS emptyish
FROM component c
JOIN base_vee bv ON c.id = bv.component_id
WHERE c.id IN (SELECT component_id FROM registry_row WHERE registry_id = 199)

COALESCE takes the first not-null argument to use, so if bv.affidavit happens to be NULL it will use '' instead.. I shouldn't need to test for it being NOT NULL in the follow up..

answered Nov 25, 2015 at 17:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.