Chapter 4. Advanced Queries

Table of Contents
Having a dynamic field value without a lookup table
Handling subqueries with NULL
Joining across databases
Altering table definitions

Having a dynamic field value without a lookup table

You want a "calculated" column returned from a select but joining to a lookup table is either not practical or not desirable.

Solution

Use the CASE...WHEN...ELSE...END structure or write a function ref.

Discussion

Let's say we want to select orders and indicate whether or not they are pending, awaiting payment or complete. Obviously this depends on the dates ordered, delivered and paid but we can't use these to index a lookup table since we don't know what values they will have.

SELECT ord_id, ord_qty,
CASE
WHEN ord_paid IS NOT NULL THEN 'Complete'
WHEN ord_delivered IS NOT NULL THEN 'Awaiting payment'
ELSE 'Pending'
END
AS status
FROM orders;
   

Note that the CASE conditions shortcut - that is the first match is the one returned, others are never tested.

Alternatively, we could write a function taking the two dates and returning the status-text we desire.

SELECT ord_id,ord_qty, status(ord_paid, ord_delivered) FROM orders;

See the reference manuals for how to build such a function.

You should write a function if it is going to be used in several places, otherwise the CASE is good for simple situations.