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

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

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

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

Pretice Hall © 2004 1

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

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

Pretice Hall © 2004 2

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.

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

Pretice Hall © 2004 3

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.

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

Pretice Hall © 2004 4

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”.

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

Pretice Hall © 2004 5

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.

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

Pretice Hall © 2004 6

• 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

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

Pretice Hall © 2004 7

• 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.

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

Pretice Hall © 2004 8

• 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

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

Pretice Hall © 2004 9

• 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

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

Pretice Hall © 2004 10

• 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 Formatting Default Output Contd.Contd.

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

Pretice Hall © 2004 11

• 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 Formatting Default Output Contd.Contd.

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

Pretice Hall © 2004 12

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 Formatting Default Output Contd.Contd.

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

Pretice Hall © 2004 13

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 OutputFormatting Default OutputContd.Contd.

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

Pretice Hall © 2004 14

• 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.

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

Pretice Hall © 2004 15

• 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.

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

Pretice Hall © 2004 16

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 Formatting Default Output Contd.Contd.

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

Pretice Hall © 2004 17

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 Formatting Default Output Contd.Contd.

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

Pretice Hall © 2004 18

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.

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

Pretice Hall © 2004 19

• 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

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

Pretice Hall © 2004 20

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’.

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

Pretice Hall © 2004 21

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’.

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

Pretice Hall © 2004 22

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'.

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

Pretice Hall © 2004 23

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…

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

Pretice Hall © 2004 24

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'.

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

Pretice Hall © 2004 25

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)

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

Pretice Hall © 2004 26

THE DISTINCT CLAUSETHE DISTINCT CLAUSEContd.Contd.The DISTINCT keyword also eliminates The DISTINCT keyword also eliminates duplicate rows where more than one column is displayed in duplicate rows where more than one column is displayed in the result table.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)

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

Pretice Hall © 2004 27

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

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

Pretice Hall © 2004 28

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

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

Pretice Hall © 2004 29

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’;

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

Pretice Hall © 2004 30

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

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

Pretice Hall © 2004 31

Comparison Operators in the Comparison Operators in the WHERE ClauseWHERE 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.

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

Pretice Hall © 2004 32

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.

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

Pretice Hall © 2004 33

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

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

Pretice Hall © 2004 34

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.

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

Pretice Hall © 2004 35

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 DESC emp_salary;ORDER BY DESC 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'.

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

Pretice Hall © 2004 36

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

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

Pretice Hall © 2004 37

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.

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

Pretice Hall © 2004 38

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

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

Pretice Hall © 2004 39

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

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

Pretice Hall © 2004 40

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

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

Pretice Hall © 2004 41

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.

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

Pretice Hall © 2004 42

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)

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

Pretice Hall © 2004 43

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.