20.07.2013 Views

Beginning SQL

Beginning SQL

Beginning SQL

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5<br />

NULLs and Strings<br />

182<br />

NULL data causes unexpected results in strings just as it does in math calculations. This section takes you<br />

through some of the effects of NULL data as it relates to string functions, and the following section looks<br />

at how to deal with it. For example, the following <strong>SQL</strong> uses the CONCAT() function to detail which city a<br />

person lives in:<br />

SELECT FirstName, LastName, City, CONCAT( CONCAT(FirstName,’ ‘),<br />

CONCAT(CONCAT(LastName, ‘ lives in ‘), City))<br />

FROM MemberDetails;<br />

If you’re using MS <strong>SQL</strong> Server or MS Access, the <strong>SQL</strong> is as follows:<br />

SELECT FirstName, LastName, City, FirstName + ‘ ‘ + + LastName + ‘ lives in ‘ +<br />

City<br />

FROM MemberDetails;<br />

Either statement provides the same results, shown here:<br />

FirstName LastName City CONCAT( CONCAT(FirstName,’ ‘),<br />

CONCAT(CONCAT(LastName, ‘ lives in ‘), City))<br />

Katie Smith Townsville Katie Smith lives in Townsville<br />

Steve Gee New Town Steve Gee lives in New Town<br />

John Jones Orange Town John Jones lives in Orange Town<br />

Jenny Jones Orange Town Jenny Jones lives in Orange Town<br />

John Jackson Orange Town John Jackson lives in Orange Town<br />

Jack Johnson Big City Jack Johnson lives in Big City<br />

Seymour Botts Windy Village Seymour Botts lives in Windy Village<br />

Susie Simons Townsville Susie Simons lives in Townsville<br />

Jamie Hills Orange Town Jamie Hills lives in Orange Town<br />

Stuart Dales Windy Village Stuart Dales lives in Windy Village<br />

William Doors Big City William Doors lives in Big City<br />

Doris Night Dover Doris Night lives in Dover<br />

Catherine Hawthorn NULL NULL<br />

Everything’s fine with the results until you hit the last one, which just says NULL, despite the other text<br />

and the fact that FirstName and LastName contain values. The NULL value in City has propagated,<br />

resulting in the whole result being NULL.<br />

The next section looks at how to deal with this problem of NULL propagation to produce a more acceptable<br />

result.

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

Saved successfully!

Ooh no, something went wrong!