20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The COALESCE() Function<br />

The COALESCE() function returns the first non-NULL value from the list of values passed to it as arguments.<br />

If all the arguments are NULL, then the function passes back NULL. Note that MS Access does not<br />

support the COALESCE() function.<br />

The following is the basic syntax for the COALESCE() function:<br />

COALESCE(first_expression, second_expression,.....,last_expression)<br />

Note that each argument passed to COALESCE() must be either the same data type (a string or number)<br />

or one that can be converted. If you get an error when passing different data types as arguments, then<br />

use the CAST() function discussed earlier in the chapter to explicitly convert to the same data type.<br />

For example, to return either a city name or Not Known, you would use COALESCE() as shown below:<br />

SELECT City, COALESCE(City, ‘Not Known’)<br />

FROM MemberDetails;<br />

Executing the query provides the following results:<br />

City COALESCE(City,’Not Known’)<br />

Townsville Townsville<br />

New Town New Town<br />

Orange Town Orange Town<br />

Orange Town Orange Town<br />

Orange Town Orange Town<br />

Big City Big City<br />

Windy Village Windy Village<br />

Townsville Townsville<br />

Orange Town Orange Town<br />

Windy Village Windy Village<br />

Big City Big City<br />

Dover Dover<br />

NULL Not Known<br />

Manipulating Data<br />

If you use the COALESCE() function with the earlier example, instead of getting NULL results, you get<br />

something a little more user-friendly — that is, a sentence rather than just Not Known. The MS <strong>SQL</strong><br />

Server version of the query is as follows:<br />

183

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!