Pretice Hall © 20041 COS 346 Day 12. Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1...

86
Pretice Hall © 2004 1 COS 346 COS 346 Day 12 Day 12
  • date post

    22-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    0

Transcript of Pretice Hall © 20041 COS 346 Day 12. Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1...

Pretice Hall © 2004 1

COS 346COS 346

Day 12Day 12

Pretice Hall © 2004 2

AgendaAgenda• Questions?Questions?• Quiz 1 correctedQuiz 1 corrected

– 1 A, 5 B’s, 1 C and 1 F 1 A, 5 B’s, 1 C and 1 F • Assignment 4 CorrectedAssignment 4 Corrected

– 2 A’s, 3 B’s, 2 C’s and 2 0’s for cheating (subject to appeal)2 A’s, 3 B’s, 2 C’s and 2 0’s for cheating (subject to appeal)• Assignment 5 PostedAssignment 5 Posted

– Due March 20 (right After Break)Due March 20 (right After Break)• Assignment 6 will be posted by March 20Assignment 6 will be posted by March 20• Capstone Project Proposals Due Capstone Project Proposals Due

– Must be a database project Must be a database project – Only received one so farOnly received one so far

• More on SQL & SQL ServerMore on SQL & SQL Server– We do chap 3-10 in SQL Text next We do chap 3-10 in SQL Text next – About 1 week behind schedule About 1 week behind schedule

Pretice Hall © 2004 3

CheatingCheating

• As Defined by UMFK Policy As Defined by UMFK Policy

Pretice Hall © 2004 4

CheatingCheating

• As Defined by UMFK Policy As Defined by UMFK Policy

Pretice Hall © 2004 5

SanctionsSanctions

First Time Offense

Multiple Offenses

Pretice Hall © 2004 6

My PolicyMy Policy

•Sharing of homework is cheating.

•Having another student check your homework is cheating.

•Tutoring without instructor’s consent is cheating.

•Collaboration is an exchange of ideas, exchanging information on graded work is cheating

Pretice Hall © 2004 7

Assignment 4Assignment 4

NOTE: DISCOUNT_AWARD is a weak, but not ID-DEPENDENT entity

I:SDD:NOAU:NOA

I:R

D:CU:C

I:SDD:NOAU:C

I:SD

D:CU:NOA

I:SD

D:NOAU:NOA

CUSTOMER

CustomerSK: int IDENTITY(10000,50)

Phone: char(12) NOT NULLEmail: char(100) NULLFirstName: char(25) NOT NULLLastName: char(25) NOT NULL

ORDER

InvoiceNumber: int NOT NULL

Date: datetime NULLCustomerSK: int NOT NULL (FK)Subtotal: numeric(8,2) NULLDiscount: int NULLSubtotalAfterDiscount: int NULLTax: numeric(8,2) NULLTotal: numeric(8,2) NULL

ORDER_ITEM

InvoiceNumber: int NOT NULL (FK)ItemNumber: int NOT NULL

Qty: int NOT NULLService: int NOT NULL (FK)UnitPrice: numeric(8,2) NULLExtendedPrice: numeric(8,2) NULL

SERVICE

Service: int NOT NULL

Description: char(50) NOT NULLUnitPrice: numeric(8,2) NOT NULL

DISCOUNT_AWARD

AwardID: int NOT NULL

StartCountDate: datetime NULLOrderCount: int NULLCustomerSK: int NOT NULL (FK)AwardDate: datetime NULL

Pretice Hall © 2004 8

Chapter 3: Single Table Chapter 3: Single Table Query BasicsQuery Basics

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Pretice Hall © 2004 9

OBJECTIVESOBJECTIVES

•Write simple SELECT statements.Write simple SELECT statements.•Learn to use the CAST and CONVERT commands to Learn to use the CAST and CONVERT commands to format columnar output.format columnar output.•Eliminate duplicate rows with the DISTINCT clause.Eliminate duplicate rows with the DISTINCT clause.•Use the WHERE clause to specify selection criteria and Use the WHERE clause to specify selection criteria and conditions.conditions.•Order rows with the ORDER BY clause.Order rows with the ORDER BY clause.•Display a TOP few rows from the result table.Display a TOP few rows from the result table.•Save the output of a query INTO a temporary table.Save the output of a query INTO a temporary table.

Pretice Hall © 2004 10

SIMPLE SELECT STATEMENTSSIMPLE SELECT STATEMENTS

• The main element in a SQL query is the SELECT The main element in a SQL query is the SELECT statement. statement.• A properly written SELECT statement will always A properly written SELECT statement will always produce a result in the form of one or more rows of produce a result in the form of one or more rows of output.output.• The SELECT statement chooses (select)The SELECT statement chooses (select) rows rows from one or more tables according to specific from one or more tables according to specific criteria. criteria.

Pretice Hall © 2004 11

ExampleExample

SELECT *SELECT *FROM employee;FROM employee;

emp_ssn emp_last_name emp_first_name emp_middle_nameemp_ssn emp_last_name emp_first_name emp_middle_name

--------- --------------- ---------------- ------------------------ --------------- ---------------- ---------------

99111111 Bock Douglas B99111111 Bock Douglas B

999222222 Amin Hyder NULL999222222 Amin Hyder NULL

999333333 Joshi Dinesh Null 999333333 Joshi Dinesh Null

more rows and columns will be displayed…more rows and columns will be displayed…

– This query selects rows from the “employee” This query selects rows from the “employee” table.table.– The asterisk (*) tells Oracle to select (display) all The asterisk (*) tells Oracle to select (display) all columns contained in the table “employee”. columns contained in the table “employee”.

Pretice Hall © 2004 12

Example Contd.Example Contd.

•The following SELECT statement produces an The following SELECT statement produces an identical output.identical output.

SELECT emp_ssn, emp_last_name, emp_first_name, emp_middle_name, emp_address, emp_city, emp_state, emp_zip, emp_date_of_birth, emp_salary, emp_parking_space, emp_gender,

emp_dpt_number, emp_superssn

FROM employee;

Note that a comma separates each column name. This syntax is required. The SELECT statement also specifies a table name in the FROM clause. Finally, the semicolon at the end of the query, which is optional in T-SQL, indicates that this is the end of the query.

Pretice Hall © 2004 13

• SQL Server will process the query regardless of SQL Server will process the query regardless of whether you type the entire query on one line, or whether you type the entire query on one line, or indent.indent.

• There are no rules about how many words can There are no rules about how many words can be put on a line or where to break a line. be put on a line or where to break a line.

• Although SQL Server does not require Although SQL Server does not require indenting, indenting enhances readability. indenting, indenting enhances readability.

• You must, however, follow the order of the You must, however, follow the order of the syntax of the SELECT statement shown on the syntax of the SELECT statement shown on the next slide.next slide.

Indenting SQL CodeIndenting SQL Code

Pretice Hall © 2004 14

• The following keywords (which constitute the The following keywords (which constitute the order of the syntax of a SELECT statement) are order of the syntax of a SELECT statement) are your signal to start a new line.your signal to start a new line.

» SELECTSELECT

» FROMFROM

» WHEREWHERE

» GROUP BYGROUP BY

» HAVINGHAVING

» ORDER BY ORDER BY

Indenting SQL Code Contd.Indenting SQL Code Contd.

Pretice Hall © 2004 15

• Specify the column names you want displayed in Specify the column names you want displayed in the result set by typing the exact, complete the result set by typing the exact, complete column names. column names.

• Separate each column name with a comma (,).Separate each column name with a comma (,).• The column names selected must belong to the The column names selected must belong to the

