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.

Converting Different Data Types<br />

This section examines how to convert from one data type to another, such as from characters to numbers<br />

or from dates to strings, and so on. For example, if you want to form a sentence that includes a column<br />

defined as a numerical data type, then you should convert the data from numerical to character.<br />

Often the database system converts data types without needing to be asked. Take a look at the following<br />

example:<br />

SELECT ZipCode, MemberId, ZipCode / MemberId<br />

FROM MemberDetails;<br />

Manipulating Data<br />

Given that ZipCode is actually a string, dividing it by MemberId surely shouldn’t work, right? In fact, it<br />

does, as the following results show:<br />

ZipCode MemberId ZipCode / MemberId<br />

123456 1 123456<br />

65423 3 21807<br />

99112 4 24778<br />

88776 5 17755<br />

88776 6 14796<br />

88992 7 12713<br />

34566 8 4320<br />

65422 9 7269<br />

123456 10 12345<br />

88776 11 8070<br />

65422 12 5451<br />

34512 13 2654<br />

68122 14 4865<br />

NULL 15 NULL<br />

The query works because although the ZipCode column was defined as a character data type, the values<br />

stored in ZipCode are digits, and the database system can convert them into a number. It does this<br />

conversion without being told to.<br />

However, there are times when you might want to specify the conversion yourself, where, for example,<br />

it’s not obvious what data type the system should convert to. Alternatively, the system could fail to convert;<br />

for example, if you’re using IBM’s DB2, the preceding <strong>SQL</strong> example fails because you need to tell it<br />

to convert ZipCode into a number. Some database systems are more helpful and convert the data for<br />

you. Others, like DB2, require you to do the conversion yourself. In this situation, you need to convert to<br />

a specific data type using the CAST() function.<br />

179

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

Saved successfully!

Ooh no, something went wrong!