Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pretice Hall © 20041 COS 346 Day 12. Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1 correctedQuiz 1 corrected –1 A, 5 B’s, 1 C and 1 F Assignment.

Similar presentations


Presentation on theme: "Pretice Hall © 20041 COS 346 Day 12. Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1 correctedQuiz 1 corrected –1 A, 5 B’s, 1 C and 1 F Assignment."— Presentation transcript:

1 Pretice Hall © 20041 COS 346 Day 12

2 Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1 correctedQuiz 1 corrected –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) Assignment 5 PostedAssignment 5 Posted –Due March 20 (right After Break) Assignment 6 will be posted by March 20Assignment 6 will be posted by March 20 Capstone Project Proposals DueCapstone Project Proposals Due –Must be a database project –Only received one so far More on SQL & SQL ServerMore on SQL & SQL Server –We do chap 3-10 in SQL Text next –About 1 week behind schedule

3 Pretice Hall © 20043 Cheating As Defined by UMFK PolicyAs Defined by UMFK Policy

4 Pretice Hall © 20044 Cheating As Defined by UMFK PolicyAs Defined by UMFK Policy

5 Pretice Hall © 20045 Sanctions First Time Offense Multiple Offenses

6 Pretice Hall © 20046 My 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

7 Pretice Hall © 20047 Assignment 4

8 Pretice Hall © 20048 Chapter 3: Single Table Query Basics SQL for SQL Server Bijoy Bordoloi and Douglas Bock

9 Pretice Hall © 20049 OBJECTIVES Write simple SELECT statements.Write simple SELECT statements. Learn to use the CAST and CONVERT commands to format columnar output.Learn to use the CAST and CONVERT commands to 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 conditions.Use the WHERE clause to specify selection criteria and 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.

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

11 Pretice Hall © 200411 Example SELECT * FROM employee; emp_ssn emp_last_name emp_first_name emp_middle_name --------- --------------- ---------------- --------------- 99111111 Bock Douglas B 999222222 Amin Hyder NULL 999333333 Joshi Dinesh Null more rows and columns will be displayed… – This query selects rows from the “employee” table. – The asterisk (*) tells Oracle to select (display) all columns contained in the table “employee”.

12 Pretice Hall © 200412 Example Contd. The following SELECT statement produces an identical output.The following SELECT statement produces an 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.

13 Pretice Hall © 200413 SQL Server will process the query regardless of whether you type the entire query on one line, or indent.SQL Server will process the query regardless of whether you type the entire query on one line, or indent. There are no rules about how many words can be put on a line or where to break a line.There are no rules about how many words can be put on a line or where to break a line. Although SQL Server does not require indenting, indenting enhances readability.Although SQL Server does not require indenting, indenting enhances readability. You must, however, follow the order of the syntax of the SELECT statement shown on the next slide.You must, however, follow the order of the syntax of the SELECT statement shown on the next slide. Indenting SQL Code

14 Pretice Hall © 200414 The following keywords (which constitute the order of the syntax of a SELECT statement) are your signal to start a new line.The following keywords (which constitute the order of the syntax of a SELECT statement) are your signal to start a new line. »SELECT »FROM »WHERE »GROUP BY »HAVING »ORDER BY Indenting SQL Code Contd.

15 Pretice Hall © 200415 Specify the column names you want displayed in the result set by typing the exact, complete column names.Specify the column names you want displayed in the result set by typing the exact, complete column names. Separate each column name with a comma (,).Separate each column name with a comma (,). The column names selected must belong to the table(s) named in the FROM clause.The column names selected must belong to the table(s) named in the FROM clause. Although we use a semicolon to mark the end of a query in almost all the examples in this book, the semicolon at the end of the query is optional in T-SQL (versus required when using SQL for other databases such as Oracle).Although we use a semicolon to mark the end of a query in almost all the examples in this book, the semicolon at the end of the query is optional in T-SQL (versus required when using SQL for other databases such as Oracle). Selecting Specific Columns

16 Pretice Hall © 200416 At times you will write a query where the columnar output will not fit onto a single display line (and may ‘wrap’ around).At times you will write a query where the columnar output will not fit onto a single display line (and may ‘wrap’ around). You can clean up the result table for such a query by modifying the output display size of specific columns.You can clean up the result table for such a query by modifying the output display size of specific columns. In SQL Server you can reformat the column output with automatic data type conversion by using the CAST and CONVERT functions in the SELECT statement.In SQL Server you can reformat the column output with automatic data type conversion by using the CAST and CONVERT functions in the SELECT statement. Formatting Default Output