table(s) named in the FROM clause. table(s) named in the FROM clause. • Although we use a semicolon to mark the end of Although we use a semicolon to mark the end of

a query in almost all the examples in this book, a query in almost all the examples in this book, the semicolon at the end of the query is the semicolon at the end of the query is optionaloptional in T-SQL (versus required when using SQL for in T-SQL (versus required when using SQL for other databases such as Oracle). other databases such as Oracle).

Selecting Specific ColumnsSelecting Specific Columns

Pretice Hall © 2004 16

• At times you will write a query where the At times you will write a query where the columnar output will not fit onto a single display columnar output will not fit onto a single display line (and may ‘wrap’ around).line (and may ‘wrap’ around).

• You can clean up the result table for such a query You can clean up the result table for such a query by modifying the output display size of specific by modifying the output display size of specific columns. columns.

• In SQL Server you can reformat the column In SQL Server you can reformat the column output with automatic data type conversion by output with automatic data type conversion by using the CAST and CONVERT functions in the using the CAST and CONVERT functions in the SELECT statement. SELECT statement.

Formatting Default OutputFormatting Default Output

Pretice Hall © 2004 17

• Using the CAST FunctionUsing the CAST Function

SELECT emp_ssn, SELECT emp_ssn, CASTCAST(emp_last_name As CHAR(12)), (emp_last_name As CHAR(12)), CASTCAST(emp_first_name As CHAR(12)), (emp_first_name As CHAR(12)),

CASTCAST(emp_date_of_birth As CHAR(12)), (emp_date_of_birth As CHAR(12)), emp_superssnemp_superssn

FROM employee;FROM employee;

emp_ssn emp_superssn emp_ssn emp_superssn ----------- ----------- ---------- --------------- --------------- ----------- ----------- ---------- --------------- --------------- 999111111 Bock Douglas Dec 5 1950 999444444999111111 Bock Douglas Dec 5 1950 999444444999222222 Amin Hyder Mar 29 1969 999555555999222222 Amin Hyder Mar 29 1969 999555555999333333 Joshi Dinesh Sep 15 1972 999444444999333333 Joshi Dinesh Sep 15 1972 999444444more rows will be displayed…more rows will be displayed…

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 18

• Using the CAST Function (Renaming Column Using the CAST Function (Renaming Column Names)Names)

SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "Last Name","Last Name", CAST(emp_first_name As CHAR(12)) CAST(emp_first_name As CHAR(12)) "First Name","First Name",

CAST(emp_date_of_birth As CHAR(12)) CAST(emp_date_of_birth As CHAR(12)) "Date of Birth""Date of Birth", , emp_superssn emp_superssn "Supervisor_SSN""Supervisor_SSN"

FROM employee;FROM employee;

emp_ssn Last Name First Name Date of Birth Supervisor_SSN emp_ssn Last Name First Name Date of Birth Supervisor_SSN ----------- ------------ ------------- --------------- ------------------ ----------- ------------ ------------- --------------- ------------------ 999111111 Bock Douglas Dec 5 1950 999444444999111111 Bock Douglas Dec 5 1950 999444444999222222 Amin Hyder Mar 29 1969 999555555999222222 Amin Hyder Mar 29 1969 999555555999333333 Joshi Dinesh Sep 15 1972 999444444999333333 Joshi Dinesh Sep 15 1972 999444444more rows will be displayed…more rows will be displayed…

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 19

When labeling or renaming display When labeling or renaming display columns from the default column columns from the default column names, be sure to follow these rules:names, be sure to follow these rules:

• Enclose the label in quotes, either single or Enclose the label in quotes, either single or double. double.

• Do Do NOTNOT separate the label from the separate the label from the expression with a comma.expression with a comma.

• The label must follow the function or The label must follow the function or column name.column name.

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 20

Using the CONVERT FunctionUsing the CONVERT Function

• Apart from the CAST function, you can Apart from the CAST function, you can also use the CONVERT function, which also use the CONVERT function, which provides some additional features for provides some additional features for formatting the output of formatting the output of numeric numeric columns.columns.

• Both CONVERT and CAST functions are Both CONVERT and CAST functions are discussed further in Chapter 9.discussed further in Chapter 9.

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 21

• Using the CONVERT FunctionUsing the CONVERT Function

SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name",

CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", emp_salary

FROM employee;

emp_ssn First Name Last Name Date of Birth emp_salary ---------- ------------- ------------- ---------------- -------------- 999111111 Bock Douglas Dec 5 1950 30000.0000999222222 Amin Hyder Mar 29 1969 25000.0000999333333 Joshi Dinesh Sep 15 1972 38000.0000

Formatting Default OutputFormatting Default Output Contd. Contd.

Pretice Hall © 2004 22

• Using the CONVERT FunctionUsing the CONVERT Function

SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name",

CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", CONVERT (CHAR (10), emp_salary, 1) "Salary"

FROM employee;

emp_ssn First Name Last Name Date of Birth Salary ---------- ------------- ------------- ---------------- -------------- 999111111 Bock Douglas Dec 5 1950 30,000.00999222222 Amin Hyder Mar 29 1969 25,000.00999333333 Joshi Dinesh Sep 15 1972 38,000.00

Formatting Default Output Formatting Default Output Contd.Contd.

Pretice Hall © 2004 23

Using the CONVERT FunctionUsing the CONVERT Function

• As shown in the previous example, the As shown in the previous example, the reformatted reformatted emp_salaryemp_salary data now has only two data now has only two digits to the right of the decimal point and digits to the right of the decimal point and includes a comma for every three digits to the includes a comma for every three digits to the left of the decimal point. left of the decimal point.

• This was achieved by setting the This was achieved by setting the style style parameter parameter value of the CONVERT function to “1”. value of the CONVERT function to “1”.

• Also, the column heading label was changed to Also, the column heading label was changed to read read SalarySalary instead of the default column name instead of the default column name ((emp_salaryemp_salary).).

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 24

Using the CONVERT FunctionUsing the CONVERT Function

• We can improve the output for the We can improve the output for the salarysalary column column even further if we place a dollar sign ($) in front even further if we place a dollar sign ($) in front of the values for the employee salary figures. of the values for the employee salary figures.

• As shown in the next slide, this result is achieved As shown in the next slide, this result is achieved by including a constant character “$” as a column by including a constant character “$” as a column name in the SELECT statement and name in the SELECT statement and concatenating concatenating this column with the this column with the salarysalary column. The “+” sign is the concatenation column. The “+” sign is the concatenation symbol. symbol.

Formatting Default Output Contd.Formatting Default Output Contd.

Pretice Hall © 2004 25

Using the CONVERT FunctionUsing the CONVERT Function

SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "First Name", CAST(emp_first_name As CHAR(12)) "Last Name",

CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", '$' + CONVERT (CHAR (10), emp_salary, 1) "Salary"

FROM employee;

emp_ssn First Name Last Name Date of Birth Salary ---------- ------------- ------------- ---------------- --------------- 999111111 Bock Douglas Dec 5 1950 $ 30,000.00999222222 Amin Hyder Mar 29 1969 $ 25,000.00999333333 Joshi Dinesh Sep 15 1972 $ 38,000.00

Formatting Default Output Formatting Default Output Contd.Contd.

Pretice Hall © 2004 26

• Although SQL is a free-form language, Although SQL is a free-form language, there are still syntactical rules that must be there are still syntactical rules that must be followed or you will receive an error followed or you will receive an error message instead of the desired result table. message instead of the desired result table.

• SQL Server will display some error SQL Server will display some error message indicating the possible cause of message indicating the possible cause of error and the line number (in your query) error and the line number (in your query) where the error has occurred. where the error has occurred.

