pretice hall © 20041 cos 346 day 12. 7-2 agenda questions?questions? assignment 5 dueassignment 5...

106
Pretice Hall © 2004 1 COS 346 COS 346 Day 12 Day 12

Post on 21-Dec-2015

220 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 1

COS 346COS 346

Day 12Day 12

Page 2: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

7-2

AgendaAgenda

• Questions?Questions?• Assignment 5 DueAssignment 5 Due• Assignment 6 Posted Assignment 6 Posted

– Due March 23 Due March 23 • Capstone Progress Report Overdue Capstone Progress Report Overdue • Erwin tutorialErwin tutorial

– http://www.isqa.unomaha.edu/wolcott/tutorials/erwin/ERwin.html • New Time line (next slide)New Time line (next slide)

– One less quiz (3 @ 10%)One less quiz (3 @ 10%)– One less assignment ( 9 @ 4.4444%)One less assignment ( 9 @ 4.4444%)

• Still drop lowest score Still drop lowest score

• More on SQL & SQL ServerMore on SQL & SQL Server– We do chap 2-10 in SQL Text next We do chap 2-10 in SQL Text next

Page 3: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

New time lineNew time line

• MarchMarch– 16 - SQL 16 - SQL

• Assignment 5 dueAssignment 5 due– 19 - SQL19 - SQL– 23 - SQL23 - SQL

• Assignment 6 dueAssignment 6 due– 26 - SQL 26 - SQL – 31 - SQL 31 - SQL

• Assignment 7 dueAssignment 7 due• Progress reportProgress report

• AprilApril– 2 Database Redesign 2 Database Redesign – 6 - 6 - Database redesign Database redesign

• Quiz 2Quiz 2• Assignment 8 due Assignment 8 due

– 9 - Managing Multiuser databases 9 - Managing Multiuser databases

– 13 - Managing Multiuser 13 - Managing Multiuser databases databases

• Assignment 9 due Assignment 9 due

– 16 Managing Multiuser databases 16 Managing Multiuser databases

– 20 Database access standards20 Database access standards

• Progress report Progress report

– 23 - Database access standards23 - Database access standards

• Assignment 10 dueAssignment 10 due

– 2727

• Quiz 3Quiz 3

• Capstones Presentations Due Capstones Presentations Due

Page 4: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 4

Chapter 2 : Creating Tables Chapter 2 : Creating Tables and Indexesand Indexes

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

Page 5: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 5

ObjectivesObjectives

• Learn how to name tables, columns, and Learn how to name tables, columns, and constraints.constraints.

• Select appropriate data types.Select appropriate data types.• Create, Alter, and Drop tables.Create, Alter, and Drop tables.• Specify primary and foreign keys. Specify primary and foreign keys. • Specify and maintain referential integrity Specify and maintain referential integrity

among tables.among tables.• Insert, Delete, and Update rows in tables.Insert, Delete, and Update rows in tables.• Create and drop indexes.Create and drop indexes.

Page 6: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 6

• One of the first steps in creating a One of the first steps in creating a database is to create the tables that will database is to create the tables that will store organization’s data. store organization’s data.

• In order to create a table, four pieces of In order to create a table, four pieces of information must be determined:information must be determined:

1.1. The table nameThe table name

2.2. The column (field) namesThe column (field) names

3.3. Column data types andColumn data types and

4.4. Column sizesColumn sizes

Table CreationTable Creation

Page 7: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 7

• Table and Column names should be meaningful Table and Column names should be meaningful and reflect the nature of the data that is to be and reflect the nature of the data that is to be stored.stored.

• If the data stored is about the products that a If the data stored is about the products that a firm sells, then the table should probably be firm sells, then the table should probably be named named product! product!

• If products are identified by a string of eight If products are identified by a string of eight characters, then the column that stores the characters, then the column that stores the product information data should be named product information data should be named product_numberproduct_number, or , or product_code.product_code.

Naming Tables and ColumnsNaming Tables and Columns

Page 8: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 8

Picking a Data typePicking a Data type

• The data type chosen for a column determines The data type chosen for a column determines the nature of the data that can be stored in the the nature of the data that can be stored in the column.column.

• This is termed the This is termed the Domain Domain of valid column of valid column values.values.

Page 9: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 9

Data typeData type

• Transact-SQL provides numerous data Transact-SQL provides numerous data types categorized as follows:types categorized as follows:

• Numeric data types.Numeric data types.• String or Character data types – this String or Character data types – this

includes binary data (bit strings).includes binary data (bit strings).• Date and/or time data types.Date and/or time data types.• Derived data types.Derived data types.• Special, new data.Special, new data.

Page 10: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 10

Integer Numeric Data TypesInteger Numeric Data Types

• BIGINT: Integer values requiring 8 bytes BIGINT: Integer values requiring 8 bytes of storage. ( +/- 2of storage. ( +/- 232)32)

• INTEGER or INT: Integer values INTEGER or INT: Integer values requiring 4 bytes of storage. INT is short requiring 4 bytes of storage. INT is short for INTEGER.for INTEGER.

• SMALLINT: Integer values requiring 2 SMALLINT: Integer values requiring 2 bytes of storage. bytes of storage.

• TINYINT: Integer values (non-negative TINYINT: Integer values (non-negative only) that can be stored in 1 byte. (2only) that can be stored in 1 byte. (28)8)

Page 11: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 11

Real Numeric Data TypesReal Numeric Data Types

