Chapter 17 – Interrogating the Data

"The difference between genius and stupidity is that genius has its limits"

- Albert Einstein

Quiz – What would the Answer be?

Sample_Table

Class_Code

 

Grade_Pt

Fr

 

0

SELECT  Class_Code

,Grade_Pt / (Grade_Pt * 2 ) as Math1

FROM Sample_Table

ORDER BY 1,2 ;

image

Can you guess what would return in the Answer Set?

Use the fake table above called Sample_Table, and try and predict what the Answer will be if this query was running on the system.

Answer to Quiz – What would the Answer be?

Sample_Table

Class_Code

 

Grade_Pt

Fr

 

0

SELECT Class_Code

,Grade_Pt / (Grade_Pt * 2 ) as Math1

FROM Sample_Table

ORDER BY 1,2 ;

image

Can you guess what would return in the Answer Set?

ErrorDivision by zero

You get an error when you DIVIDE by ZERO! Let’s turn the page and fix it!

The NULLIF Command

image

What the NULLIF does is take two values and if they match return a NULL. In the above example, the NULLIF compares the first argument, Grade_Pt, with the second argument, 0, and replaces any zeros with NULL. So, the answer set you’d get from this is a simple ‘ FR’, and then a NULL value represented usually by a ‘? ’. If you have a calculation where a ZERO could kill the operation, and you don’t want that, you can use the NULLIF command to convert any zero value to a NULL value. The NULIF command can also be used to return NULL if any two values match.

Quiz – Fill in the Blank Values in the Answer Set

image

SELECT   NULLIF (Cust_No ,0)          AS Cust_No

,NULLIF (Acc_Balance, 0)   AS Acc_Balance

,NULLIF (Location, 0)          AS Location

FROM Sample_Table ;

image

Fill in the Answer Set above after looking at the table and the query.

Okay! Time to show me your brilliance! What would the Answer Set produce?

Answer to Quiz – Fill in the Blank Values in the Answer Set

image

SELECT   NULLIF (Cust_No, 0)            AS Cust_No

,NULLIF (Acc_Balance, 0)    AS Acc_Balance

,NULLIF (Location, 0)           AS Location

FROM Sample_Table ;

image

Here is the answer set! How’d you do? The NULLIF command found a zero in Cust_No, so it made it NULL. The others were not zero, so they retained their value. The only time NULLIF changes data is if the 1st argument and the 2nd argument are equal, and then it changes it to NULL.

Quiz – Fill in the Answers for the NULLIF Command

image

SELECT  NULLIF(Cust_No, 0)AS Cust1

,NULLIF(Cust_No, 3)AS Cust2

,NULLIF(Acc_Balance, 0)AS Acc1

,NULLIF(Acc_Balance, 3)AS Acc2

,NULLIF(Location, 0)AS Loc1

,NULLIF(Location, 3)AS Loc2

FROM Sample_Table;

image

Fill in the Answer Set above after looking at the table and the query.

As mentioned previously, you can also use the NULLIF() if you are asking Matrix to NULL the answer if the COLUMN matches the number in the parentheses (it doesn’t have to be 0). What would the above Answer Set produce from your analysis?

Quiz – Fill in the Answers for the NULLIF Command

image

SELECT  NULLIF(Cust_No, 0)AS Cust1

,NULLIF(Cust_No, 3)AS Cust2

,NULLIF(Acc_Balance, 0)AS Acc1

,NULLIF(Acc_Balance, 3)AS Acc2

,NULLIF(Location, 0)AS Loc1

,NULLIF(Location, 3)AS Loc2

FROM Sample_Table;

image

Look at the answers above, and if it doesn’t make sense, go over it again until it does.

Quiz – Fill in the Answers for the NULLIF Command

image

SELECT Cust_No, NULLIF(Current_State, Origin_State) as “Mobile Worker State” FROM Sample_Table;

Cust_No

Mobile Worker State

1003

 

1004

 

1005

 

1005

 

Fill in the Answer Set above after looking at the table and the query.

Finally, you can also use the NULLIF() if you are asking Matrix to NULL the answer if the COLUMN matches another COLUMN in the parentheses (it doesn’t have to be a literal number or string). What would the above Answer Set produce from your analysis?

Quiz – Fill in the Answers for the NULLIF Command

image

SELECT Cust_No, NULLIF(Current_State, Origin_State) as “Mobile Worker State” FROM Sample_Table;

Cust_No

Mobile Worker State

1003

NY

1004

?

1005

CT

1005

?

Look at the answers above, and if it doesn’t make sense, go over it again until it does.

The ISNULL, NVL and COALESCE Commands

image

Fill in the Answer Set above after looking at the table and the query.

ISNULL, NVL and COALESCE commands all are synonyms for the same function. These functions take any number of expressions as input and returns the value of the first expression in the list that is not null. If all expressions are null, the result is null. When a non-null value is found, the remaining expressions in the list are not evaluated.

The ISNULL, NVL and COALESCE Commands

image