Common ErrorsCommon Errors

Pretice Hall © 2004 27

Invalid Column NameInvalid Column Name

• In this SELECT statement, the employee social In this SELECT statement, the employee social security number column name is spelled security number column name is spelled incorrectly.incorrectly.

SELECT emp_socsecnoSELECT emp_socsecno

FROM employee;FROM employee;

Server: Msg 207, Level 16, State 3, Line 1Server: Msg 207, Level 16, State 3, Line 1

Invalid column name ‘emp_socsecno’.Invalid column name ‘emp_socsecno’.

Pretice Hall © 2004 28

FROM Keyword MissingFROM Keyword Missing

• The next SELECT statement is missing the FROM The next SELECT statement is missing the FROM clause so that no table name has been specified.clause so that no table name has been specified.

• Without a table name, the DBMS does not know Without a table name, the DBMS does not know which table to query.which table to query.

SELECT emp_ssn;SELECT emp_ssn;

Server: Msg 207, Level 16, State 3, Line 1Server: Msg 207, Level 16, State 3, Line 1

Invalid column name ‘emp_ssn’.Invalid column name ‘emp_ssn’.

Pretice Hall © 2004 29

Invalid Command StructureInvalid Command Structure

• You must follow the syntax order of the SELECT You must follow the syntax order of the SELECT statement correctly. statement correctly.

• In the example below, the order of the SELECT In the example below, the order of the SELECT and FROM clauses is reversed. SQL Server and FROM clauses is reversed. SQL Server simply returns an ‘incorrect syntax’ error message.simply returns an ‘incorrect syntax’ error message.

FROM employee SELECT emp_ssn;FROM employee SELECT emp_ssn;

Server: Msg 156, Level 15, State 1, Line 1Server: Msg 156, Level 15, State 1, Line 1Incorrect syntax near the keyword 'FROM'.Incorrect syntax near the keyword 'FROM'.

Pretice Hall © 2004 30

Errors in Placing CommasErrors in Placing Commas• Must have a comma between column names in the Must have a comma between column names in the

SELECT clauseSELECT clause

SELECT emp_ssn, emp_last_name SELECT emp_ssn, emp_last_name emp_first_nameemp_first_nameFROM employee;FROM employee;emp_ssn emp_ssn emp_first_name emp_first_name ----------- ------------------------- ----------- ------------------------- 999111111 Bock999111111 Bock999222222 Amin999222222 Amin999333333 Joshi999333333 Joshimore rows will be displayed…more rows will be displayed…

Pretice Hall © 2004 31

Errors in Placing Commas Errors in Placing Commas Contd.Contd.

• Must Must notnot have a comma after the last have a comma after the last column names in the SELECT clausecolumn names in the SELECT clause

SELECT emp_ssn, emp_last_name, SELECT emp_ssn, emp_last_name, emp_first_name,emp_first_name,

FROM employee;FROM employee;

Server: Msg 156, Level 15, State 1, Line 2Server: Msg 156, Level 15, State 1, Line 2Incorrect syntax near the keyword 'FROM'.Incorrect syntax near the keyword 'FROM'.

Pretice Hall © 2004 32

THE DISTINCT CLAUSETHE DISTINCT CLAUSESQL Server provides a means for eliminating duplicate rows SQL Server provides a means for eliminating duplicate rows

in a result table through use of the DISTINCT keyword .in a result table through use of the DISTINCT keyword .

SELECT emp_salarySELECT emp_salaryFROM employee;FROM employee;emp_salary emp_salary --------------------30000.000030000.000025000.000025000.000038000.000038000.000043000.000043000.000043000.000043000.000055000.000055000.000025000.000025000.000025000.000025000.0000(8 row(s) affected)(8 row(s) affected)

SELECT DISTINCT emp_salarySELECT DISTINCT emp_salaryFROM employee;FROM employee; emp_salary emp_salary --------------------25000.000025000.000030000.000030000.000038000.000038000.000043000.000043000.000055000.000055000.0000(5 row(s) affected)(5 row(s) affected)

Pretice Hall © 2004 33

THE DISTINCT CLAUSE Contd.THE DISTINCT CLAUSE Contd.The DISTINCT keyword also eliminates duplicate rows The DISTINCT keyword also eliminates duplicate rows

where more than one column is displayed in the result table.where more than one column is displayed in the result table.

SELECT room_id, bed_type_id SELECT room_id, bed_type_id FROM bed;FROM bed;room_id bed_type_id room_id bed_type_id ------- ----------- ------- ----------- SW1001 R1SW1001 R1SW1002 R1SW1002 R1SW1003 R2SW1003 R2....

SW1010 R1SW1010 R1SW1010 R2SW1010 R2SW1011 R2SW1011 R2SW1011 R2SW1011 R2SW1012 R1SW1012 R1(98 row(s) affected)(98 row(s) affected)

SELECT DISTINCT room_id, SELECT DISTINCT room_id, bed_type_id bed_type_id

FROM bed;FROM bed;room_id bed_type_id room_id bed_type_id ------- ----------- ------- ----------- . . .. . .SW1001 R1SW1001 R1SW1002 R1SW1002 R1SW1003 R1SW1003 R1. . .. . .SW1004 R2SW1004 R2SW1005 R2SW1005 R2SW1006 R1SW1006 R1SW1006 R2SW1006 R2SW1010 RESW1010 RESW1011 R2SW1011 R2SW1012 R1SW1012 R1(65 row(s) affected) (65 row(s) affected)

Pretice Hall © 2004 34

THE WHERE CLAUSETHE WHERE CLAUSE

• Specific Specific rowsrows can be selected by adding a WHERE can be selected by adding a WHERE clause to the SELECT query.clause to the SELECT query.

SELECT emp_ssn, emp_last_name, emp_first_name, SELECT emp_ssn, emp_last_name, emp_first_name, emp_salaryemp_salary

FROM employeeFROM employeeWHERE emp_salary >= 35000; WHERE emp_salary >= 35000; emp_ssn emp_last_name emp_first_name emp_salary emp_ssn emp_last_name emp_first_name emp_salary

------- ------------- -------------- ---------- ------- ------------- -------------- ---------- 999333333 Joshi Dinesh 38000.0000999333333 Joshi Dinesh 38000.0000999444444 Zhu Waiman 43000.0000999444444 Zhu Waiman 43000.0000999555555 Joyner Suzanne 43000.0000999555555 Joyner Suzanne 43000.0000999666666 Bordoloi Bijoy 55000.0000999666666 Bordoloi Bijoy 55000.0000

Pretice Hall © 2004 35

Comparison OperatorsComparison Operators

Operator MeaningOperator Meaning == equal toequal to << less thanless than >> greater thangreater than >=>= greater than or equal togreater than or equal to <=<= less than or equal toless than or equal to !=!= not equal tonot equal to <><> not equal to not equal to !>!> not greater thannot greater than !<!< not less thannot less than

Pretice Hall © 2004 36

Comparing Character DataComparing Character Data

• Comparison operators are not limited to numeric data.Comparison operators are not limited to numeric data.• They can also be used with columns containing They can also be used with columns containing

character data. character data. • If the value is a character string or date, you must If the value is a character string or date, you must

surround the value (string of characters) with which a surround the value (string of characters) with which a column is being compared with column is being compared with single quotation single quotation (' ')(' ') marks.marks.

SELECT emp_ssn, emp_last_name, emp_first_nameSELECT emp_ssn, emp_last_name, emp_first_name

FROM employeeFROM employee

WHERE emp_gender = ‘M’; WHERE emp_gender = ‘M’;