DECIMAL(p,[s]) or DEC:DECIMAL(p,[s]) or DEC: Fixed point values with precision Fixed point values with precision pp that specifies the total number of digits, with assumed that specifies the total number of digits, with assumed decimal point of scale decimal point of scale ss to the right of the decimal. to the right of the decimal. Memory requirements vary from 2 to 17 bytes Memory requirements vary from 2 to 17 bytes depending on the value of depending on the value of pp. The specification of a . The specification of a value for value for ss is optional. is optional.

NUMERIC(p,[s]):NUMERIC(p,[s]): Same as DECIMAL. Same as DECIMAL.REAL:REAL: Floating point values. Positive values stored range Floating point values. Positive values stored range

from 2.23E-308 to 1.79E+308. Negative values stored from 2.23E-308 to 1.79E+308. Negative values stored range from -2.23E-308 to -1.79E+308. range from -2.23E-308 to -1.79E+308.

FLOAT[(p)]:FLOAT[(p)]: Floating point values like REAL where the Floating point values like REAL where the parameter parameter pp specifies the precision. When specifies the precision. When pp < 25, the < 25, the number is stored using 4 bytes and is single-precision. number is stored using 4 bytes and is single-precision. When When pp >= 25, the number is stored using 8 bytes and is >= 25, the number is stored using 8 bytes and is double-precision.double-precision.

Page 12: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 12

Monetary Numeric Data TypesMonetary Numeric Data Types

• MONEY: Monetary values requiring 8 MONEY: Monetary values requiring 8 bytes of storage. This corresponds to 8 bytes of storage. This corresponds to 8 byte DECIMAL values rounded to four byte DECIMAL values rounded to four digits to the right of the decimal point.digits to the right of the decimal point.

– $123.4567$123.4567

• SMALLMONEY: Monetary values SMALLMONEY: Monetary values requiring 4 bytes of storage.requiring 4 bytes of storage.

– $123.46$123.46

Page 13: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 13

Character (String) Data TypesCharacter (String) Data Types

CHAR[(n)] or CHARACTER(n):CHAR[(n)] or CHARACTER(n): Fixed-length string Fixed-length string values where values where nn is the number of characters in the string. is the number of characters in the string. The parameter The parameter nn cannot be greater than 8,000. The cannot be greater than 8,000. The default length when default length when nn is omitted is 1 character. is omitted is 1 character.

NCHAR[(n)]:NCHAR[(n)]: Fixed-length string values storing Unicode Fixed-length string values storing Unicode character data. Each NCHAR character requires 2 bytes character data. Each NCHAR character requires 2 bytes of storage whereas CHAR data requires 1 byte of storage of storage whereas CHAR data requires 1 byte of storage per character. The parameter per character. The parameter nn cannot be greater than cannot be greater than 4,000.4,000.

VARCHAR[(n)]:VARCHAR[(n)]: Variable-length string values where Variable-length string values where nn is is the maximum number of characters in the string. The the maximum number of characters in the string. The parameter parameter nn cannot be greater than 8,000. Also termed cannot be greater than 8,000. Also termed CHAR VARYING and CHARACTER VARYING.CHAR VARYING and CHARACTER VARYING.

Page 14: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 14

Character (String) Data Types Contd.Character (String) Data Types Contd.

NVARCHAR[(n)]:NVARCHAR[(n)]: Variable-length string values Variable-length string values storing Unicode characters. This data type has storing Unicode characters. This data type has the same characteristics of storage as NCHAR.the same characteristics of storage as NCHAR.

TEXT[(n)]:TEXT[(n)]: Fixed-length string up to Fixed-length string up to 2,147,483,647 characters. 2,147,483,647 characters.

NTEXT[(n)]:NTEXT[(n)]: Stores large string values of varying Stores large string values of varying lengths with a maximum length of lengths with a maximum length of 1,073,741,823 characters. NTEXT data 1,073,741,823 characters. NTEXT data characters are stored using the Unicode scheme characters are stored using the Unicode scheme of 2 bytes per character while TEXT data of 2 bytes per character while TEXT data requires 1 byte of storage per character.requires 1 byte of storage per character.

Page 15: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 15

Binary (and Bit) String Data TypesBinary (and Bit) String Data Types

BINARY[(n)]:BINARY[(n)]: Fixed-length bit string of exactly Fixed-length bit string of exactly nn bytes where the maximum value of the bytes where the maximum value of the parameter parameter nn is 8000. is 8000.

VARBINARY[(n)]:VARBINARY[(n)]: Variable-length bit string where Variable-length bit string where nn is the maximum number of bytes stored. The is the maximum number of bytes stored. The maximum value of the parameter maximum value of the parameter nn is 8000. is 8000.

IMAGE[(n)]:IMAGE[(n)]: Fixed-length bit strings of nearly Fixed-length bit strings of nearly unlimited values ~2 GB. unlimited values ~2 GB.

BIT:BIT: Stores Boolean data. Each value requires only Stores Boolean data. Each value requires only a single bit of storage. The values stored are a single bit of storage. The values stored are limited to TRUE, FALSE, or NULL.limited to TRUE, FALSE, or NULL.

Page 16: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 16

Date and Time Data TypesDate and Time Data Types

DATETIME:DATETIME: Date and time data requiring 4 Date and time data requiring 4 bytes of storage for the date and 4 bytes of bytes of storage for the date and 4 bytes of storage for the time.storage for the time.

