+ All Categories
Home > Documents > Prentice Hall © 20041 COS 346 Day 10. Prentice Hall © 20042 Agenda Questions?Questions? Assignment...

Prentice Hall © 20041 COS 346 Day 10. Prentice Hall © 20042 Agenda Questions?Questions? Assignment...

Date post: 19-Dec-2015
Category:
View: 216 times
Download: 0 times
Share this document with a friend
Popular Tags:
64
Prentice Hall © 2004 1 COS 346 COS 346 Day 10 Day 10
Transcript

Prentice Hall © 2004 1

COS 346COS 346

Day 10Day 10

Prentice Hall © 2004 2

AgendaAgenda

• Questions?Questions?• Assignment 3 CorrectedAssignment 3 Corrected

– 2 B’s, 4 C’s, 1 D and 2 F’s2 B’s, 4 C’s, 1 D and 2 F’s– Correct answers sent in WebCTCorrect answers sent in WebCT

• Assignment 4 is posted Assignment 4 is posted – Due Feb 23Due Feb 23

• Capstone Project Proposal Due Feb 27Capstone Project Proposal Due Feb 27– Must be a database project Must be a database project

• Quiz 1Quiz 1– Feb 23Feb 23– DP Chap 1-6, SQL Chap 1 & 2DP Chap 1-6, SQL Chap 1 & 2– 20 M/C and 5 Short Essay20 M/C and 5 Short Essay

• Creating Tables and Indexes in SQL ServerCreating Tables and Indexes in SQL Server

Prentice Hall © 2004 3

AFUM ScholarshipAFUM Scholarship• Last year AFUM awarded 3 $500 scholarshipsLast year AFUM awarded 3 $500 scholarships• CriteriaCriteria

– UMFK student that will have completed 24 Credits by this spring UMFK student that will have completed 24 Credits by this spring and is returning to UMFK next falland is returning to UMFK next fall

– Complete a Letter of Commitment to scholarship and serviceComplete a Letter of Commitment to scholarship and service– One Letter of recommendation from a faculty memberOne Letter of recommendation from a faculty member– A resumeA resume– Copy of your transcript (get from registrar)Copy of your transcript (get from registrar)

• Turn in all materials to Prof. Stephen Hansen by March 3, Turn in all materials to Prof. Stephen Hansen by March 3, 20062006– Room 232 Nadeau HallRoom 232 Nadeau Hall

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

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.

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

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

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.

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.

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)

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.

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

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.

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.

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 Variable-length bit string where where nn is the maximum number of bytes stored. is the maximum number of bytes stored. The maximum value of the parameter The 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.

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

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.

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.

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.

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.

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

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,……..……..

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 ),…………..…………..

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),   

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,

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.

Prentice Hall © 2004 27

Viewing a Table DescriptionViewing a Table Description

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.

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

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

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

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 rows table to rows in in department department table we need to introduce a new table we need to introduce a new type of constraint, the FOREIGN KEY constraint. type of constraint, the FOREIGN KEY constraint.

Prentice Hall © 2004 33

Relating Tables- Identifying Foreign Keys Relating Tables- Identifying Foreign Keys Contd.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.

Prentice Hall © 2004 34

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

Contd.Contd.

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,););

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?

Prentice Hall © 2004 37

MAINTAINING REFERENTIAL MAINTAINING REFERENTIAL INTEGRITYINTEGRITY

Contd.Contd.

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.

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

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.

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.

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.

Prentice Hall © 2004 43

Populating Tables: The INSERT Populating Tables: The INSERT CommandCommand

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

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');

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

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

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;

  

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.

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

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

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. The BEGIN TRANSACTION statement begins an explicit transaction. Two employee rows are deleted, but the change to the database does Two employee rows are deleted, but the change to the database does not take place until the COMMIT TRANSACTION statement not take place until the COMMIT TRANSACTION statement processes. 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.

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

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.

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.

Prentice Hall © 2004 55

INDEXESINDEXESContd. Contd.

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.

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.

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, column2…);ON<table name> (column1, column2…);

CREATE INDEX employee_emp_dpt_numberCREATE INDEX employee_emp_dpt_number

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

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, column2…);ON <table name> (column1, column2…);

CREATE UNIQUE INDEX patient_pat_ssnCREATE UNIQUE INDEX patient_pat_ssn

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

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.

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.

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;

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.

Prentice Hall © 2004 64

Exercise Exercise

• Log on to SQL server using enterprise Log on to SQL server using enterprise mangermanger– Littleblack or local Littleblack or local – Create a COMPANY databaseCreate a COMPANY database

• Use Sql Query analyzerUse Sql Query analyzer– Select your new databaseSelect your new database– Start doing exercise on Page 61 -62, 1-18Start doing exercise on Page 61 -62, 1-18– Scripts are available in WebCTScripts are available in WebCT


Recommended