Pretice Hall © 2004 37

Comparing Character DataComparing Character Data

• You can also write SELECT statements that use operators other You can also write SELECT statements that use operators other than the equal signthan the equal sign. .

SELECT emp_last_name, emp_first_nameSELECT emp_last_name, emp_first_nameFROM employeeFROM employeeWHERE emp_last_name >= 'J';WHERE emp_last_name >= 'J';

emp_last_name emp_first_name emp_last_name emp_first_name ------------------------- ------------------------- ------------------------- ------------------------- Joshi DineshJoshi DineshZhu WaimanZhu WaimanJoyner SuzanneJoyner SuzanneMarkis MarciaMarkis MarciaPrescott SherriPrescott Sherri

Pretice Hall © 2004 38

Comparison Operators in the WHERE ClauseComparison Operators in the WHERE Clause

• When you use comparison operators in a When you use comparison operators in a WHERE clause, the arguments (objects or WHERE clause, the arguments (objects or values you are comparing) on both sides of values you are comparing) on both sides of the operator must be either the operator must be either a column name, a column name, or a specific valueor a specific value. If a specific value is . If a specific value is specified, then the value must be either a specified, then the value must be either a numeric value or a literal, character string.numeric value or a literal, character string.

Pretice Hall © 2004 39

Comparison Operators in the Comparison Operators in the WHERE Clause Contd.WHERE Clause Contd.

SELECT emp_ssn, emp_last_name, emp_first_nameSELECT emp_ssn, emp_last_name, emp_first_nameFROM employeeFROM employeeWHERE emp_gender = M; WHERE emp_gender = M;

ERROR at line 3: ERROR at line 3: ORA-00904: invalid column name ORA-00904: invalid column name

• Since the literal string value was not enclosed by single Since the literal string value was not enclosed by single quote marks, SQL Server assumed the letter M to be a quote marks, SQL Server assumed the letter M to be a column name.column name.

• There is no column named M in the table so an error There is no column named M in the table so an error was returned. was returned.

Pretice Hall © 2004 40

THE ORDER BY CLAUSETHE ORDER BY CLAUSE

• Output from a SELECT statement can be sorted by using the Output from a SELECT statement can be sorted by using the optional ORDER BY clause. optional ORDER BY clause.

SELECT emp_last_name, emp_first_nameSELECT emp_last_name, emp_first_nameFROM employeeFROM employeeWHERE emp_last_name >= 'J'WHERE emp_last_name >= 'J'ORDER BY emp_last_name;ORDER BY emp_last_name;

emp_last_name emp_first_name emp_last_name emp_first_name ------------------------- ------------------------- ------------------------- ------------------------- Joshi DineshJoshi DineshJoyner SuzanneJoyner SuzanneMarkis MarciaMarkis MarciaPrescott SherriPrescott SherriZhu Waiman Zhu Waiman

Pretice Hall © 2004 41

ORDER BY With ASC and DESCORDER BY With ASC and DESC

• By default, the ORDER BY clause sorts output rows in By default, the ORDER BY clause sorts output rows in a result table in ascending order. a result table in ascending order.

• To sort columns from high to low, or descending, an To sort columns from high to low, or descending, an optional keyword DESC must be specified.optional keyword DESC must be specified. ASC - Ascending, low to high.ASC - Ascending, low to high. DESC - Descending, high to low. DESC - Descending, high to low.

When ASC or DESC is used, it must be followed by the When ASC or DESC is used, it must be followed by the column name.column name.

You can include a maximum of You can include a maximum of 16 column16 column names in the names in the ORDER BY clause. ORDER BY clause.

Pretice Hall © 2004 42

ORDER BY With ASC and DESC ORDER BY With ASC and DESC Contd.Contd.

• When ASC or DESC is used, it must be When ASC or DESC is used, it must be followed by the column name.followed by the column name.

SELECT emp_last_name, emp_first_name, emp_salary SELECT emp_last_name, emp_first_name, emp_salary

FROM employeeFROM employee

WHERE emp_salary > 35000WHERE emp_salary > 35000

ORDER BY ORDER BY DESCDESC emp_salary; emp_salary;

Server: Msg 156, Level 15, State 1, Line 4Server: Msg 156, Level 15, State 1, Line 4

Incorrect syntax near the keyword 'DESC'.Incorrect syntax near the keyword 'DESC'.

Pretice Hall © 2004 43

ORDER BY With More Than One ColumnORDER BY With More Than One Column

• Sorting by multiple columns can improve the look and usability of Sorting by multiple columns can improve the look and usability of the information.the information.

SELECT emp_dpt_number, emp_last_name, emp_first_nameSELECT emp_dpt_number, emp_last_name, emp_first_nameFROM employeeFROM employeeORDER BY emp_dpt_number ORDER BY emp_dpt_number DESCDESC, emp_last_name;, emp_last_name;

emp_dpt_number emp_last_name emp_first_name emp_dpt_number emp_last_name emp_first_name

-------------- ------------------ -------------------- -------------- ------------------ -------------------- 7 Bock Douglas7 Bock Douglas7 Joshi Dinesh7 Joshi Dinesh7 Prescott Sherri7 Prescott Sherri7 Zhu Waiman7 Zhu Waiman3 Amin Hyder3 Amin Hyder3 Joyner Suzanne3 Joyner Suzanne3 Markis Marcia3 Markis Marcia1 Bordoloi Bijoy1 Bordoloi Bijoy

Pretice Hall © 2004 44

The TOP KeywordThe TOP Keyword

• A SELECT statement that specifies the TOP A SELECT statement that specifies the TOP keyword is particularly useful in business for keyword is particularly useful in business for producing listings of the top salespeople, top producing listings of the top salespeople, top products sold, and the like. products sold, and the like.

• SQL example in the next slide combines the use SQL example in the next slide combines the use of the TOP keyword with the ORDER BY of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest clause to list the employees with the 2 largest salaries. salaries.

Pretice Hall © 2004 45

The TOP Keyword Contd.The TOP Keyword Contd.

SELECT SELECT TOP 2TOP 2 emp_ssn, emp_last_name, emp_salary emp_ssn, emp_last_name, emp_salary

FROM employeeFROM employee

ORDER BY emp_salary DESC;ORDER BY emp_salary DESC;

emp_ssn emp_last_name emp_salary emp_ssn emp_last_name emp_salary

--------- ---------------- ------------- --------- ---------------- -------------

999666666 Bordoloi 55000.0000999666666 Bordoloi 55000.0000

999444444 Zhu 43000.0000999444444 Zhu 43000.0000

Pretice Hall © 2004 46

The TOP Keyword Contd.The TOP Keyword Contd.

• But what if there are salary ties? But what if there are salary ties?

SELECT SELECT TOP 2TOP 2 WITH TIESWITH TIES emp_ssn, emp_last_name, emp_ssn, emp_last_name, emp_salaryemp_salary

FROM employeeFROM employeeORDER BY emp_salary DESC;ORDER BY emp_salary DESC;

emp_ssn emp_last_name emp_salary emp_ssn emp_last_name emp_salary

--------- ---------------- ------------- --------- ---------------- ------------- 999666666 Bordoloi 55000.0000999666666 Bordoloi 55000.0000999444444 Zhu 43000.0000999444444 Zhu 43000.0000999555555 Joyner 43000.0000999555555 Joyner 43000.0000

Pretice Hall © 2004 47

The TOP Keyword Contd.The TOP Keyword Contd.• If the PERCENT keyword is specified, only the If the PERCENT keyword is specified, only the

specified percentage of rows is included in the result specified percentage of rows is included in the result table. table.