Fill in the Answer Set above after looking at the table and the query.

The answer set placed a zero in the place of the NULL Acc_Balance, but the other values didn’t change because they were NOT Null. As you probably noticed, these powerful functions can be used in a number of other ways. We’ll show another example in the next slide. Hold onto your seat this is pretty exciting stuff!

The ISNULL, NVL and COALESCE more examples

image

SELECT Last_Name

,COALESCE (Home_Phone, Work_Phone, Cell_Phone) as Phone
FROM Sample_Table ;

Last_Name

Phone     

Fill in the Answer Set above after looking at the table and the query.

Coalesce returns the first non-Null value in a list, and if all values are Null, returns Null. Coalesce is the ANSI compliant name for this function but many legacy databases also support the synonyms NVL and ISNULL for this function.

The COALESCE Answer Set

image

SELECT Last_Name

,COALESCE (Home_Phone, Work_Phone, Cell_Phone) as Phone

FROM Sample_Table ;

Last_Name

Phone    

   Jones

555-1234

   Patel

456-7890

   Gonzales

354-0987

   Nguyen

?

Coalesce returns the first non-Null value in a list, and if all values are Null, returns Null.

The Coalesce Quiz

image

SELECT Last_Name

,COALESCE (Home_Phone, Work_Phone, Cell_Phone, 'No Phone') as Phone

FROM   Sample_Table ;

Last_Name

Phone    

Fill in the Answer Set above after looking at the table and the query.

Coalesce returns the first non-Null value in a list, and if all values are Null, returns Null. Since we decided in the above query we don’t want NULLs, notice we have placed a literal ‘No Phone’ in the list. How will this affect the Answer Set?

Answer – The Coalesce Quiz

image

SELECT Last_Name

,COALESCE (Home_Phone, Work_Phone, Cell_Phone, 'No Phone') as Phone

FROM   Sample_Table ;

Last_Name

Phone    

   Jones

555-1234

   Patel

456-7890

   Gonzales

354-0987

   Nguyen

No Phone

Answers are above! We put a literal in the list so there’s no chance of NULL returning.

The Basics of CAST (Convert And STore)

CAST will convert a column or value’s data type
temporarily into another data type. Below is the syntax:

SELECT CAST(<column-name> AS <data-type>[(<length>)] )

FROM <table-name> ;

Examples using CAST:

CAST ( <smallint-data>  AS   CHAR(5) )        /* convert smallint to character  */

CAST ( <decimal-data>  AS  INTEGER )       /* truncates decimals     */

CAST ( <byteint-data>   AS   SMALLINT )   /* convert binary to smallint    */

CAST ( <char-data>       AS   BYTE (128) )    /* convert character to binary  */

CAST ( <byteint-data>   AS  VARCHAR(5) )  /* convert byteint to character   */

CAST ( <integer-data>   AS  FLOAT )             /* convert integer to float point  */

Data can be converted from one type to another by using the CAST function. As long as the data involved does not break any data rules (i.e. placing alphabetic or special characters into a numeric data type), the conversion works. The name of the CAST function comes from the Convert And STore operation that it performs.

Some Great CAST (Convert And STore) Examples

SELECT   CAST('ABCDE' AS CHAR(1) ) AS Trunc

,CAST(128 AS CHAR(3) )  AS OK

,CAST(127 AS INTEGER )  AS Bigger ;

image

The first CAST truncates the five characters (left to right) to form the single character ‘A’. In the second CAST, the integer 128 is converted to three characters and left justified in the output. The 127 was initially stored in a SMALLINT (5 digits - up to 32767) and then converted to an INTEGER. Hence, it uses 11 character positions for its display, ten numeric digits and a sign (positive assumed) and right justified as numeric.

Some Great CAST (Convert And STore) Examples

SELECT   CAST(121.53 AS SMALLINT)  AS Whole

‚CAST(121.53 AS DECIMAL(3,0)) AS Rounder ;

WholeRounder

_____________

121122

The value of 121.53 was initially stored as a DECIMAL as 5 total digits with 2 of them to the right of the decimal point. Then, it is converted to a SMALLINT using CAST to remove the decimal positions. Therefore, it truncates data by stripping off the decimal portion. It does not round data using this data type. On the other hand, the CAST in the fifth column called Rounder is converted to a DECIMAL as 3 digits with no digits (3,0) to the right of the decimal, so it will round data values instead of truncating. Since .53 is greater than .5, it is rounded up to 122.

Some Great CAST (Convert And STore) Examples

SELECT Order_Number as OrdNo

‚Customer_Number as CustNo

‚Order_Date

‚Order_Total

CAST(Order_Total as integer)            as Chopped

CAST(Order_Total as Decimal(5,0))  as Rounded

FROM Order_Table ;

image