17 Pretice Hall © 200417 Using the CAST FunctionUsing the CAST Function SELECT emp_ssn, CAST(emp_last_name As CHAR(12)), CAST(emp_first_name As CHAR(12)), CAST(emp_date_of_birth As CHAR(12)), CAST(emp_date_of_birth As CHAR(12)),emp_superssn FROM employee; emp_ssn emp_superssn ----------- ----------- ---------- --------------- --------------- 999111111 Bock Douglas Dec 5 1950 999444444 999222222 Amin Hyder Mar 29 1969 999555555 999333333 Joshi Dinesh Sep 15 1972 999444444 more rows will be displayed… Formatting Default Output Contd.

18 Pretice Hall © 200418 Using the CAST Function (Renaming Column Names)Using the CAST Function (Renaming Column Names) SELECT emp_ssn, CAST(emp_last_name As CHAR(12)) "Last Name", CAST(emp_first_name As CHAR(12)) "First Name", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", CAST(emp_date_of_birth As CHAR(12)) "Date of Birth", emp_superssn "Supervisor_SSN" FROM employee; emp_ssn Last Name First Name Date of Birth Supervisor_SSN ----------- ------------ ------------- --------------- ------------------ 999111111 Bock Douglas Dec 5 1950 999444444 999222222 Amin Hyder Mar 29 1969 999555555 999333333 Joshi Dinesh Sep 15 1972 999444444 more rows will be displayed… Formatting Default Output Contd.

19 Pretice Hall © 200419 When labeling or renaming display columns from the default column names, be sure to follow these rules: Enclose the label in quotes, either single or double.Enclose the label in quotes, either single or double. Do NOT separate the label from the expression with a comma.Do NOT separate the label from the expression with a comma. The label must follow the function or column name.The label must follow the function or column name. Formatting Default Output Contd.

20 Pretice Hall © 200420 Using the CONVERT Function Apart from the CAST function, you can also use the CONVERT function, which provides some additional features for formatting the output of numeric columns.Apart from the CAST function, you can also use the CONVERT function, which provides some additional features for formatting the output of numeric columns. Both CONVERT and CAST functions are discussed further in Chapter 9.Both CONVERT and CAST functions are discussed further in Chapter 9. Formatting Default Output Contd.

21 Pretice Hall © 200421 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.0000 999222222 Amin Hyder Mar 29 1969 25000.0000 999333333 Joshi Dinesh Sep 15 1972 38000.0000 Formatting Default Output Contd.

22 Pretice Hall © 200422 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.00 999222222 Amin Hyder Mar 29 1969 25,000.00 999333333 Joshi Dinesh Sep 15 1972 38,000.00 Formatting Default Output Contd.

23 Pretice Hall © 200423 Using the CONVERT Function As shown in the previous example, the reformatted emp_salary data now has only two digits to the right of the decimal point and includes a comma for every three digits to the left of the decimal point.As shown in the previous example, the reformatted emp_salary data now has only two digits to the right of the decimal point and includes a comma for every three digits to the left of the decimal point. This was achieved by setting the style parameter value of the CONVERT function to “1”.This was achieved by setting the style parameter value of the CONVERT function to “1”. Also, the column heading label was changed to read Salary instead of the default column name (emp_salary).Also, the column heading label was changed to read Salary instead of the default column name (emp_salary). Formatting Default Output Contd.

24 Pretice Hall © 200424 Using the CONVERT Function We can improve the output for the salary column even further if we place a dollar sign ($) in front of the values for the employee salary figures.We can improve the output for the salary column even further if we place a dollar sign ($) in front of the values for the employee salary figures. As shown in the next slide, this result is achieved by including a constant character “$” as a column name in the SELECT statement and concatenating this column with the salary column. The “+” sign is the concatenation symbol.As shown in the next slide, this result is achieved by including a constant character “$” as a column name in the SELECT statement and concatenating this column with the salary column. The “+” sign is the concatenation symbol. Formatting Default Output Contd.

25 Pretice Hall © 200425 Using 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.00 999222222 Amin Hyder Mar 29 1969 $ 25,000.00 999333333 Joshi Dinesh Sep 15 1972 $ 38,000.00 Formatting Default Output Contd.

26 Pretice Hall © 200426 Although SQL is a free-form language, there are still syntactical rules that must be followed or you will receive an error message instead of the desired result table.Although SQL is a free-form language, there are still syntactical rules that must be followed or you will receive an error message instead of the desired result table. SQL Server will display some error message indicating the possible cause of error and the line number (in your query) where the error has occurred.SQL Server will display some error message indicating the possible cause of error and the line number (in your query) where the error has occurred. Common Errors