SELECT SELECT TOP 40 PERCENTTOP 40 PERCENT WITH TIESWITH TIES emp_ssn, emp_last_name, emp_ssn, emp_last_name, emp_salaryemp_salary

FROM employeeFROM employeeORDER BY emp_salary DESC;ORDER BY emp_salary DESC;

emp_ssn emp_last_name emp_salary emp_ssn emp_last_name emp_salary

--------- ---------------- ------------- --------- ---------------- ------------- 999666666 Bordoloi 55000.0000999666666 Bordoloi 55000.0000999444444 Zhu 43000.0000999444444 Zhu 43000.0000999555555 Joyner 43000.0000999555555 Joyner 43000.0000999333333 Joshi 38000.0000999333333 Joshi 38000.0000

Pretice Hall © 2004 48

The INTO ClauseThe INTO Clause

• The optional INTO clause of the SELECT The optional INTO clause of the SELECT statement is used to create temporary tables. statement is used to create temporary tables.

• This clause can be used to store the output of a This clause can be used to store the output of a result table for future manipulation. result table for future manipulation.

• These temporary tables are not part of an These temporary tables are not part of an organization’s permanent, base tables; rather, organization’s permanent, base tables; rather, they are simply an additional option to support they are simply an additional option to support managerial decision-making. managerial decision-making.

Pretice Hall © 2004 49

The INTO Clause Contd.The INTO Clause Contd.

SELECT SELECT TOP 40TOP 40 PERCENTPERCENT WITH TIESWITH TIES emp_ssn, emp_last_name, emp_ssn, emp_last_name, emp_salaryemp_salary

INTO top_salary_employeesINTO top_salary_employeesFROM employeeFROM employeeORDER BY emp_salary DESC;ORDER BY emp_salary DESC;(4 row(s) affected)(4 row(s) affected)

SELECT *SELECT *FROM top_salary_employees;FROM top_salary_employees;

emp_ssn emp_last_name emp_salary emp_ssn emp_last_name emp_salary --------- ------------------------- --------------------- --------- ------------------------- --------------------- 999666666 Bordoloi 55000.0000999666666 Bordoloi 55000.0000999444444 Zhu 43000.0000999444444 Zhu 43000.0000999555555 Joyner 43000.0000999555555 Joyner 43000.0000999333333 Joshi 38000.0000999333333 Joshi 38000.0000(4 row(s) affected)(4 row(s) affected)

Pretice Hall © 2004 50

SUMMARYSUMMARYYou retrieve data from a relational database using the SELECT You retrieve data from a relational database using the SELECT statement. In this chapter, you were exposed to the following clauses of statement. In this chapter, you were exposed to the following clauses of the SELECT statement: SELECT, FROM, WHERE, and ORDER BY.the SELECT statement: SELECT, FROM, WHERE, and ORDER BY.• The SELECT clause controls the selection of columns in the final The SELECT clause controls the selection of columns in the final result table.result table.• The FROM clause indicates to the DBMS the tables that are involved The FROM clause indicates to the DBMS the tables that are involved in processing the query.in processing the query.• The WHERE clause controls the selection of rows depending on the The WHERE clause controls the selection of rows depending on the selection criteria and conditions specified in the WHERE clause.selection criteria and conditions specified in the WHERE clause.• The ORDER BY clause controls the sort order according to which the The ORDER BY clause controls the sort order according to which the output of the final result table should be displayed.output of the final result table should be displayed.You also learned how to:You also learned how to:• Use the CAST and CONVERT commands to format columnar output.Use the CAST and CONVERT commands to format columnar output.• Eliminate duplicate rows with the DISTINCT clause.Eliminate duplicate rows with the DISTINCT clause.• Display a TOP few rows from the result table.Display a TOP few rows from the result table.• Save the output of a query INTO a temporary table.Save the output of a query INTO a temporary table.

Pretice Hall © 2004 51

Chapter 4: Adding Power to QueriesChapter 4: Adding Power to Queries

SQL for SQL ServerSQL for SQL ServerBijoy Bordoloi and Douglas BockBijoy Bordoloi and Douglas Bock

Pretice Hall © 2004 52

OBJECTIVESOBJECTIVES

• Use logical operators (AND, OR, NOT) to Use logical operators (AND, OR, NOT) to write complex query conditions.write complex query conditions.

• Use the IN and BETWEEN operators.Use the IN and BETWEEN operators.

• Use the LIKE operator for character Use the LIKE operator for character matching.matching.

• Use the IS NULL operator when querying Use the IS NULL operator when querying for unknown values.for unknown values.

• Use expressions in WHERE clauses.Use expressions in WHERE clauses.

Pretice Hall © 2004 53

LOGICAL OPERATORSLOGICAL OPERATORS (AND, OR, AND NOT) (AND, OR, AND NOT)

• AND: Joins two or more conditions, and returns AND: Joins two or more conditions, and returns results only when results only when allall of the conditions are true. of the conditions are true.

• OR: Joins two or more conditions, and returns OR: Joins two or more conditions, and returns results when results when anyany of the conditions are true.of the conditions are true.

• NOT: Negates the expression that follows it.NOT: Negates the expression that follows it.

Pretice Hall © 2004 54

AND OPERATORAND OPERATOR

SELECT emp_last_name, emp_first_name, emp_gender SELECT emp_last_name, emp_first_name, emp_gender "Gender""Gender"

FROM employeeFROM employee

WHERE emp_gender = ‘F’ AND emp_last_name >= 'E'WHERE emp_gender = ‘F’ AND emp_last_name >= 'E'

ORDER BY emp_last_name;ORDER BY emp_last_name;

emp_last_name emp_first_name Gender emp_last_name emp_first_name Gender

------------- -------------- ------ ------------- -------------- ------

Joyner Suzanne FJoyner Suzanne F

Markis Marcia FMarkis Marcia F

Prescott Sherri FPrescott Sherri F

Pretice Hall © 2004 55

AND OPERATORAND OPERATOR