The Column Chopped takes Order_Total (a Decimal (10,2) and CASTs it as an integer which chops off the decimals. Rounded CASTs Order_Total as a Decimal (5,0), which takes the decimals and rounds up if the decimal is .50 or above.

The Basics of the CASE Statements

Sample_Table

Course_NameCredits

_____________________

Tera-Tom on SQL1

SELECT Course_Name

CASE Credits

WHEN 1 THEN 'One Credit'

WHEN 2 THEN 'Two Credits'

WHEN 3 THEN 'Three Credits'

END  AS CreditAlias

FROM  Sample_Table ;

Course_NameCreditAlias

______________________

                                            

Fill in the Answer Set above after looking at the table and the query.

This is a CASE STATEMENT which allows you to evaluate a column in your table, and from that, come up with a new answer for your report. Every CASE begins with a CASE, and they all must end with a corresponding END. What would the answer be?

The Basics of the CASE Statement

Sample_Table

Course_NameCredits

_____________________

Tera-Tom on SQL1

SELECT Course_Name

CASE Credits

WHEN 1 THEN 'One Credit'

WHEN 2 THEN 'Two Credits'

WHEN 3 THEN 'Three Credits'

END  AS CreditAlias

FROM  Sample_Table ;

Course_NameCreditAlias

__________________________

Tera-Tom on SQLOne Credit

This is a CASE STATEMENT which allows you to evaluate a column in your table, and from that, come up with a new answer for your report. Every CASE begins with a CASE, and they all must end with a corresponding END. What would the answer be?

Valued Case Vs. A Searched Case

image

The second example is better unless you have a simple query like the first example.

Quiz - Valued Case Statement

image

Look at the CASE Statement and look at the Course_Table, then fill in the Answer Set.

Answer - Valued Case Statement

image

Above is the full answer set.

Quiz - Searched CASE Statement

image

Look at the CASE Statement and look at the Course_Table, then fill in the Answer Set.

Answer - Searched CASE Statement

image

Above is the full answer.

Quiz - When NO ELSE is present in CASE Statement

image

SELECT Course_Name

,CASE Credits

WHEN 1 THEN 'One Credit'

WHEN 2 THEN 'Two Credits'

WHEN 3 THEN 'Three Credits'

END AS CreditAlias

FROM Sample_Table ;

image

Notice now that we have a 4 under the ‘Credit’ Column. However, in our CASE statement, we don’t have instructions on what to do if the number is 4. What will occur?

Answer - When NO ELSE is present in CASE Statement

image

SELECT Course_Name

,CASE Credits

WHEN 1 THEN 'One Credit'

WHEN 2 THEN 'Two Credits'

WHEN 3 THEN 'Three Credits'

END AS CreditAlias

FROM  Sample_Table ;

image

A null value will occur when the evaluation falls through the case and there is no else statement. Notice above that we have a 4 under the ‘Credit’ Column. However, in our CASE statement, we don’t have instructions on what to do if the number is 4. That is why the null value is in the report.

When an ELSE is present in CASE Statement

image

SELECT Course_Name

,CASE Credits

WHEN 1 THEN 'One Credit'

WHEN 2 THEN 'Two Credits'

WHEN 3 THEN 'Three Credits'

ELSE 'Don"t Know'

END AS CreditAlias

FROM  Sample_Table ;

image

Notice now that we have a 4 under the ‘Credit’ Column. However, in our CASE statement, we don’t have instructions on what to do if the number is 4. What will occur?

Answer - When an ELSE is present in CASE Statement

image

Since our value of 4 fell through the CASE statement, the ELSE statement kicked in and we delivered ‘Don’t Know’. Notice two single quotes that provided the word Don’t.

When an Alias is NOT used in a CASE Statement

image

Notice now that we don’t have an ALIAS for the CASE Statement. What will the system place in there for the Column Title.

Answer - When an Alias is NOT used in a CASE Statement

image

Notice now that we don’t have an ALIAS for the CASE Statement. The title given by default is < CASE Expression >. That is why you should ALIAS your Case statements.

Combining Searched Case and Valued Case

image

This Query above uses both a Valued Case and Searched Case. That’s ALLOWED!

Nested Case

SELECT Last_Name

     ,CASE Class_Code

          WHEN 'JR' THEN 'Jr'

              ||(CASE WHEN Grade_pt < 2 THEN 'Failing'

                   WHEN Grade_pt < 3.5 THEN 'Passing'

                           ELSE 'Exceeding'

                 END)

                     ELSE  'Sr'

                      ||(CASE WHEN Grade_pt < 2 THEN 'Failing'

                            WHEN Grade_pt < 3.5 THEN 'Passing'

                                  ELSE 'Exceeding'

                         END)

      END   AS  Status

FROM Student_Table WHERE Class_Code IN ('JR','SR')

ORDER BY Class_Code, Last_Name;

Last_Name

Status         

 Bond

 Jr Exceeding

 McRoberts

 Jr Failing

 Delaney

 Sr Passing

 Phillips

 Sr Passing

A NESTED Case occurs when you have a Case Statement within another CASE Statement. Notice the Double Pipe symbols (||) that provide Concatenation.

Put a CASE in the ORDER BY

image

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.176.254