Sei sulla pagina 1di 1

110 Chapter 3: Selecting

that isnt NULL. COALESCE will accept two or more parameters but is most
often called with exactly two: a column name and a value to be used when the
column value is NULL. Here is an example that shows how non-NULL values
can be substituted for NULL values in a table:
CREATE TABLE t1 (
key_1 UNSIGNED BIGINT NOT NULL,
non_key_1 VARCHAR ( 100 ) NULL,
non_key_2 TIMESTAMP NULL,
PRIMARY KEY ( key_1 ) );

INSERT t1 VALUES ( 2, NULL, NULL );

SELECT COALESCE ( non_key_1, 'empty' ) AS a,


COALESCE ( non_key_2, CURRENT TIMESTAMP ) AS b
FROM t1;
Heres the result of the SELECT:
a b
======= =======================
'empty' 2003-10-19 15:58:36.176
COALESCE can be used to eliminate the need for IS NOT NULL comparisons
in WHERE clauses. It can also be used to eliminate the need for indicator vari-
ables in application programs by returning only non-NULL values from queries.
This is helpful because NULL values can show up in your result sets even if
every single column in every table is declared as NOT NULL. Thats because
all the OUTER JOIN operators produce NULL values to represent missing
rows.
For example, a query in Section 3.6, Multi-Table Joins, satisfied this
request: Show how many of each kind of shirt were sold to each customer in
Washington, D.C., including combinations of product and customer that had no
sales. The result contained NULL values for customer-product combinations
with no sales. Here is that same query with COALESCE calls to turn NULL
quantity and amount values into zeroes:
SELECT customer.company_name AS company_name,
product.name AS product_name,
product.description AS product_description,
COALESCE (
SUM ( sales_order_items.quantity ),
0.00 ) AS quantity,
COALESCE (
SUM ( product.unit_price
* sales_order_items.quantity ),
0.00 ) AS amount
FROM ( customer
CROSS JOIN product )
LEFT OUTER JOIN
( sales_order
INNER JOIN sales_order_items
ON sales_order_items.id = sales_order.id )
ON customer.id = sales_order.cust_id
AND product.id = sales_order_items.prod_id
WHERE customer.state = 'DC'
AND product.name LIKE '%shirt%'
GROUP BY customer.company_name,
product.name,

Potrebbero piacerti anche