A clever requirement!
In DB2 for i (formerly known as DB2/400), you can use a technique called "scalar subquery" with a UNION operator to achieve this. Here's the query pattern:
SELECT
COALESCE((SELECT your_column
FROM your_table
WHERE your_conditions), 'ERR') AS your_column
FROM SYSIBM.SYSDUMMY1;
Let's break it down:
SYSIBM.SYSDUMMY1 is a special virtual table in DB2 for i that always contains 1 row (and 1 column, IBMREQD with a value of 'Y'). Think of it as a "dummy" table to anchor our query.
- The scalar subquery
(SELECT your_column FROM your_table WHERE your_conditions) is executed first. If your WHERE condition finds a matching row, its value is returned.
- If the subquery finds no rows (i.e., your
WHERE condition doesn't match anything), it returns NULL.
COALESCE() function returns the first non-NULL value from the list of arguments. If the subquery returns NULL (meaning no rows found), COALESCE() will return the second argument, 'ERR'.
Here's a concrete example:
-- Let's assume we have a table EMPLOYEE with column NAME
SELECT
COALESCE((SELECT NAME
FROM EMPLOYEE
WHERE ID = 99999), 'ERR') AS RESULT
FROM SYSIBM.SYSDUMMY1;
In this case:
- If there's an employee with
ID = 99999, the query returns that employee's NAME.
- If no employee has
ID = 99999, the subquery returns NULL, and COALESCE() returns 'ERR'.
The key benefits:
- You always get 1 row in the result set, even if the
WHERE condition doesn't match any rows.
- If no rows are found, the result set contains
'ERR' in the column.
Alternative approach using VALUES
If you prefer a more concise syntax, you can use the VALUES statement:
VALUES (COALESCE((SELECT your_column
FROM your_table
WHERE your_conditions), 'ERR'));
This does essentially the same thing as the previous example, but:
VALUES is used to construct a result set with 1 row and 1 column.
- The
COALESCE() logic remains the same.
Both approaches work on DB2 for i (V7R1 and later). Choose the one you find more readable.
Happy querying!