Creating Tables, Defining Constraints Rose-Hulman Institute of - - PowerPoint PPT Presentation

creating tables defining constraints
SMART_READER_LITE
LIVE PREVIEW

Creating Tables, Defining Constraints Rose-Hulman Institute of - - PowerPoint PPT Presentation

Creating Tables, Defining Constraints Rose-Hulman Institute of Technology Curt Clifton Outline Data Types Creating and Altering Tables Constraints Primary and Foreign Key Constraints Row and Tuple Checks Generating Column


slide-1
SLIDE 1

Creating Tables, Defining Constraints

Rose-Hulman Institute of Technology Curt Clifton

slide-2
SLIDE 2

Outline

 Data Types  Creating and Altering Tables  Constraints

 Primary and Foreign Key Constraints  Row and Tuple Checks

 Generating Column Values  Generating Scripts

slide-3
SLIDE 3

Data Types

slide-4
SLIDE 4

System-supplied Data Types

 Numeric

Integer

Exact numeric

Approximate numeric

Monetary

 Date and Time  Character and Unicode Character  Binary  Other

Slide based on MS-CreatingTables.ppt

slide-5
SLIDE 5

User-defined Data Types

 Simple, self-documenting short-hand  Creating:

 CREATE TYPE ssn

FROM varchar(11) NOT NULL

 Dropping:

 DROP TYPE ssn

 Advanced use: C# objects

slide-6
SLIDE 6

Guidelines for Data Types

 If Column Length Varies, Use a Variable

Data Type

 Use tinyint Appropriately  For Numeric Data Types, Commonly Use

decimal

 Use money for Currency  Do Not Use float or real as Primary Keys

Slide based on MS-CreatingTables.ppt

slide-7
SLIDE 7

Creating and Altering Tables

slide-8
SLIDE 8

Creating Tables

 Need:

 Table name  Column names and types

 Basic Example:

 CREATE TABLE Soda(

name CHAR(20), manf CHAR(20) );

slide-9
SLIDE 9

Header Fixed Data NB VB Variable Data

Null Block Variable Block 4 bytes Data

How SQL Server Organizes Data

Slide based on MS-CreatingTables.ppt

A Single Data Row

slide-10
SLIDE 10

Data row

Text Text Pointer Pointer

Root Structure Intermediate Node Intermediate Node block 1 block 2 block 1 block 2

Big @$$ Data

Slide based on MS-CreatingTables.ppt

slide-11
SLIDE 11

Altering Tables

 Adding columns:

 ALTER TABLE Soda

ADD msrp float;

 Changing columns:

 ALTER TABLE Soda

ALTER COLUMN msrp money;

 Dropping columns:

 ALTER TABLE Soda

DROP COLUMN manf;

slide-12
SLIDE 12

Dropping Tables

 DROP TABLE Soda;

slide-13
SLIDE 13

Constraints

 A requirement on data elements or the

relationship between data elements that the DBMS is required to enforce

slide-14
SLIDE 14

Kinds of Constraints

 Primary keys (entity integrity)  Foreign keys (referential integrity)  Attribute-based

Restrictions on the value of a single attribute

 Row-based

Restrictions on the value of one attribute in row based on value of other attributes

 Assertions

Later…

slide-15
SLIDE 15

Specifying Primary Key Constraint

 Examples:

 CREATE TABLE Soda (

name CHAR(20) PRIMARY KEY, manf CHAR(20) );

 CREATE TABLE Likes(

customer CHAR(30), soda CHAR(20), PRIMARY KEY(customer, soda) );

slide-16
SLIDE 16

Foreign Key Constraints

 Consider foreign keys in Sells relation…

slide-17
SLIDE 17

Specifying Foreign Key Constraints

CREATE TABLE Sells( rest CHAR(20) REFERENCES Rest(name), soda CHAR(20) REFERENCES Soda(name), price money );

  • r

CREATE TABLE Sells( rest CHAR(20), soda CHAR(20), price money, FOREIGN KEY(rest) REFERENCES Rest(name), FOREIGN KEY(soda) REFERENCES Soda(name) );

slide-18
SLIDE 18

Foreign Key Restriction

 Referenced attributes must be either:

 PRIMARY KEY or else  UNIQUE (another element constraint)

slide-19
SLIDE 19

Enforcing Foreign-Key Constraints

 What changes to the SodaBase data might

break referential integrity?

slide-20
SLIDE 20

Change to Table with Foreign Key

 How should we handle an insert or update to

the table with the foreign key that would break referential integrity?

slide-21
SLIDE 21