# of days from Jan 1, 1753# of days from Jan 1, 1753

SMALLDATETIME:SMALLDATETIME: Date and time data Date and time data requiring 2 bytes of storage for the date requiring 2 bytes of storage for the date and 2 bytes of storage for the time.and 2 bytes of storage for the time.

# of days from Jan 1, 1900# of days from Jan 1, 1900

Page 17: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 17

DerivedDerived Data TypesData Types

SYSNAME:SYSNAME: Columns defined as Columns defined as NVARCHAR(128) that store the names of NVARCHAR(128) that store the names of

database objects in the system catalogdatabase objects in the system catalog..

TIMESTAMP:TIMESTAMP: Columns defined as VARBINARY(8) Columns defined as VARBINARY(8) or BINARY(8) that stores the current value for each or BINARY(8) that stores the current value for each database that is used to timestamp rows that are inserted database that is used to timestamp rows that are inserted or updated that contain a TIMESTAMP column. or updated that contain a TIMESTAMP column.

Page 18: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 18

CREATING A TABLECREATING A TABLE

• Create a simple table that stores five items Create a simple table that stores five items of information about employees for an of information about employees for an organization.organization.

• The table is named “employee” and stores The table is named “employee” and stores information about each employee’s social information about each employee’s social security number, last name, first name, security number, last name, first name, date hired, and annual salary. date hired, and annual salary.

Page 19: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 19

Table CreationTable Creation

CREATE TABLE employee (CREATE TABLE employee (emp_ssn emp_ssn CHAR(9),CHAR(9),emp_last_name emp_last_name VARCHAR(25),VARCHAR(25),emp_first_name emp_first_name VARCHAR(25),VARCHAR(25),emp_date_of_birth DATETIME,emp_date_of_birth DATETIME,emp_salary emp_salary MONEYMONEY););

• The table named “employee”, is specified The table named “employee”, is specified along with five data columns.along with five data columns.

• Each column has a name that is unique within Each column has a name that is unique within the table and is specified to store a specific the table and is specified to store a specific type of data.type of data.

Page 20: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 20

Data Integrity and Table ConstraintsData Integrity and Table Constraints

• The term data integrity simply means that the The term data integrity simply means that the data stored in the table is valid.data stored in the table is valid.

• There are different types of data integrity, often There are different types of data integrity, often referred to as constraints.referred to as constraints.

• The specifications of different data types aid in The specifications of different data types aid in maintaining certain aspects of the data stored for maintaining certain aspects of the data stored for employees.employees.

Page 21: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 21

NOT NULL ConstraintNOT NULL Constraint

• A NOT NULL constraint means that a data row A NOT NULL constraint means that a data row must have a value for the column specified as must have a value for the column specified as NOT NULL.NOT NULL.

• A fairly standard practice is to assign each A fairly standard practice is to assign each constraint a constraint a unique constraint name.unique constraint name.

• It is common to use either a prefix or suffix to It is common to use either a prefix or suffix to denote the type of constraint. In this text, we denote the type of constraint. In this text, we use prefixes. The prefix for a NOT NULL use prefixes. The prefix for a NOT NULL constraint is constraint is ‘nn.’‘nn.’

ExampleExampleemp_last_name VARCHAR(25)emp_last_name VARCHAR(25)

CONSTRAINT nn_emp_last_name NOT NULLCONSTRAINT nn_emp_last_name NOT NULL

Page 22: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 22

PRIMARY KEY ConstraintPRIMARY KEY Constraint

Each table must normally contain a Each table must normally contain a column or set of columns that uniquely column or set of columns that uniquely identifies rows of data that are stored in identifies rows of data that are stored in the table. This column or set of columns is the table. This column or set of columns is referred to as the referred to as the primary key.primary key. Example:Example:

emp_ssnemp_ssn CHAR(9)CHAR(9) CONSTRAINT pk_employee PRIMARY KEY,CONSTRAINT pk_employee PRIMARY KEY,……..……..

Page 23: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 23

Composite PRIMARY KEY ConstraintComposite PRIMARY KEY Constraint

• If a table requires two or more columns in order to If a table requires two or more columns in order to identify each row, the primary key is termed a identify each row, the primary key is termed a composite composite primary key.primary key.

Example:Example:CREATE TABLE assignment (CREATE TABLE assignment ( work_emp_ssn CHAR(9),work_emp_ssn CHAR(9), work_pro_number SMALLINT,work_pro_number SMALLINT, work_hours DECIMAL (5,1),work_hours DECIMAL (5,1),CONSTRAINT pk_assignment CONSTRAINT pk_assignment PRIMARY KEY ( work_emp_ssn, work_pro_number ),PRIMARY KEY ( work_emp_ssn, work_pro_number ),…………..…………..

Page 24: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 24

CHECK ConstraintCHECK Constraint

• Sometimes the data values stored in a specific Sometimes the data values stored in a specific column must fall within some acceptable range column must fall within some acceptable range of values.of values.

• A CHECK constraint is used to enforce this data A CHECK constraint is used to enforce this data limit.limit.emp_salaryemp_salary MONEYMONEY CONSTRAINT ck_emp_salary CONSTRAINT ck_emp_salary CHECK (emp_salary <= 85000), CHECK (emp_salary <= 85000),   

Page 25: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 25

UNIQUE ConstraintUNIQUE Constraint

• Sometimes it is necessary to enforce uniqueness for Sometimes it is necessary to enforce uniqueness for a column value that is not a primary key column.a column value that is not a primary key column.

• The The UNIQUE UNIQUE constraint can be used to enforce this constraint can be used to enforce this rule. rule.

• Assume that each parking space for the organization Assume that each parking space for the organization is numbered and that no two employees can be is numbered and that no two employees can be assigned the same parking space.assigned the same parking space.

emp_parking_spaceemp_parking_space INT INT CONSTRAINT un_emp_parking_space CONSTRAINT un_emp_parking_space

UNIQUE,UNIQUE,

Page 26: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 26

Commands to Manage and Alter TablesCommands to Manage and Alter Tables

Viewing a Table DescriptionViewing a Table Description

• The SQL Query Analyzer provides the The SQL Query Analyzer provides the ability to examine the columns that ability to examine the columns that comprise a table through the comprise a table through the object object browserbrowser facility. facility.

Page 27: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 27

Viewing a Table DescriptionViewing a Table Description

Page 28: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 28

Altering a column for an existing TableAltering a column for an existing Table

• Modifying existing tables to either add new Modifying existing tables to either add new columns or alter existing columns can be columns or alter existing columns can be accomplished with the ALTER TABLE accomplished with the ALTER TABLE statement.statement.

• The current data type of the The current data type of the emp_parking_space emp_parking_space column is INT (INTEGER). Due to growth in column is INT (INTEGER). Due to growth in the availability of employee parking spaces, you the availability of employee parking spaces, you have determined that it is necessary to modify have determined that it is necessary to modify the definition of this column to specify a the definition of this column to specify a BIGINT data type. BIGINT data type.

Page 29: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 29

ALTER TABLE CommandALTER TABLE Command

• The ALTER TABLE command can be used to modify The ALTER TABLE command can be used to modify the the emp_parking_space emp_parking_space column to specify the BIGINT column to specify the BIGINT data type.data type.

ALTER TABLE employee DROP CONSTRAINT ALTER TABLE employee DROP CONSTRAINT un_emp_parking_space;un_emp_parking_space;

ALTER TABLE employee ALTER COLUMN emp_parking_space ALTER TABLE employee ALTER COLUMN emp_parking_space BIGINT;BIGINT;

ALTER TABLE employee ALTER TABLE employee

ADD CONSTRAINT un_emp_parking_space ADD CONSTRAINT un_emp_parking_space

UNIQUE (emp_parking_space);UNIQUE (emp_parking_space);

Page 30: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 30

Adding New ColumnsAdding New Columns

• The ALTER TABLE command can be used to The ALTER TABLE command can be used to add a new column to the employee table.add a new column to the employee table.

• Suppose that an organization recognizes the Suppose that an organization recognizes the need to track the gender of employees in order to need to track the gender of employees in order to meet a governmental reporting requirement, an meet a governmental reporting requirement, an emp_genderemp_gender column can be added to the column can be added to the employee table.employee table.

ALTER TABLE employee ADD ALTER TABLE employee ADD

emp_gender CHAR(1);emp_gender CHAR(1);

Page 31: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 31

Relating Tables – Identifying Foreign Relating Tables – Identifying Foreign KeysKeys

• Normally, in a relational database, data Normally, in a relational database, data rows in one table are related to data rows rows in one table are related to data rows in other tables.in other tables.

• The The department department table will store table will store information about departments within the information about departments within the organization.organization.

• Each department is identified by a unique, Each department is identified by a unique, 2-digit department number (primary key). 2-digit department number (primary key).

Page 32: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 32

Relating Tables- Identifying Foreign Keys Contd.Relating Tables- Identifying Foreign Keys Contd.

CREATE TABLE department (CREATE TABLE department ( dpt_nodpt_no SMALLINTSMALLINT CONSTRAINT pk_department PRIMARY KEY,CONSTRAINT pk_department PRIMARY KEY, dpt_namedpt_name VARCHAR2(20)VARCHAR2(20) CONSTRAINT nn_dpt_name NOT NULLCONSTRAINT nn_dpt_name NOT NULL););

• Employees are generally assigned to work in Employees are generally assigned to work in departments. In an organization, at a given time, departments. In an organization, at a given time, an employee is assigned to a single department.an employee is assigned to a single department.

• In order to link rows in the In order to link rows in the employee employee table to table to rows in rows in department department table we need to introduce a table we need to introduce a new type of constraint, the FOREIGN KEY new type of constraint, the FOREIGN KEY constraint. constraint.

Page 33: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 33

Relating Tables- Identifying Foreign Keys Contd.Relating Tables- Identifying Foreign Keys Contd.

• Foreign keys (FKs) are columns in one table that Foreign keys (FKs) are columns in one table that reference primary key (PK) values in another or reference primary key (PK) values in another or in the same table.in the same table.

• Let’s relate employee rows to the PK column Let’s relate employee rows to the PK column named named dpt_no dpt_no in the department table. in the department table.

• The value stored to the The value stored to the emp_dpt_number emp_dpt_number column for any given column for any given employeeemployee row must match row must match a value stored in the a value stored in the dpt_no dpt_no column in the column in the department table.department table.

Page 34: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 34

Relating Tables-Relating Tables-Identifying Foreign Keys Identifying Foreign Keys

Contd.Contd.

Page 35: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 35

Relating Tables- Identifying Foreign Relating Tables- Identifying Foreign Keys Contd.Keys Contd.

CREATE TABLE employee ( CREATE TABLE employee ( emp_ssn CHAR(9)emp_ssn CHAR(9) CONSTRAINT pk_employee PRIMARY KEY,CONSTRAINT pk_employee PRIMARY KEY, emp_last_name VARCHAR(25)emp_last_name VARCHAR(25) CONSTRAINT nn_emp_last_name NOT NULL,CONSTRAINT nn_emp_last_name NOT NULL,……………………emp_parking_space INTemp_parking_space INT CONSTRAINT un_emp_parking_space UNIQUE,CONSTRAINT un_emp_parking_space UNIQUE, emp_gender CHAR(1) NULL,emp_gender CHAR(1) NULL, emp_dpt_number SMALLINT,emp_dpt_number SMALLINT,CONSTRAINT fk_emp_dpt FOREIGN KEY (emp_dpt_number)CONSTRAINT fk_emp_dpt FOREIGN KEY (emp_dpt_number) REFERENCES department,REFERENCES department,););

Page 36: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 36

MAINTAINING REFERENTIAL INTEGRITYMAINTAINING REFERENTIAL INTEGRITY

• FOREIGN KEY constraints are also referred to FOREIGN KEY constraints are also referred to as referential integrity constraints, and assist in as referential integrity constraints, and assist in maintaining database integrity.maintaining database integrity.

• Referential integrity stipulates that values of a Referential integrity stipulates that values of a foreign key must correspond to values of a foreign key must correspond to values of a primary key in the table that it references. But primary key in the table that it references. But what happens if the primary key values change what happens if the primary key values change or the row that is referenced is deleted or or the row that is referenced is deleted or updated? updated?

Page 37: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 37

MAINTAINING REFERENTIAL MAINTAINING REFERENTIAL INTEGRITYINTEGRITY

Contd.Contd.

Page 38: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 38

MAINTAINING REFERENTIAL INTEGRITY MAINTAINING REFERENTIAL INTEGRITY Contd.Contd.

What if some specific employee, say, Waiman What if some specific employee, say, Waiman Zhu decides to seek employment elsewhere and Zhu decides to seek employment elsewhere and leaves The Company? If Zhu's row is deleted leaves The Company? If Zhu's row is deleted from the from the employeeemployee table, the table, the dependentdependent table table will have three rows (dependents) that do not will have three rows (dependents) that do not belong to an employee row. A special clause for belong to an employee row. A special clause for the FOREIGN KEY constraint enables the the FOREIGN KEY constraint enables the maintenance of referential integrity to prevent maintenance of referential integrity to prevent this type of problem. This is the ON DELETE this type of problem. This is the ON DELETE CASCADE clause. CASCADE clause.

Page 39: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 39

MAINTAINING REFERRENTIAL INTEGRITY Contd.MAINTAINING REFERRENTIAL INTEGRITY Contd.

CREATE TABLE dependent (CREATE TABLE dependent ( dep_emp_ssn CHAR(9),dep_emp_ssn CHAR(9), dep_name VARCHAR(50),dep_name VARCHAR(50), dep_gender CHAR(1) NULL,dep_gender CHAR(1) NULL, dep_date_of_birth DATETIME NULL,dep_date_of_birth DATETIME NULL, dep_relationship VARCHAR(10) NULL,dep_relationship VARCHAR(10) NULL,CONSTRAINT pk_dependent PRIMARY KEY CONSTRAINT pk_dependent PRIMARY KEY

(dep_emp_ssn, dep_name),(dep_emp_ssn, dep_name),CONSTRAINT fk_dep_emp_ssn CONSTRAINT fk_dep_emp_ssn FOREIGN KEY (dep_emp_ssn) REFERENCES employeeFOREIGN KEY (dep_emp_ssn) REFERENCES employee ON DELETE CASCADEON DELETE CASCADE););

Page 40: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 40

MAINTAINING REFERENTIAL INTEGRITY MAINTAINING REFERENTIAL INTEGRITY Contd.Contd.

Because of thisBecause of this special ON DELETE special ON DELETE CASCADE clause in the CASCADE clause in the dependentdependent table, table, if Zhu's row is deleted from the if Zhu's row is deleted from the employeeemployee table, this clause will cause Zhu's table, this clause will cause Zhu's dependent's to be deleted automatically dependent's to be deleted automatically from the from the dependentdependent table, thereby table, thereby maintaining referential integrity between maintaining referential integrity between the two tables.the two tables.

Page 41: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 41

MAINTAINING REFERENTIAL INTEGRITY MAINTAINING REFERENTIAL INTEGRITY Contd.Contd.

• The other ON DELETE clause option is to The other ON DELETE clause option is to specify NO ACTION as the object of the specify NO ACTION as the object of the clause. When NO ACTION is the option, clause. When NO ACTION is the option, any attempted deletion of an employee any attempted deletion of an employee row that has associated dependent rows row that has associated dependent rows will fail with an error from SQL Server. will fail with an error from SQL Server.

• SQL Server also supports the ON SQL Server also supports the ON

UPDATE CASCADE option. UPDATE CASCADE option.

Page 42: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 42

Dropping a TableDropping a Table

• Tables can be removed from the database with Tables can be removed from the database with the DROP TABLE command.the DROP TABLE command.

DROP TABLE assignment;DROP TABLE assignment;

• This command deletes both the table structure, This command deletes both the table structure, its data, related constraints, and indexes.its data, related constraints, and indexes.Note:Note: If you attempt to drop a table that is referenced If you attempt to drop a table that is referenced through FOREIGN KEY constraint by another table, through FOREIGN KEY constraint by another table, then the DROP TABLE statement will fail. For then the DROP TABLE statement will fail. For example, you cannot DROP the example, you cannot DROP the projectproject table without table without altering or dropping the altering or dropping the assignmentassignment table first. table first.

Page 43: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 43

Populating Tables: The INSERT CommandPopulating Tables: The INSERT Command

• The INSERT command is used to store The INSERT command is used to store data in tables.data in tables.

• The INSERT command is often embedded The INSERT command is often embedded in higher-level programming language in higher-level programming language applications as an embedded SQL applications as an embedded SQL command.command.

• We focus on two different forms of the We focus on two different forms of the INSERT command.INSERT command.

Page 44: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 44

POPULATING TABLES: THE INSERT POPULATING TABLES: THE INSERT Command Contd.Command Contd.

• The first form is used if a new row will The first form is used if a new row will have a value inserted into each column of have a value inserted into each column of the row. the row.

INSERT INTO table VALUES INSERT INTO table VALUES (column1 value, column2 (column1 value, column2 value, …);value, …);

INSERT INTO department VALUES (7, 'Production');INSERT INTO department VALUES (7, 'Production');INSERT INTO department VALUES (3, 'Admin and INSERT INTO department VALUES (3, 'Admin and

Records');Records');INSERT INTO department VALUES (1, 'Headquarters');INSERT INTO department VALUES (1, 'Headquarters');

Page 45: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 45

POPULATING TABLES: THE INSERT POPULATING TABLES: THE INSERT Command Contd.Command Contd.

• The second form of the INSERT command is used to The second form of the INSERT command is used to insert rows where some of the column data is insert rows where some of the column data is unknown (NULLunknown (NULL). ).

• This form of the INSERT command requires that you This form of the INSERT command requires that you specify the names of the columns for which data are specify the names of the columns for which data are being stored.being stored.

INSERT INTO table (column1 name, column2 name, . . .)INSERT INTO table (column1 name, column2 name, . . .) VALUES (column1 value, column2 value, . . .);VALUES (column1 value, column2 value, . . .);

INSERT INTO employee (emp_ssn, emp_last_name, INSERT INTO employee (emp_ssn, emp_last_name, emp_first_name,emp_salary) emp_first_name,emp_salary) VALUES ('999111111', 'Bock', 'Douglas', 30000);VALUES ('999111111', 'Bock', 'Douglas', 30000);  

Page 46: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 46

The DELETE CommandThe DELETE Command

• It removes one or more rows from a table. It removes one or more rows from a table. Multiple table delete operations are not Multiple table delete operations are not allowed in SQL. allowed in SQL.

• The syntax of the DELETE command is:The syntax of the DELETE command is:

DELETE FROM table_nameDELETE FROM table_name

[WHERE [WHERE conditioncondition];];

Page 47: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 47

The DELETE Command Contd.The DELETE Command Contd.

• As the WHERE clause is optional, you can As the WHERE clause is optional, you can easily delete all rows from a table by omitting easily delete all rows from a table by omitting a WHERE clause because the WHERE clause a WHERE clause because the WHERE clause limits the scope of the DELETE operation.limits the scope of the DELETE operation.

• For example, the DELETE FROM command For example, the DELETE FROM command shown here removes all rows in the shown here removes all rows in the assignmentassignment table. table.

DELETE FROM assignment;DELETE FROM assignment;

  

Page 48: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 48

The UPDATE CommandThe UPDATE Command

• Values stored in individual columns of Values stored in individual columns of selected rows can be modified (updated) with selected rows can be modified (updated) with the UPDATE command. the UPDATE command.

• Updating Updating columnscolumns is different from is different from alteringaltering columns. columns.

• The ALTER command changes the table The ALTER command changes the table structure, but leaves the table data unaffected.structure, but leaves the table data unaffected.

• The UPDATE command changes data in the The UPDATE command changes data in the table, not the table structure. table, not the table structure.

Page 49: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 49

The UPDATE Command Contd.The UPDATE Command Contd.

• The general syntax of the UPDATE The general syntax of the UPDATE command is: command is:

UPDATE UPDATE tabletableSET SET columncolumn = = expressionexpression [, [,columncolumn = =

expressionexpression]...]...

[WHERE [WHERE conditioncondition];];

UPDATE employee SET emp_salary = 45000UPDATE employee SET emp_salary = 45000

WHERE emp_ssn = '999444444';WHERE emp_ssn = '999444444';

Page 50: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 50

Committing TransactionsCommitting Transactions

• Unlike many other relational DBMS products such Unlike many other relational DBMS products such as Oracle, SQL Server automatically commits after as Oracle, SQL Server automatically commits after every INSERT, DELETE, or UPDATE operation. every INSERT, DELETE, or UPDATE operation.

• One option for controlling when transactions One option for controlling when transactions commit is to use explicit transaction specifications commit is to use explicit transaction specifications by grouping SQL statements within transaction by grouping SQL statements within transaction delimiters: BEGIN TRANSACTION and delimiters: BEGIN TRANSACTION and COMMIT TRANSACTION. COMMIT TRANSACTION.

• This is you “Save your bacon” command This is you “Save your bacon” command

Page 51: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 51

Committing Transactions Contd.Committing Transactions Contd.

BEGIN TRANSACTIONBEGIN TRANSACTIONDELETE FROM employeeDELETE FROM employee WHERE emp_ssn = '999111111';WHERE emp_ssn = '999111111';DELETE FROM employeeDELETE FROM employee WHERE emp_ssn = '999444444';WHERE emp_ssn = '999444444';COMMIT TRANSACTION;COMMIT TRANSACTION;

The BEGIN TRANSACTION statement begins an explicit transaction. Two The BEGIN TRANSACTION statement begins an explicit transaction. Two employee rows are deleted, but the change to the database does not employee rows are deleted, but the change to the database does not take place until the COMMIT TRANSACTION statement processes. take place until the COMMIT TRANSACTION statement processes.

At any point prior to execution of COMMIT TRANSACTION, the At any point prior to execution of COMMIT TRANSACTION, the ROLLBACK TRANSACTION statement can be used to cancel the ROLLBACK TRANSACTION statement can be used to cancel the deletions that are in-process. deletions that are in-process.

Page 52: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 52

COMPUTED (Derived)COLUMNSCOMPUTED (Derived)COLUMNS

• Sometimes you will want to store information in a column that Sometimes you will want to store information in a column that is derived from other information stored in the table. Examine is derived from other information stored in the table. Examine the CREATE TABLE statement shown below:the CREATE TABLE statement shown below:

CREATE TABLE equipment (CREATE TABLE equipment ( eqp_no CHAR(4)eqp_no CHAR(4) CONSTRAINT pk_equipment PRIMARY KEY,CONSTRAINT pk_equipment PRIMARY KEY, eqp_description VARCHAR(15),eqp_description VARCHAR(15), eqp_value MONEY,eqp_value MONEY, eqp_qty_on_hand SMALLINT,eqp_qty_on_hand SMALLINT, eqp_total_value AS eqp_value * eqp_qty_on_hand,eqp_total_value AS eqp_value * eqp_qty_on_hand, eqp_pro_number SMALLINT,eqp_pro_number SMALLINT,CONSTRAINT fk_eqp_pro_number FOREIGN KEY CONSTRAINT fk_eqp_pro_number FOREIGN KEY

(eqp_pro_number)(eqp_pro_number) REFERENCES project REFERENCES project ON DELETE CASCADE );ON DELETE CASCADE );

Page 53: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 53

COMPUTED (Derived) COLUMNS Contd.COMPUTED (Derived) COLUMNS Contd.

– When values are inserted into the table, it is not When values are inserted into the table, it is not necessary to insert a value for the necessary to insert a value for the eqp_total_valueeqp_total_value derived column. derived column.

– Data for a computed column is not actually stored; Data for a computed column is not actually stored; rather, it is computed at the time that data for the rather, it is computed at the time that data for the column is selected. column is selected.

– Likewise, if a value stored in a row for either the Likewise, if a value stored in a row for either the eqp_valueeqp_value or or eqp_qty_on_handeqp_qty_on_hand column(s) changes, column(s) changes, the value displayed for the corresponding the value displayed for the corresponding eqp_total_valueeqp_total_value computed column during a SELECT computed column during a SELECT operation is automatically updated.operation is automatically updated.

Page 54: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 54

INDEXESINDEXES

• Indexes are optional structures associated Indexes are optional structures associated with tables. with tables. Indexes facilitate the rapid Indexes facilitate the rapid retrieval of information from tables much like retrieval of information from tables much like the index of a book enables you to find the index of a book enables you to find specific topics in the book rapidly. specific topics in the book rapidly.

• There are different types of indexes including There are different types of indexes including those used to enforce primary key constraints, those used to enforce primary key constraints, unique indexes, non-unique indexes, unique indexes, non-unique indexes, composite indexes, and others. composite indexes, and others.

Page 55: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 55

INDEXESINDEXESContd. Contd.

Page 56: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 56

PRIMARY KEY indexesPRIMARY KEY indexes

• When a PRIMARY KEY constraint is When a PRIMARY KEY constraint is specified, SQL Server will automatically specified, SQL Server will automatically create a unique index to support rapid data create a unique index to support rapid data retrieval for the specified table.retrieval for the specified table.

• Without an index, a command that retrieves Without an index, a command that retrieves data will cause the DBMS to completely scan data will cause the DBMS to completely scan a table for rows that satisfy the retrieval a table for rows that satisfy the retrieval condition.condition.

• For example, consider the following SELECT For example, consider the following SELECT statement that will display a list of employees statement that will display a list of employees assigned to a specific department.assigned to a specific department.

Page 57: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 57

PRIMARY KEY indexes Contd.PRIMARY KEY indexes Contd.

SELECT emp_last_name,emp_first_name, SELECT emp_last_name,emp_first_name, emp_dpt_number FROM employeeemp_dpt_number FROM employee

WHERE emp_dpt_number = 7;WHERE emp_dpt_number = 7;

• If the If the employeeemployee table is not indexed on the table is not indexed on the emp_dpt_numberemp_dpt_number column, SQL Server will column, SQL Server will have to scan the entire table in order to satisfy have to scan the entire table in order to satisfy the query. the query.

Page 58: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 58

Creating an IndexCreating an Index

• The general form of the CREATE INDEX The general form of the CREATE INDEX command is:command is:

CREATE INDEX <index name> CREATE INDEX <index name>

ON<table name> (column1, ON<table name> (column1, column2column2……););

CREATE INDEX employee_emp_dpt_numberCREATE INDEX employee_emp_dpt_number

ON employee (emp_dpt_number);ON employee (emp_dpt_number);

Page 59: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 59

Creating a UNIQUE IndexCreating a UNIQUE Index

• The general form of the CREATE UNIQUE The general form of the CREATE UNIQUE INDEX command is:INDEX command is:

CREATE UNIQUE INDEX <index name> CREATE UNIQUE INDEX <index name>

ON <table name> (column1, ON <table name> (column1, column2column2……););

CREATE UNIQUE INDEX patient_pat_ssnCREATE UNIQUE INDEX patient_pat_ssn

ON patient (pat_ssn);ON patient (pat_ssn);

Page 60: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 60

Creating a Composite IndexCreating a Composite Index

• A A composite indexcomposite index (also called a (also called a concatenated indexconcatenated index) ) is an index created on multiple columns of a table.is an index created on multiple columns of a table.

• Columns in a composite index can appear in any Columns in a composite index can appear in any order and need not be adjacent columns in the table.order and need not be adjacent columns in the table.

• Composite indexes enhance row retrieval speed for Composite indexes enhance row retrieval speed for queries in which the WHERE clause references all or queries in which the WHERE clause references all or the leading portion of the columns in the composite the leading portion of the columns in the composite index. index.

• Generally the most commonly accessed or most Generally the most commonly accessed or most selective columns are listed first when creating the selective columns are listed first when creating the index. index.

Page 61: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 61

DROPPING IndexesDROPPING Indexes

• An index should not be retained unless it An index should not be retained unless it improves system processing in some fashion.improves system processing in some fashion.

• All indexes on a table must be updated All indexes on a table must be updated whenever row data is changed that is whenever row data is changed that is referenced by an index.referenced by an index.

• Useless indexes burden the system by adding Useless indexes burden the system by adding unnecessary maintenance and by needlessly unnecessary maintenance and by needlessly occupying disk space. These indexes should occupying disk space. These indexes should be dropped. be dropped.

Page 62: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 62

DROPPING Indexes Contd.DROPPING Indexes Contd.

• The syntax of the DROP INDEX command is The syntax of the DROP INDEX command is simple:simple:

DROP INDEX table_name.index_name; DROP INDEX table_name.index_name;

DROP INDEX DROP INDEX employee.employee_emp_dpt_number;employee.employee_emp_dpt_number;

Page 63: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Prentice Hall © 2004 63

SummarySummary• This chapter exposed you to the Data Definition This chapter exposed you to the Data Definition

Language (DDL) part of SQL.Language (DDL) part of SQL.• CREATE TABLE is the command that you use to CREATE TABLE is the command that you use to

define the structure of a table including selection define the structure of a table including selection and specification of: and specification of: – Appropriate data types and length.Appropriate data types and length.– Primary and foreign keys. Primary and foreign keys. – Various data integrity constraints such as NOT NULL, Various data integrity constraints such as NOT NULL,

CHECK, and UNIQUE.CHECK, and UNIQUE.– Referential integrity rules.Referential integrity rules.

• You also learned how to:You also learned how to:– DROP and ALTER the structural definition of tables.DROP and ALTER the structural definition of tables.– Insert, Delete, and Update rows in tables.Insert, Delete, and Update rows in tables.– Create and drop INDEXES.Create and drop INDEXES.

Page 64: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 64

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 65: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 65

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 66: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 66

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 67: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 67

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 68: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 68

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 69: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 69

• 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 70: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 70

• 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 71: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 71

• 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 72: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 72

• 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 73: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 73

• Using the CAST FunctionUsing the CAST Function

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

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

FROM employee;FROM employee;

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 74: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 74

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

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

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

FROM employee;FROM employee;

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 75: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 75

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

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

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

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 76: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 76

Using the CONVERT FunctionUsing the CONVERT Function

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

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 77: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 77

• 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 78: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 78

• 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 79: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 79

Using the CONVERT FunctionUsing the CONVERT Function

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

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

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 80: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 80

Using the CONVERT FunctionUsing the CONVERT Function

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

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

Formatting Default Output Contd.Formatting Default Output Contd.

Page 81: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 81

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 82: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 82

• 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 83: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 83

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 84: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 84

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 85: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 85

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 86: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 86

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 87: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 87

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 88: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 88

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 89: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 89

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

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

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

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

SELECT DISTINCT room_id, SELECT DISTINCT room_id, bed_type_id bed_type_id

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

Page 90: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 90

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 91: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 91

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 92: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 92

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 93: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 93

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 94: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 94

Comparison Operators in the WHERE ClauseComparison Operators in the WHERE Clause

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

Page 95: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 95

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 96: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 96

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 97: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 97

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 98: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 98

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

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

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

FROM employeeFROM employee

WHERE emp_salary > 35000WHERE emp_salary > 35000

ORDER BY ORDER BY DESCDESC emp_salary; emp_salary;

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

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

Page 99: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 99

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 100: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 100

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 clause of the TOP keyword with the ORDER BY clause to list the employees with the 2 largest salaries. to list the employees with the 2 largest salaries.

Page 101: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 101

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 102: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 102

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 103: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 103

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 104: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 104

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 105: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 105

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 106: Pretice Hall © 20041 COS 346 Day 12. 7-2 Agenda Questions?Questions? Assignment 5 DueAssignment 5 Due Assignment 6 PostedAssignment 6 Posted –Due March

Pretice Hall © 2004 106

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.