SELECT CAST(emp_last_name AS Char (12)) "Last Name", SELECT CAST(emp_last_name AS Char (12)) "Last Name", CAST(emp_first_name AS CHAR(2)) "First Name",CAST(emp_first_name AS CHAR(2)) "First Name", CAST(emp_date_of_birth AS CHAR(12))"Birth Day",CAST(emp_date_of_birth AS CHAR(12))"Birth Day", emp_gender "Gender", ‘$’ +emp_gender "Gender", ‘$’ + CONVERT (CHAR (10), emp_salary, 1) "Salary"CONVERT (CHAR (10), emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_last_name > ‘E’WHERE emp_last_name > ‘E’AND AND emp_date_of_birth > ‘20-Jun-71’emp_date_of_birth > ‘20-Jun-71’ANDAND emp_gender = ‘M’ emp_gender = ‘M’ ANDAND emp_salary > 20000emp_salary > 20000ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name Birth Day Gender Salary Last Name First Name Birth Day Gender Salary ------------ ---------- ------------ -------- ----------- ------------ ---------- ------------ -------- ----------- Joshi Di Sep 15 1972 M $ 38,000.00Joshi Di Sep 15 1972 M $ 38,000.00Zhu Wa Dec 8 1975 M $ 43,000.00Zhu Wa Dec 8 1975 M $ 43,000.00

Pretice Hall © 2004 56

OR OPERATOROR OPERATOR

SELECT emp_last_name, emp_first_name, emp_gender SELECT emp_last_name, emp_first_name, emp_gender

FROM employeeFROM employee

WHERE emp_gender = 'F' OR emp_last_name >= 'M'WHERE emp_gender = 'F' OR emp_last_name >= 'M'

ORDER BY emp_last_name;ORDER BY emp_last_name;

emp_last_name emp_first_name emp_gender emp_last_name emp_first_name emp_gender

------------- -------------- ---------- ------------- -------------- ----------

Joyner Suzanne FJoyner Suzanne F

Markis Marcia FMarkis Marcia F

Prescott Sherri FPrescott Sherri F

Zhu Waiman MZhu Waiman M

Pretice Hall © 2004 57

NOT OPERATORNOT OPERATOR

SELECT emp_last_name, emp_first_name, SELECT emp_last_name, emp_first_name, emp_dpt_numberemp_dpt_number

FROM employeeFROM employee

WHERE NOT emp_dpt_number = 7WHERE NOT emp_dpt_number = 7

ORDER BY emp_last_name;ORDER BY emp_last_name;  

emp_last_name emp_first_name emp_dpt_number emp_last_name emp_first_name emp_dpt_number

------------- -------------- -------------- ------------- -------------- --------------

Amin Hyder 3Amin Hyder 3

Bordoloi Bijoy 1Bordoloi Bijoy 1

Joyner Suzanne 3Joyner Suzanne 3

Markis Marcia 3Markis Marcia 3

Pretice Hall © 2004 58

Combining OR and AND OperatorsCombining OR and AND Operators

• When the AND operator is combined with When the AND operator is combined with OR, the SQL Server will evaluate the OR, the SQL Server will evaluate the condition connected by the AND condition connected by the AND firstfirst before any conditions connected with OR.before any conditions connected with OR.

• Parentheses must be used to force an order Parentheses must be used to force an order of operation. of operation.

Pretice Hall © 2004 59

Combining OR and AND Operators Contd.Combining OR and AND Operators Contd.

Q? Q?

Display a list of employees with a last Display a list of employees with a last name that begins with or is greater than the name that begins with or is greater than the letter ‘E’, and who are either female or works letter ‘E’, and who are either female or works in department number #1.in department number #1.

Pretice Hall © 2004 60

Combining OR and AND Operators Contd.Combining OR and AND Operators Contd.

SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", CAST(emp_first_name AS CHAR(12)) "First Name", CAST(emp_first_name AS CHAR(12)) "First Name", emp_gender, emp_dpt_number emp_gender, emp_dpt_number FROM employeeFROM employeeWHERE emp_last_name >= ‘E’ AND emp_gender = ‘F’ OR WHERE emp_last_name >= ‘E’ AND emp_gender = ‘F’ OR

emp_dpt_number = 1emp_dpt_number = 1ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name emp_gender emp_dpt_number Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- ------------ ------------ ---------- -------------- Bordoloi Bijoy M 1Bordoloi Bijoy M 1Joyner Suzanne F 3Joyner Suzanne F 3Markis Marcia F 3Markis Marcia F 3Prescott Sherri F 7Prescott Sherri F 7

Is this answer correct?Is this answer correct?

Pretice Hall © 2004 61

Combining OR and AND Operators Combining OR and AND Operators SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", SELECT CAST(emp_last_name AS CHAR(12)) "Last Name", CAST(emp_first_name AS CHAR(12)) "First Name", CAST(emp_first_name AS CHAR(12)) "First Name", emp_gender, emp_dpt_number emp_gender, emp_dpt_number FROM employeeFROM employeeWHERE emp_last_name >= ‘E’ AND WHERE emp_last_name >= ‘E’ AND (emp_gender = ‘F’ OR emp_dpt_number = 1)(emp_gender = ‘F’ OR emp_dpt_number = 1)ORDER BY emp_last_name; ORDER BY emp_last_name;

Last Name First Name emp_gender emp_dpt_number Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- ------------ ------------ ---------- -------------- Joyner Suzanne F 3Joyner Suzanne F 3Markis Marcia F 3Markis Marcia F 3Prescott Sherri F 7Prescott Sherri F 7  

Pretice Hall © 2004 62

LISTS (IN AND NOT IN)LISTS (IN AND NOT IN)

• There are two operators that are designed for There are two operators that are designed for testing to determine if data stored in a table column testing to determine if data stored in a table column is either in or not in a list or set of values.is either in or not in a list or set of values.

• These are the IN and NOT IN operators. These are the IN and NOT IN operators. • These operators greatly simplify the task of writing These operators greatly simplify the task of writing

queries that might otherwise require a large queries that might otherwise require a large number of either OR logical operators or an number of either OR logical operators or an unwieldy use of the NOT logical operator. unwieldy use of the NOT logical operator.

Pretice Hall © 2004 63

Using IN OperatorUsing IN OperatorSELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name",

CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name",

CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"

FROM employeeFROM employee

WHERE emp_salary = 43000 WHERE emp_salary = 43000 OROR emp_salary = 30000 emp_salary = 30000 OR OR emp_salary = 25000emp_salary = 25000

ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary

--------------- --------------- ------------ --------------- --------------- ------------

Amin Hyder 25000.00Amin Hyder 25000.00

Markis Marcia 25000.00Markis Marcia 25000.00

Prescott Sherri 25000.00Prescott Sherri 25000.00

Bock Douglas 30000.00Bock Douglas 30000.00

Zhu Waiman 43000.00Zhu Waiman 43000.00

Joyner Suzanne 43000.00Joyner Suzanne 43000.00

Pretice Hall © 2004 64

Using IN Operator Contd.Using IN Operator Contd.SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"FROM employeeFROM employeeWHERE emp_salary WHERE emp_salary IN (43000, 30000, 25000)IN (43000, 30000, 25000)ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ------------ --------------- --------------- ------------ Amin Hyder 25000.00Amin Hyder 25000.00Markis Marcia 25000.00Markis Marcia 25000.00Prescott Sherri 25000.00Prescott Sherri 25000.00Bock Douglas 30000.00Bock Douglas 30000.00Zhu Waiman 43000.00Zhu Waiman 43000.00Joyner Suzanne 43000.00Joyner Suzanne 43000.00

Pretice Hall © 2004 65

Using IN Operator Contd.Using IN Operator Contd.SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", emp_city "City"emp_city "City"FROM employeeFROM employeeWHERE emp_city IN (‘Marina’, ‘Edwardsville’, ‘St. Louis’)WHERE emp_city IN (‘Marina’, ‘Edwardsville’, ‘St. Louis’)ORDER BY emp_city;ORDER BY emp_city;

Last Name First Name City Last Name First Name City --------------- --------------- ------------------------- --------------- --------------- ------------------------- Bordoloi Bijoy EdwardsvilleBordoloi Bijoy EdwardsvillePrescott Sherri EdwardsvillePrescott Sherri EdwardsvilleAmin Hyder MarinaAmin Hyder MarinaJoyner Suzanne MarinaJoyner Suzanne MarinaBock Douglas St. LouisBock Douglas St. LouisZhu Waiman St. LouisZhu Waiman St. Louis

Pretice Hall © 2004 66

Using the NOT IN OperatorUsing the NOT IN Operator

• NOT can precede IN to form negative.NOT can precede IN to form negative.• To get the list of employees who did not earn the To get the list of employees who did not earn the

three salary figures listed earlierthree salary figures listed earlier

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", CAST(emp_salary AS DECIMAL(10, 2)) "Salary"CAST(emp_salary AS DECIMAL(10, 2)) "Salary"FROM employeeFROM employeeWHERE emp_salary WHERE emp_salary NOT INNOT IN (43000, 30000, 25000) (43000, 30000, 25000)ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ------------ --------------- --------------- ------------ Joshi Dinesh 38000.00Joshi Dinesh 38000.00Bordoloi Bijoy 55000.00Bordoloi Bijoy 55000.00

Pretice Hall © 2004 67

RANGES (BETWEEN AND NOT BETWEEN)RANGES (BETWEEN AND NOT BETWEEN)

• SQL provides two operators, BETWEEN and SQL provides two operators, BETWEEN and NOT BETWEEN that can simplify the range NOT BETWEEN that can simplify the range of values in a query.of values in a query.

• This eliminates the need to use a more This eliminates the need to use a more complex WHERE clause involving the use of complex WHERE clause involving the use of the AND logical operator.the AND logical operator.

Pretice Hall © 2004 68

Using the BETWEEN OperatorUsing the BETWEEN Operator

• The following query uses the AND logical operator.The following query uses the AND logical operator.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name’’CAST(emp_first_name AS CHAR(15)) "First Name’’ ‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_salary >= 25000 AND emp_salary <= 40000WHERE emp_salary >= 25000 AND emp_salary <= 40000ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ----------- --------------- --------------- ----------- Amin Hyder $ 25,000.00Amin Hyder $ 25,000.00Markis Marcia $ 25,000.00Markis Marcia $ 25,000.00Prescott Sherri $ 25,000.00Prescott Sherri $ 25,000.00Bock Douglas $ 30,000.00Bock Douglas $ 30,000.00Joshi Dinesh $ 38,000.00Joshi Dinesh $ 38,000.00

Pretice Hall © 2004 69

Using the BETWEEN Operator Contd.Using the BETWEEN Operator Contd.

• The query can be rewritten using the BETWEEN operator. The query can be rewritten using the BETWEEN operator.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", ‘ ‘$’+ Convert(char(10),emp_salary, 1) "Salary"$’+ Convert(char(10),emp_salary, 1) "Salary"FROM employeeFROM employeeWHERE emp_salary BETWEEN 25000 AND 40000WHERE emp_salary BETWEEN 25000 AND 40000ORDER BY emp_salary;ORDER BY emp_salary;

Last Name First Name Salary Last Name First Name Salary --------------- --------------- ----------- --------------- --------------- ----------- Amin Hyder $ 25,000.00Amin Hyder $ 25,000.00Markis Marcia $ 25,000.00Markis Marcia $ 25,000.00Prescott Sherri $ 25,000.00Prescott Sherri $ 25,000.00Bock Douglas $ 30,000.00Bock Douglas $ 30,000.00Joshi Dinesh $ 38,000.00Joshi Dinesh $ 38,000.00

Pretice Hall © 2004 70

Specifying More Than One Salary RangeSpecifying More Than One Salary Range

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", ‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"FROM employee FROM employee WHEREWHERE emp_salaryemp_salary BETWEEN 25000 AND 30000 BETWEEN 25000 AND 30000 OR emp_salary BETWEEN 40000 AND 43000OR emp_salary BETWEEN 40000 AND 43000ORDER BY emp_salaryORDER BY emp_salary;;

Last Name Salary Last Name Salary --------------- ----------- --------------- ----------- Amin $ 25,000.00Amin $ 25,000.00Markis $ 25,000.00Markis $ 25,000.00Prescott $ 25,000.00Prescott $ 25,000.00Bock $ 30,000.00Bock $ 30,000.00Zhu $ 43,000.00Zhu $ 43,000.00Joyner $ 43,000.00Joyner $ 43,000.00

Pretice Hall © 2004 71

Using the NOT BETWEEN OperatorUsing the NOT BETWEEN Operator

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name",

‘ ‘$’ + Convert(char(10),emp_salary, 1) "Salary"$’ + Convert(char(10),emp_salary, 1) "Salary"

FROM employee FROM employee

WHERE emp_salary NOT BETWEEN 28000 AND 50000WHERE emp_salary NOT BETWEEN 28000 AND 50000

ORDER BY emp_salary;ORDER BY emp_salary;

Last Name Salary Last Name Salary

--------------- ----------- --------------- -----------

Amin $ 25,000.00Amin $ 25,000.00

Markis $ 25,000.00Markis $ 25,000.00

Prescott $ 25,000.00Prescott $ 25,000.00

Bordoloi $ 55,000.00Bordoloi $ 55,000.00

Pretice Hall © 2004 72

LIKE AND NOT LIKELIKE AND NOT LIKE

• The LIKE and NOT LIKE operators can be used to The LIKE and NOT LIKE operators can be used to search for data rows containing incomplete or partial search for data rows containing incomplete or partial character strings within a data column. character strings within a data column.

• The next query searches the employee table for The next query searches the employee table for employee names that begin with the characters ‘Bo’.employee names that begin with the characters ‘Bo’.

• The search is case-sensitive meaning that ‘Bo’ is not The search is case-sensitive meaning that ‘Bo’ is not equivalent to ‘BO’.equivalent to ‘BO’.

SELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name"CAST(emp_first_name AS CHAR(15)) "First Name"FROM employeeFROM employeeWHERE emp_last_name LIKE 'Bo%';WHERE emp_last_name LIKE 'Bo%';

Pretice Hall © 2004 73

LIKE AND NOT LIKELIKE AND NOT LIKE

Wild cardWild card MeaningMeaning

% % (percent) (percent) any string of zero or more charactersany string of zero or more characters

_ (underscore)_ (underscore) any single characterany single character

[ ] (brackets)[ ] (brackets) any single character within a specified any single character within a specified range such as ‘range such as ‘aa’ to ‘’ to ‘dd’, inclusive [a-d] ’, inclusive [a-d] or a set of characters such as or a set of characters such as [aeiouy][aeiouy]

[^] (not brackets)[^] (not brackets) any single character any single character not not in the in the specified range or set (e.g., [^a-f] )specified range or set (e.g., [^a-f] )

Pretice Hall © 2004 74

MORE EXAMPLESMORE EXAMPLES

• LIKE ‘%inger’ will search for every name that ends LIKE ‘%inger’ will search for every name that ends with ‘inger’ (Rwith ‘inger’ (Ringeringer, Str, Stringeringer).).

• LIKE ‘%en%’ will search for every name that has the LIKE ‘%en%’ will search for every name that has the letters ‘en’ in the name (Bletters ‘en’ in the name (Benennet, Grenet, Greenen, McBadd, McBaddenen).).

• LIKE ‘_heryl’ will search for every six-letter name LIKE ‘_heryl’ will search for every six-letter name ending with ‘heryl’ (Cending with ‘heryl’ (Cherylheryl). Notice how this is ). Notice how this is different than ‘%heryl’ ,which would return names different than ‘%heryl’ ,which would return names that are six characters or more.that are six characters or more.

Pretice Hall © 2004 75

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

• LIKE ‘[CK]ars[eo]n’ will search for every six-letter LIKE ‘[CK]ars[eo]n’ will search for every six-letter name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ or ‘o’ between ‘ars’ and ‘n’ (e.g., 'or ‘o’ between ‘ars’ and ‘n’ (e.g., 'CCarsarseen,' ‘n,' ‘KKarsarseen,’ n,’ ‘‘CCarsarsoon,’ and ‘n,’ and ‘KKarsarsoon’.n’.

• LIKE ‘[M-Z]inger’ will search for all the names ending LIKE ‘[M-Z]inger’ will search for all the names ending with ‘inger’ that begin with any single letter ‘M’ thru with ‘inger’ that begin with any single letter ‘M’ thru ‘Z’ (R‘Z’ (Ringeringer).).

• LIKE ‘M[^c]%’ will search for all the names that begin LIKE ‘M[^c]%’ will search for all the names that begin with ‘M’ not having ‘c’ as the second letter.with ‘M’ not having ‘c’ as the second letter.

Pretice Hall © 2004 76

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

•The SELECT statement shown below generates a The SELECT statement shown below generates a result table that includes all DISTINCT rows where result table that includes all DISTINCT rows where the employee social security number in the the employee social security number in the assignmentassignment table ends with the numbers 555. table ends with the numbers 555.

SELECT DISTINCT work_emp_ssn "Emp SSN"SELECT DISTINCT work_emp_ssn "Emp SSN"

FROM assignmentFROM assignment

WHERE work_emp_ssn LIKE ‘%555’WHERE work_emp_ssn LIKE ‘%555’

Emp SSN Emp SSN

--------- ---------

999555555999555555

Pretice Hall © 2004 77

UNKNOWN VALUESUNKNOWN VALUES (IS NULL and IS NOT NULL) (IS NULL and IS NOT NULL)

• NULL value is NULL value is not synonymous not synonymous with “zero” with “zero” (numerical values) or “blank” (character values).(numerical values) or “blank” (character values).

• NULL values allow users to distinguish between a NULL values allow users to distinguish between a deliberate entry of zero/blank and a non entry of deliberate entry of zero/blank and a non entry of data.data.

SELECT *SELECT *

FROM assignment FROM assignment

WHERE work_hours IS NULL;WHERE work_hours IS NULL;

work_emp_ssn work_pro_number work_hours work_emp_ssn work_pro_number work_hours

------------ --------------- ---------- ------------ --------------- ----------

999444444 1 NULL999444444 1 NULL

999666666 20 NULL999666666 20 NULL

Pretice Hall © 2004 78

MORE EXAMPLES Contd.MORE EXAMPLES Contd.

SELECT *SELECT *FROM assignmentFROM assignmentWHERE work_hours = 0;WHERE work_hours = 0;

work_emp_ssn work_pro_number work_hours work_emp_ssn work_pro_number work_hours ------------ --------------- ---------- ------------ --------------- ---------- (0 row(s) affected)(0 row(s) affected)

• The query did not return a result table because none The query did not return a result table because none of the rows in the assignment table have a zero of the rows in the assignment table have a zero value for work_hours. Thus, you can see that zero value for work_hours. Thus, you can see that zero (0) is a value, not an “unknown value.”(0) is a value, not an “unknown value.”

Pretice Hall © 2004 79

MORE EXAMPLESMORE EXAMPLES

• The NOT NULL condition can also be tested.The NOT NULL condition can also be tested.

SELECT *SELECT *

FROM assignment FROM assignment

WHERE work_hours IS NOT NULL;WHERE work_hours IS NOT NULL;

(15 row(s) affected)(15 row(s) affected)

• The result table contains all the rows where The result table contains all the rows where work_hours column contains a value. work_hours column contains a value.

Pretice Hall © 2004 80

EXPRESSIONS IN SELECT CLAUSESEXPRESSIONS IN SELECT CLAUSES

• An expression is formed by combining a column An expression is formed by combining a column name or constant with an arithmetic operator.name or constant with an arithmetic operator.

• The arithmetic operators used in SQL are The arithmetic operators used in SQL are

SYMBOL OPERATION ORDER

* Multiplication 1

/ Division 1

% Modulo 1

+ Addition 2

- Subtraction 2

Pretice Hall © 2004 81

EXAMPLEEXAMPLESELECT CAST(emp_last_name AS Char (15)) "Last Name", SELECT CAST(emp_last_name AS Char (15)) "Last Name", CAST(emp_first_name AS CHAR(15)) "First Name",CAST(emp_first_name AS CHAR(15)) "First Name", emp_salary/12emp_salary/12 "Monthly Salary" "Monthly Salary"FROM employeeFROM employeeWHERE emp_salary/12 > 3500WHERE emp_salary/12 > 3500ORDER BY emp_last_name;ORDER BY emp_last_name;

Last Name First Name Monthly Salary Last Name First Name Monthly Salary --------------- --------------- --------------- --------------- --------------------- --------------------- Bordoloi Bijoy Bordoloi Bijoy 4583.33334583.3333Joyner Suzanne Joyner Suzanne 3583.33333583.3333Zhu Waiman Zhu Waiman 3583.33333583.3333

Pretice Hall © 2004 82

EXPRESSIONSEXPRESSIONS

• When expression is used in select with a column When expression is used in select with a column name it has no effect on the table’s underlying name it has no effect on the table’s underlying values.values.

• The data contained in each column must be The data contained in each column must be numeric data.numeric data.

• The result of an arithmetic operation on The result of an arithmetic operation on NULL is NULL. NULL is NULL.

Pretice Hall © 2004 83

Examples of Operations on NullsExamples of Operations on NullsSELECT work_emp_ssn "SSN", work_pro_number SELECT work_emp_ssn "SSN", work_pro_number

"Project","Project", work_hours/40 "Avg Hours/Week"work_hours/40 "Avg Hours/Week"FROM assignmentFROM assignmentWHERE work_pro_number = 1WHERE work_pro_number = 1ORDER BY work_emp_ssn;ORDER BY work_emp_ssn;

SSN Project Avg Hours/Week SSN Project Avg Hours/Week --------- ------- -------------- --------- ------- -------------- 999111111 1 .785000999111111 1 .785000999444444 1 NULL999444444 1 NULL999888888 1 .525000999888888 1 .525000

Pretice Hall © 2004 84

Examples of Operations on Nulls Contd.Examples of Operations on Nulls Contd. Table: Contract_EmployeeTable: Contract_Employee

emp_id, emp_id, emp_jobemp_job emp_salaryemp_salary emp_bonus emp_bonus

1010 BIG BOSS BIG BOSS 100000 100000 NULLNULL

2020 LITTLE LITTLE BOSS BOSS

50000 50000 NULLNULL

3030 WARRIOR WARRIOR 10000 10000 20002000

4040 WARRIOR WARRIOR 10000 10000 30003000

Pretice Hall © 2004 85

Examples of Operations on Nulls Examples of Operations on Nulls Contd.Contd.

SELECT emp_id, emp_job, emp_salary+emp_bonus SELECT emp_id, emp_job, emp_salary+emp_bonus "Total Comp""Total Comp"

FROM contract_employee; FROM contract_employee;

emp_id emp_job Total Comp emp_id emp_job Total Comp --------- --------------- --------- --------------- --------------------- --------------------- 10 BIG BOSS 10 BIG BOSS NULLNULL20 LITTLE BOSS NULL20 LITTLE BOSS NULL30 WORKER 30 WORKER 12000.000012000.000040 WORKER 40 WORKER 14000.000014000.0000

Pretice Hall © 2004 86

SUMMARYSUMMARY

• Logical operators (AND and OR) in the WHERE clause add Logical operators (AND and OR) in the WHERE clause add power to your queries.power to your queries.

• When the AND operator is combined with OR, AND takes When the AND operator is combined with OR, AND takes precedence over OR. Always use parentheses' to clarify the precedence over OR. Always use parentheses' to clarify the order of operation. order of operation.

• IN AND NOT IN operators are used to compare a column IN AND NOT IN operators are used to compare a column against several values.against several values.

• The BETWEEN operators specifies an The BETWEEN operators specifies an inclusiveinclusive range of range of values.values.

• Use the LIKE operator for incomplete search of character Use the LIKE operator for incomplete search of character string.string.

• Use the IS NULL operator when querying for unknown Use the IS NULL operator when querying for unknown values.values.

• The result of an arithmetic operation on NULL is NULL. The result of an arithmetic operation on NULL is NULL.