Change to Table with Primary Key

 How should we handle an update or delete to

the table with the primary key that would break referential integrity?

slide-22
SLIDE 22

3 Solutions to Primary Key Change

 Reject!

 This is the default

 Cascade

 Make same change to foreign key

 Set null

 Set foreign key to null

slide-23
SLIDE 23

Example: Default Policy

 Suppose ‘Coke’ is referenced by Sells…

 We attempt to delete ‘Coke’ from Soda table

Rejected!

 We attempt to update ‘Coke’ row, changing

‘Coke’ to ‘Coca-Cola’

Rejected!

 Forces Sells table to be changed first

slide-24
SLIDE 24

Example: Cascade Policy

 Suppose we delete Coke row from Soda

 Then automatically delete all rows for Coke from

Sells

 Suppose we update the Coke row, changing

‘Coke’ to ‘Coca-Cola’

 Then automatically change all rows in Sells

referencing Coke to reference Coca-Cola instead

slide-25
SLIDE 25

Example: “Set Null” Policy

 Suppose we delete Coke row from Soda

 Then automatically change all rows referencing

Coke in Sells to have nulls

 Suppose we update the Coke row, changing

‘Coke’ to ‘Coca-Cola’

 Then automatically change all rows in Sells

referencing Coke to have nulls

slide-26
SLIDE 26

Choosing a Policy

 Can independently choose policy…

 For update  For delete

 What policy should we use for…

 Deleting soda? Why?  Updating soda name? Why?

slide-27
SLIDE 27

Specifying a Policy

 Follow foreign-key declaration with:

 [ON UPDATE {SET NULL | CASCADE}]

[ON DELETE {SET NULL | CASCADE}]

 Omitted clause means default policy

slide-28
SLIDE 28

Example

 CREATE TABLE Sells(

rest CHAR(20) REFERENCES Rest(name) ON DELETE CASCADE ON UPDATE CASCADE, soda CHAR(20) REFERENCES Soda(name) ON DELETE SET NULL ON UPDATE CASCADE, price money );

slide-29
SLIDE 29

Attribute-based Checks

 Can constrain single attribute values  Syntax:

 CHECK( condition )

 Condition can use:

 Name of checked attribute  Subqueries

 Checked only upon insertion, update

slide-30
SLIDE 30

Example

 CREATE TABLE Customer(

name CHAR(20) PRIMARY KEY, addr CHAR(50), phone CHAR(8) CHECK (phone LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]') );

slide-31
SLIDE 31

Same or Different?

CREATE TABLE Sells ( rest CHAR(20), soda CHAR(20) REFERENCES Soda(name), price money );

CREATE TABLE Sells ( rest CHAR(20), soda CHAR(20) CHECK ( soda IS NULL OR soda IN (SELECT name FROM Soda)), price money );

slide-32
SLIDE 32

Row-Based Checks

 Can also put CHECK at end of table

declaration

 Can reference any attribute in table  CHECK for each tuple…

 Inserted or  Updated

slide-33
SLIDE 33

Example

 Only Joe’s can sell Coke for more than $2  CREATE TABLE Sells (

rest CHAR(20), soda CHAR(20), price money, CHECK( condition ) );

 What should condition be?

slide-34
SLIDE 34

Generating Column Values

 Table identity columns  Globally unique identifiers

slide-35
SLIDE 35

Table Identity Column

 Constraint on single column of table  Column must be integer or decimal data type  Syntax:

 IDENTITY [ (seed, increment) ]

 Example:

 CREATE TABLE Users(

name CHAR(20), id int IDENTITY (0, 5) );

slide-36
SLIDE 36

Getting Last Identity Value

 Use @@identity in scripts  INSERT INTO Users(name)

VALUE ('Molly'); SELECT 'Last identity used: ' + CONVERT(char, @@identity) AS Answer;

slide-37
SLIDE 37

GUIDs

 Globally unique

identifiers

 Generated with newid()

function

 Used with DEFAULT

constraint

slide-38
SLIDE 38

Example

 CREATE TABLE Household(

HouseholdID uniqueidentifier NOT NULL DEFAULT newid(), … );

slide-39
SLIDE 39

Generating Scripts

 Can generate scripts from objects

 Right click database  Tasks → Generate Scripts…

 Useful for:

 Storing schemas in version control system  Creating test environment  Training

slide-40
SLIDE 40

Recommended Practices

 Specify Appropriate Data Types and Data

Type Sizes (duh!)

 Always Specify Column Characteristics in

CREATE TABLE

 Generate Scripts to Recreate Database Objects

Slide based on MS-CreatingTables.ppt