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.

CREATE Table MyTable(FirstColumn int, SecondColumn int);<br />

INSERT INTO MyTable(FirstColumn,SecondColumn)<br />

VALUES (3,2);<br />

INSERT INTO MyTable(FirstColumn)<br />

VALUES (5);<br />

INSERT INTO MyTable(SecondColumn)<br />

VALUES (7);<br />

Now try the following query:<br />

SELECT FirstColumn, SecondColumn, 10 + (SecondColumn * 1.175) + FirstColumn - 5<br />

FROM MyTable;<br />

The query calculates SecondColumn * 1.175, then adds 10, and then adds the value of FirstColumn<br />

minus 5. You get results that are mostly NULL because of NULL values in FirstColumn or SecondColumn:<br />

FirstColumn SecondColumn 10 + (SecondColumn * 1.175) + FirstColumn - 5<br />

3 2 10.350<br />

5 NULL NULL<br />

NULL 7 NULL<br />

The last column in the first row of the table is calculated like this: 10 + (SecondColumn * 1.175) +<br />

FirstColumn – 5 = 10 + (2 * 1.175) + 3 – 5 = 10 + (2.35) + 3 – 5 = 10.35.<br />

The third column in the second row is calculated like this: 10 + (SecondColumn * 1.175) +<br />

FirstColumn – 5 = 10 + (NULL * 1.175) + 5 – 5 = 10 + (NULL) + 5 – 5 = NULL.<br />

The final answer is NULL because any time NULL data is involved the answer comes out NULL. If you<br />

were asked to compute 1 plus 1, the answer is obviously 2. However, if you were asked to add 1 to some<br />

unknown number, all you can say is that you don’t know — the answer is unknown. Remember, NULL<br />

represents unknown data rather than any specific value.<br />

It’s easy to forget that if NULL is involved at any point in a math calculation, the result always comes out<br />

NULL, so you need to make sure the program using the data can handle NULLs. Otherwise, if the data is<br />

displayed directly to a user, they may wonder what NULL means!<br />

To circumvent these problems, you can choose either to filter out NULL results or to use one of the functions<br />

(discussed shortly) to change NULL to something the end user can understand.<br />

The same problem of unexpected NULL results applies if you use the math functions, such as POWER(),<br />

ABS(), and so on. A NULL value causes the function to return NULL, which propagates to the whole<br />

expression, leaving a final result of NULL.<br />

MyTable is no longer needed and can be dropped from the database:<br />

DROP TABLE MyTable;<br />

Manipulating Data<br />

181

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

Saved successfully!

Ooh no, something went wrong!