27 Pretice Hall © 200427 Invalid Column Name In this SELECT statement, the employee social security number column name is spelled incorrectly.In this SELECT statement, the employee social security number column name is spelled incorrectly. SELECT emp_socsecno FROM employee; Server: Msg 207, Level 16, State 3, Line 1 Invalid column name ‘emp_socsecno’.

28 Pretice Hall © 200428 FROM Keyword Missing The next SELECT statement is missing the FROM clause so that no table name has been specified.The next SELECT statement is missing the FROM clause so that no table name has been specified. Without a table name, the DBMS does not know which table to query.Without a table name, the DBMS does not know which table to query. SELECT emp_ssn; Server: Msg 207, Level 16, State 3, Line 1 Invalid column name ‘emp_ssn’.

29 Pretice Hall © 200429 Invalid Command Structure You must follow the syntax order of the SELECT statement correctly.You must follow the syntax order of the SELECT statement correctly. In the example below, the order of the SELECT and FROM clauses is reversed. SQL Server simply returns an ‘incorrect syntax’ error message.In the example below, the order of the SELECT and FROM clauses is reversed. SQL Server simply returns an ‘incorrect syntax’ error message. FROM employee SELECT emp_ssn; Server: Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'FROM'.

30 Pretice Hall © 200430 Errors in Placing Commas Must have a comma between column names in the SELECT clauseMust have a comma between column names in the SELECT clause SELECT emp_ssn, emp_last_name emp_first_name FROM employee; emp_ssn emp_first_name ----------- ------------------------- 999111111 Bock 999222222 Amin 999333333 Joshi more rows will be displayed…

31 Pretice Hall © 200431 Errors in Placing Commas Contd. Must not have a comma after the last column names in the SELECT clauseMust not have a comma after the last column names in the SELECT clause SELECT emp_ssn, emp_last_name, emp_first_name, FROM employee; Server: Msg 156, Level 15, State 1, Line 2 Incorrect syntax near the keyword 'FROM'.

32 Pretice Hall © 200432 THE DISTINCT CLAUSE SQL Server provides a means for eliminating duplicate rows in a result table through use of the DISTINCT keyword. SELECT emp_salary FROM employee; emp_salary----------30000.000025000.000038000.000043000.000043000.000055000.000025000.000025000.0000 (8 row(s) affected) SELECT DISTINCT emp_salary FROM employee; emp_salary----------25000.000030000.000038000.000043000.000055000.0000 (5 row(s) affected)

33 Pretice Hall © 200433 THE DISTINCT CLAUSE Contd. The DISTINCT keyword also eliminates duplicate rows where more than one column is displayed in the result table. SELECT room_id, bed_type_id FROM bed; room_id bed_type_id ------- ----------- SW1001 R1 SW1002 R1 SW1003 R2.. SW1010 R1 SW1010 R2 SW1011 R2 SW1012 R1 (98 row(s) affected) SELECT DISTINCT room_id, bed_type_id FROM bed; room_id bed_type_id ------- -----------... SW1001 R1 SW1002 R1 SW1003 R1... SW1004 R2 SW1005 R2 SW1006 R1 SW1006 R2 SW1010 RE SW1011 R2 SW1012 R1 (65 row(s) affected)

34 Pretice Hall © 200434 THE WHERE CLAUSE THE WHERE CLAUSE Specific rows can be selected by adding a WHERE clause to the SELECT query.Specific rows can be selected by adding a WHERE clause to the SELECT query. SELECT emp_ssn, emp_last_name, emp_first_name, emp_salary FROM employee WHERE emp_salary >= 35000; emp_ssn emp_last_name emp_first_name emp_salary ------- ------------- -------------- ---------- 999333333 Joshi Dinesh 38000.0000 999444444 Zhu Waiman 43000.0000 999555555 Joyner Suzanne 43000.0000 999666666 Bordoloi Bijoy 55000.0000

35 Pretice Hall © 200435 Comparison Operators Operator Meaning =equal to =equal to <less than <less than >greater than >greater than >=greater than or equal to >=greater than or equal to <=less than or equal to <=less than or equal to !=not equal to !=not equal to <>not equal to <>not equal to !>not greater than !>not greater than !<not less than !<not less than

36 Pretice Hall © 200436 Comparing Character Data Comparing 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 character data.They can also be used with columns containing character data. If the value is a character string or date, you must surround the value (string of characters) with which a column is being compared with single quotation (' ') marks.If the value is a character string or date, you must surround the value (string of characters) with which a column is being compared with single quotation (' ') marks. SELECT emp_ssn, emp_last_name, emp_first_name FROM employee WHERE emp_gender = ‘M’;

37 Pretice Hall © 200437 Comparing Character Data Comparing Character Data You can also write SELECT statements that use operators other than the equal sign.You can also write SELECT statements that use operators other than the equal sign. SELECT emp_last_name, emp_first_name FROM employee WHERE emp_last_name >= 'J'; emp_last_name emp_first_name ------------------------- ------------------------- Joshi Dinesh Zhu Waiman Joyner Suzanne Markis Marcia Prescott Sherri

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

39 Pretice Hall © 200439 Comparison Operators in the WHERE Clause Contd. SELECT emp_ssn, emp_last_name, emp_first_name FROM employee WHERE emp_gender = M; ERROR at line 3: ORA-00904: invalid column name Since the literal string value was not enclosed by single quote marks, SQL Server assumed the letter M to be a column name.Since the literal string value was not enclosed by single quote marks, SQL Server assumed the letter M to be a column name. There is no column named M in the table so an error was returned.There is no column named M in the table so an error was returned.

40 Pretice Hall © 200440 THE ORDER BY CLAUSE Output from a SELECT statement can be sorted by using the optional ORDER BY clause.Output from a SELECT statement can be sorted by using the optional ORDER BY clause. SELECT emp_last_name, emp_first_name FROM employee WHERE emp_last_name >= 'J' ORDER BY emp_last_name; emp_last_name emp_first_name ------------------------- ------------------------- Joshi Dinesh Joyner Suzanne Markis Marcia Prescott Sherri Zhu Waiman

41 Pretice Hall © 200441 ORDER BY With ASC and DESC By default, the ORDER BY clause sorts output rows in a result table in ascending order.By default, the ORDER BY clause sorts output rows in a result table in ascending order. To sort columns from high to low, or descending, an optional keyword DESC must be specified.To sort columns from high to low, or descending, an optional keyword DESC must be specified.  ASC - Ascending, low to high.  DESC - Descending, high to low.  When ASC or DESC is used, it must be followed by the column name.  You can include a maximum of 16 column names in the ORDER BY clause.

42 Pretice Hall © 200442 ORDER BY With ASC and DESC Contd. When ASC or DESC is used, it must be followed by the column name.When ASC or DESC is used, it must be followed by the column name. SELECT emp_last_name, emp_first_name, emp_salary FROM employee WHERE emp_salary > 35000 ORDER BY DESC emp_salary; Server: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'DESC'.

43 Pretice Hall © 200443 ORDER BY With More Than One Column Sorting by multiple columns can improve the look and usability of the information.Sorting by multiple columns can improve the look and usability of the information. SELECT emp_dpt_number, emp_last_name, emp_first_name FROM employee ORDER BY emp_dpt_number DESC, emp_last_name; emp_dpt_number emp_last_name emp_first_name -------------- ------------------ -------------------- 7 Bock Douglas 7 Joshi Dinesh 7 Prescott Sherri 7 Zhu Waiman 3 Amin Hyder 3 Joyner Suzanne 3 Markis Marcia 1 Bordoloi Bijoy

44 Pretice Hall © 200444 The TOP Keyword A SELECT statement that specifies the TOP keyword is particularly useful in business for producing listings of the top salespeople, top products sold, and the like.A SELECT statement that specifies the TOP keyword is particularly useful in business for producing listings of the top salespeople, top products sold, and the like. SQL example in the next slide combines the use of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest salaries.SQL example in the next slide combines the use of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest salaries.

45 Pretice Hall © 200445 The TOP Keyword Contd. SELECT TOP 2 emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000

46 Pretice Hall © 200446 The TOP Keyword Contd. But what if there are salary ties?But what if there are salary ties? SELECT TOP 2 WITH TIES emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000

47 Pretice Hall © 200447 The TOP Keyword Contd. If the PERCENT keyword is specified, only the specified percentage of rows is included in the result table.If the PERCENT keyword is specified, only the specified percentage of rows is included in the result table. SELECT TOP 40 PERCENT WITH TIES emp_ssn, emp_last_name, emp_salary FROM employee ORDER BY emp_salary DESC; emp_ssn emp_last_name emp_salary --------- ---------------- ------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000 999333333 Joshi 38000.0000

48 Pretice Hall © 200448 The INTO Clause The optional INTO clause of the SELECT statement is used to create temporary tables.The optional INTO clause of the SELECT statement is used to create temporary tables. This clause can be used to store the output of a result table for future manipulation. This clause can be used to store the output of a result table for future manipulation. These temporary tables are not part of an organization’s permanent, base tables; rather, they are simply an additional option to support managerial decision-making.These temporary tables are not part of an organization’s permanent, base tables; rather, they are simply an additional option to support managerial decision-making.

49 Pretice Hall © 200449 The INTO Clause Contd. SELECT TOP 40 PERCENT WITH TIES emp_ssn, emp_last_name, emp_salary INTO top_salary_employees FROM employee ORDER BY emp_salary DESC; (4 row(s) affected) SELECT * FROM top_salary_employees; emp_ssn emp_last_name emp_salary --------- ------------------------- --------------------- 999666666 Bordoloi 55000.0000 999444444 Zhu 43000.0000 999555555 Joyner 43000.0000 999333333 Joshi 38000.0000 (4 row(s) affected)

50 Pretice Hall © 200450 SUMMARY You retrieve data from a relational database using the SELECT statement. In this chapter, you were exposed to the following clauses of the SELECT statement: SELECT, FROM, WHERE, and ORDER BY. The SELECT clause controls the selection of columns in the final result table. The SELECT clause controls the selection of columns in the final result table. The FROM clause indicates to the DBMS the tables that are involved in processing the query. The FROM clause indicates to the DBMS the tables that are involved in processing the query. The WHERE clause controls the selection of rows depending on the selection criteria and conditions specified in the WHERE clause. The WHERE clause controls the selection of rows depending on the selection criteria and conditions specified in the WHERE clause. The ORDER BY clause controls the sort order according to which the output of the final result table should be displayed. The ORDER BY clause controls the sort order according to which the output of the final result table should be displayed. 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.

51 Pretice Hall © 200451 Chapter 4: Adding Power to Queries SQL for SQL Server Bijoy Bordoloi and Douglas Bock

52 Pretice Hall © 200452 OBJECTIVES Use logical operators (AND, OR, NOT) to write complex query conditions.Use logical operators (AND, OR, NOT) to write complex query conditions. Use the IN and BETWEEN operators.Use the IN and BETWEEN operators. Use the LIKE operator for character matching.Use the LIKE operator for character matching. Use the IS NULL operator when querying for unknown values.Use the IS NULL operator when querying for unknown values. Use expressions in WHERE clauses.Use expressions in WHERE clauses.

53 Pretice Hall © 200453 LOGICAL OPERATORS (AND, OR, AND NOT) AND: Joins two or more conditions, and returns results only when all of the conditions are true.AND: Joins two or more conditions, and returns results only when all of the conditions are true. OR: Joins two or more conditions, and returns results when any of the conditions are true.OR: Joins two or more conditions, and returns results when any of the conditions are true. NOT: Negates the expression that follows it.NOT: Negates the expression that follows it.

54 Pretice Hall © 200454 AND OPERATOR SELECT emp_last_name, emp_first_name, emp_gender "Gender" FROM employee WHERE emp_gender = ‘F’ AND emp_last_name >= 'E' ORDER BY emp_last_name; emp_last_name emp_first_name Gender ------------- -------------- ------ Joyner Suzanne F Markis Marcia F Prescott Sherri F

55 Pretice Hall © 200455 AND OPERATOR 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 employee WHERE emp_last_name > ‘E’AND emp_date_of_birth > ‘20-Jun-71’AND emp_date_of_birth > ‘20-Jun-71’AND emp_gender = ‘M’ AND emp_gender = ‘M’ AND emp_salary > 20000 emp_salary > 20000 ORDER BY emp_last_name; Last Name First Name Birth Day Gender Salary ------------ ---------- ------------ -------- ----------- Joshi Di Sep 15 1972 M $ 38,000.00 Zhu Wa Dec 8 1975 M $ 43,000.00

56 Pretice Hall © 200456 OR OPERATOR SELECT emp_last_name, emp_first_name, emp_gender FROM employee WHERE emp_gender = 'F' OR emp_last_name >= 'M' ORDER BY emp_last_name; emp_last_name emp_first_name emp_gender ------------- -------------- ---------- Joyner Suzanne F Markis Marcia F Prescott Sherri F Zhu Waiman M

57 Pretice Hall © 200457 NOT OPERATOR SELECT emp_last_name, emp_first_name, emp_dpt_number FROM employee WHERE NOT emp_dpt_number = 7 ORDER BY emp_last_name; ORDER BY emp_last_name; emp_last_name emp_first_name emp_dpt_number ------------- -------------- -------------- Amin Hyder 3 Bordoloi Bijoy 1 Joyner Suzanne 3 Markis Marcia 3

58 Pretice Hall © 200458 Combining OR and AND Operators When the AND operator is combined with OR, the SQL Server will evaluate the condition connected by the AND first before any conditions connected with OR.When the AND operator is combined with OR, the SQL Server will evaluate the condition connected by the AND first before any conditions connected with OR. Parentheses must be used to force an order of operation.Parentheses must be used to force an order of operation.

59 Pretice Hall © 200459 Combining OR and AND Operators Contd. Q? Display a list of employees with a last name that begins with or is greater than the letter ‘E’, and who are either female or works in department number #1.

60 Pretice Hall © 200460 Combining OR and AND Operators Contd. 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 employee WHERE emp_last_name >= ‘E’ AND emp_gender = ‘F’ OR emp_dpt_number = 1 ORDER BY emp_last_name; Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- Bordoloi Bijoy M 1 Joyner Suzanne F 3 Markis Marcia F 3 Prescott Sherri F 7 Is this answer correct?

61 Pretice Hall © 200461 Combining OR and AND Operators 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 employee 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; Last Name First Name emp_gender emp_dpt_number ------------ ------------ ---------- -------------- Joyner Suzanne F 3 Markis Marcia F 3 Prescott Sherri F 7

62 Pretice Hall © 200462 LISTS (IN AND NOT IN) There are two operators that are designed for testing to determine if data stored in a table column is either in or not in a list or set of values.There are two operators that are designed for testing to determine if data stored in a table column 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 queries that might otherwise require a large number of either OR logical operators or an unwieldy use of the NOT logical operator.These operators greatly simplify the task of writing queries that might otherwise require a large number of either OR logical operators or an unwieldy use of the NOT logical operator.

63 Pretice Hall © 200463 Using IN Operator 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 employee WHERE emp_salary = 43000 OR emp_salary = 30000 OR emp_salary = 25000 ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ------------ Amin Hyder 25000.00 Markis Marcia 25000.00 Prescott Sherri 25000.00 Bock Douglas 30000.00 Zhu Waiman 43000.00 Joyner Suzanne 43000.00

64 Pretice Hall © 200464 Using IN Operator Contd. 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 employee WHERE emp_salary IN (43000, 30000, 25000) ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ------------ Amin Hyder 25000.00 Markis Marcia 25000.00 Prescott Sherri 25000.00 Bock Douglas 30000.00 Zhu Waiman 43000.00 Joyner Suzanne 43000.00

65 Pretice Hall © 200465 Using IN Operator Contd. 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 employee WHERE emp_city IN (‘Marina’, ‘Edwardsville’, ‘St. Louis’) ORDER BY emp_city; Last Name First Name City --------------- --------------- ------------------------- Bordoloi Bijoy Edwardsville Prescott Sherri Edwardsville Amin Hyder Marina Joyner Suzanne Marina Bock Douglas St. Louis Zhu Waiman St. Louis

66 Pretice Hall © 200466 Using 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 three salary figures listed earlierTo get the list of employees who did not earn the three salary figures listed earlier 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 employee WHERE emp_salary NOT IN (43000, 30000, 25000) ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ------------ Joshi Dinesh 38000.00 Bordoloi Bijoy 55000.00

67 Pretice Hall © 200467 RANGES (BETWEEN AND NOT BETWEEN) SQL provides two operators, BETWEEN and NOT BETWEEN that can simplify the range of values in a query.SQL provides two operators, BETWEEN and NOT BETWEEN that can simplify the range of values in a query. This eliminates the need to use a more complex WHERE clause involving the use of the AND logical operator.This eliminates the need to use a more complex WHERE clause involving the use of the AND logical operator.

68 Pretice Hall © 200468 Using 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", 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 employee WHERE emp_salary >= 25000 AND emp_salary = 25000 AND emp_salary <= 40000 ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Amin Hyder $ 25,000.00 Markis Marcia $ 25,000.00 Prescott Sherri $ 25,000.00 Bock Douglas $ 30,000.00 Joshi Dinesh $ 38,000.00

69 Pretice Hall © 200469 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", 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 employee WHERE emp_salary BETWEEN 25000 AND 40000 ORDER BY emp_salary; Last Name First Name Salary --------------- --------------- ----------- Amin Hyder $ 25,000.00 Markis Marcia $ 25,000.00 Prescott Sherri $ 25,000.00 Bock Douglas $ 30,000.00 Joshi Dinesh $ 38,000.00

