I need to loop through a set of values (less than 10) and see if they are in a table. If so, I need to print out all of the record values, but if the item doesn’t exist, I still want it to be included in the printed result, although with NULL or 0 values. So, for example, the following query returns:
select *
from ACTOR
where ID in (4, 5, 15);
+—-+—————————–+————-+———-+——+
| ID | NAME | DESCRIPTION | ORDER_ID | TYPE |
+—-+—————————–+————-+———-+——+
| 4 | [TEST-1] | | 3 | NULL |
| 5 | [TEST-2] | | 4 | NULL |
+—-+—————————–+————-+———-+——+
But I want it to return
+—-+—————————–+————-+———-+——+
| ID | NAME | DESCRIPTION | ORDER_ID | TYPE |
+—-+—————————–+————-+———-+——+
| 4 | [TEST-1] | | 3 | NULL |
| 5 | [TEST-2] | | 4 | NULL |
| 15| NULL | | 0 | NULL |
+—-+—————————–+————-+———-+——+
Is this possible?
To get the output you want, you first have to construct a derived table containing the
ACTOR.idvalues you desire. UNION ALL works for small data sets:With that, you can OUTER JOIN to the actual table to get the results you want:
If there’s no match between
xanda, theacolumns will be null. So if you want orderid to be zero when there’s no match for id 15: