Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Pretice Hall © 20041 Chapter 3: Single Table Query Basics SQL for SQL Server Bijoy Bordoloi and Douglas Bock."— Presentation transcript:

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

2 Pretice Hall © 20042 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.

3 Pretice Hall © 20043 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.

4 Pretice Hall © 20044 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”.

5 Pretice Hall © 20045 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.

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

7 Pretice Hall © 20047 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.

8 Pretice Hall © 20048 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

9 Pretice Hall © 20049 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

10 Pretice Hall © 200410 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.

11 Pretice Hall © 200411 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.

12 Pretice Hall © 200412 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.

13 Pretice Hall © 200413 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.

14 Pretice Hall © 200414 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.

15 Pretice Hall © 200415 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.

16 Pretice Hall © 200416 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.

17 Pretice Hall © 200417 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.

18 Pretice Hall © 200418 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.

19 Pretice Hall © 200419 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

20 Pretice Hall © 200420 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’.

21 Pretice Hall © 200421 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’.

22 Pretice Hall © 200422 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'.

23 Pretice Hall © 200423 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…

24 Pretice Hall © 200424 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'.

25 Pretice Hall © 200425 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)

26 Pretice Hall © 200426 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)

27 Pretice Hall © 200427 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

28 Pretice Hall © 200428 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

29 Pretice Hall © 200429 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’;

30 Pretice Hall © 200430 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

31 Pretice Hall © 200431 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.

32 Pretice Hall © 200432 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.

33 Pretice Hall © 200433 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

34 Pretice Hall © 200434 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.

35 Pretice Hall © 200435 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'.

36 Pretice Hall © 200436 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

37 Pretice Hall © 200437 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.

38 Pretice Hall © 200438 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

39 Pretice Hall © 200439 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

40 Pretice Hall © 200440 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

41 Pretice Hall © 200441 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.

42 Pretice Hall © 200442 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)

43 Pretice Hall © 200443 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.


Download ppt "Pretice Hall © 20041 Chapter 3: Single Table Query Basics SQL for SQL Server Bijoy Bordoloi and Douglas Bock."

Similar presentations


Ads by Google