70 Pretice Hall © 200470 Specifying More Than One Salary Range 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 WHERE emp_salary BETWEEN 25000 AND 30000 OR emp_salary BETWEEN 40000 AND 43000 OR emp_salary BETWEEN 40000 AND 43000 ORDER BY emp_salary; Last Name Salary --------------- ----------- Amin $ 25,000.00 Markis $ 25,000.00 Prescott $ 25,000.00 Bock $ 30,000.00 Zhu $ 43,000.00 Joyner $ 43,000.00

71 Pretice Hall © 200471 Using the NOT BETWEEN Operator 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 WHERE emp_salary NOT BETWEEN 28000 AND 50000 ORDER BY emp_salary; Last Name Salary --------------- ----------- Amin $ 25,000.00 Markis $ 25,000.00 Prescott $ 25,000.00 Bordoloi $ 55,000.00

72 Pretice Hall © 200472 LIKE AND NOT LIKE The LIKE and NOT LIKE operators can be used to search for data rows containing incomplete or partial character strings within a data column.The LIKE and NOT LIKE operators can be used to search for data rows containing incomplete or partial character strings within a data column. The next query searches the employee table for employee names that begin with the characters ‘Bo’.The next query searches the employee table for employee names that begin with the characters ‘Bo’. The search is case-sensitive meaning that ‘Bo’ is not equivalent to ‘BO’.The search is case-sensitive meaning that ‘Bo’ is not equivalent to ‘BO’. 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 employee WHERE emp_last_name LIKE 'Bo%';

73 Pretice Hall © 200473 LIKE AND NOT LIKE Wild cardMeaning % (percent) any string of zero or more characters _ (underscore)any single character [ ] (brackets)any single character within a specified range such as ‘a’ to ‘d’, inclusive [a-d] or a set of characters such as [aeiouy] [^] (not brackets)any single character not in the specified range or set (e.g., [^a-f] )

74 Pretice Hall © 200474 MORE EXAMPLES LIKE ‘%inger’ will search for every name that ends with ‘inger’ (Ringer, Stringer).LIKE ‘%inger’ will search for every name that ends with ‘inger’ (Ringer, Stringer). LIKE ‘%en%’ will search for every name that has the letters ‘en’ in the name (Bennet, Green, McBadden).LIKE ‘%en%’ will search for every name that has the letters ‘en’ in the name (Bennet, Green, McBadden). LIKE ‘_heryl’ will search for every six-letter name ending with ‘heryl’ (Cheryl). Notice how this is different than ‘%heryl’,which would return names that are six characters or more.LIKE ‘_heryl’ will search for every six-letter name ending with ‘heryl’ (Cheryl). Notice how this is different than ‘%heryl’,which would return names that are six characters or more.

75 Pretice Hall © 200475 MORE EXAMPLES Contd. LIKE ‘[CK]ars[eo]n’ will search for every six-letter name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ or ‘o’ between ‘ars’ and ‘n’ (e.g., 'Carsen,' ‘Karsen,’ ‘Carson,’ and ‘Karson’.LIKE ‘[CK]ars[eo]n’ will search for every six-letter name that begins with a ‘C’ or ‘K’ and has the letter ‘e’ or ‘o’ between ‘ars’ and ‘n’ (e.g., 'Carsen,' ‘Karsen,’ ‘Carson,’ and ‘Karson’. LIKE ‘[M-Z]inger’ will search for all the names ending with ‘inger’ that begin with any single letter ‘M’ thru ‘Z’ (Ringer).LIKE ‘[M-Z]inger’ will search for all the names ending with ‘inger’ that begin with any single letter ‘M’ thru ‘Z’ (Ringer). LIKE ‘M[^c]%’ will search for all the names that begin with ‘M’ not having ‘c’ as the second letter.LIKE ‘M[^c]%’ will search for all the names that begin with ‘M’ not having ‘c’ as the second letter.

76 Pretice Hall © 200476 MORE EXAMPLES Contd. The SELECT statement shown below generates a result table that includes all DISTINCT rows where the employee social security number in the assignment table ends with the numbers 555.The SELECT statement shown below generates a result table that includes all DISTINCT rows where the employee social security number in the assignment table ends with the numbers 555. SELECT DISTINCT work_emp_ssn "Emp SSN" FROM assignment WHERE work_emp_ssn LIKE ‘%555’ Emp SSN ---------999555555

77 Pretice Hall © 200477 UNKNOWN VALUES (IS NULL and IS NOT NULL) NULL value is not synonymous with “zero” (numerical values) or “blank” (character values).NULL value is not synonymous with “zero” (numerical values) or “blank” (character values). NULL values allow users to distinguish between a deliberate entry of zero/blank and a non entry of data.NULL values allow users to distinguish between a deliberate entry of zero/blank and a non entry of data. SELECT * FROM assignment WHERE work_hours IS NULL; work_emp_ssn work_pro_number work_hours ------------ --------------- ---------- 999444444 1 NULL 999666666 20 NULL

78 Pretice Hall © 200478 MORE EXAMPLES Contd. SELECT * FROM assignment WHERE work_hours = 0; work_emp_ssn work_pro_number work_hours ------------ --------------- ---------- (0 row(s) affected) The query did not return a result table because none of the rows in the assignment table have a zero value for work_hours. Thus, you can see that zero (0) is a value, not an “unknown value.”The query did not return a result table because none of the rows in the assignment table have a zero value for work_hours. Thus, you can see that zero (0) is a value, not an “unknown value.”

79 Pretice Hall © 200479 MORE EXAMPLES The NOT NULL condition can also be tested.The NOT NULL condition can also be tested. SELECT * FROM assignment WHERE work_hours IS NOT NULL; (15 row(s) affected) The result table contains all the rows where work_hours column contains a value.The result table contains all the rows where work_hours column contains a value.

80 Pretice Hall © 200480 EXPRESSIONS IN SELECT CLAUSES An expression is formed by combining a column name or constant with an arithmetic operator.An expression is formed by combining a column name or constant with an arithmetic operator. The arithmetic operators used in SQL areThe arithmetic operators used in SQL are SYMBOLOPERATIONORDER *Multiplication1 /Division1 %Modulo1 +Addition2 -Subtraction2

81 Pretice Hall © 200481 EXAMPLE 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/12 "Monthly Salary" emp_salary/12 "Monthly Salary" FROM employee WHERE emp_salary/12 > 3500 ORDER BY emp_last_name; Last Name First Name Monthly Salary --------------- --------------- --------------------- Bordoloi Bijoy 4583.3333 Joyner Suzanne 3583.3333 Zhu Waiman 3583.3333

82 Pretice Hall © 200482 EXPRESSIONS When expression is used in select with a column name it has no effect on the table’s underlying values.When expression is used in select with a column name it has no effect on the table’s underlying values. The data contained in each column must be numeric data.The data contained in each column must be numeric data. The result of an arithmetic operation on NULL is NULL.The result of an arithmetic operation on NULL is NULL.

83 Pretice Hall © 200483 Examples of Operations on Nulls SELECT work_emp_ssn "SSN", work_pro_number "Project", work_hours/40 "Avg Hours/Week" work_hours/40 "Avg Hours/Week" FROM assignment WHERE work_pro_number = 1 ORDER BY work_emp_ssn; SSN Project Avg Hours/Week --------- ------- -------------- 999111111 1.785000 999444444 1 NULL 999888888 1.525000

84 Pretice Hall © 200484 Examples of Operations on Nulls Contd. Table: Contract_Employee emp_id,emp_jobemp_salaryemp_bonus 10 BIG BOSS 100000NULL 20 LITTLE BOSS 50000NULL 30WARRIOR100002000 40WARRIOR100003000

85 Pretice Hall © 200485 Examples of Operations on Nulls Contd. SELECT emp_id, emp_job, emp_salary+emp_bonus "Total Comp" FROM contract_employee; emp_id emp_job Total Comp --------- --------------- --------------------- 10 BIG BOSS NULL 20 LITTLE BOSS NULL 30 WORKER 12000.0000 40 WORKER 14000.0000

86 Pretice Hall © 200486 SUMMARY Logical operators (AND and OR) in the WHERE clause add power to your queries.Logical operators (AND and OR) in the WHERE clause add power to your queries. When the AND operator is combined with OR, AND takes precedence over OR. Always use parentheses' to clarify the order of operation.When the AND operator is combined with OR, AND takes precedence over OR. Always use parentheses' to clarify the order of operation. IN AND NOT IN operators are used to compare a column against several values.IN AND NOT IN operators are used to compare a column against several values. The BETWEEN operators specifies an inclusive range of values.The BETWEEN operators specifies an inclusive range of values. Use the LIKE operator for incomplete search of character string.Use the LIKE operator for incomplete search of character string. Use the IS NULL operator when querying for unknown values.Use the IS NULL operator when querying for unknown values. The result of an arithmetic operation on NULL is NULL.The result of an arithmetic operation on NULL is NULL.


Download ppt "Pretice Hall © 20041 COS 346 Day 12. Pretice Hall © 20042 Agenda Questions?Questions? Quiz 1 correctedQuiz 1 corrected –1 A, 5 B’s, 1 C and 1 F Assignment."

Similar presentations


Ads by Google