Creating Tables, Defining Constraints. Rose-Hulman Institute of Technology Curt Clifton

Similar documents
SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

SQL DATA DEFINITION LANGUAGE

SQL: Data Definition Language

From Relational Algebra to the Structured Query Language. Rose-Hulman Institute of Technology Curt Clifton

Constraints. Local and Global Constraints Triggers

CS W Introduction to Databases Spring Computer Science Department Columbia University

CS54100: Database Systems

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

Constraints and Triggers

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Databases 1. Defining Tables, Constraints

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Where Are We? Next Few Lectures. Integrity Constraints Motivation. Constraints in E/R Diagrams. Keys in E/R Diagrams

Basic SQL. Basic SQL. Basic SQL

Full file at

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

Chapter 7: Constraints and Triggers. Foreign Keys Local and Global Constraints Triggers

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Introduction to Database Systems CSE 414

From E/R Diagrams to Relations

Chapter 7 Constraints and Triggers. Spring 2011 Instructor: Hassan Khosravi

A tuple is dangling if it doesn't join with any

Structured Query Language Continued. Rose-Hulman Institute of Technology Curt Clifton

SQL: Data Definition Language. csc343, Introduction to Databases Diane Horton Fall 2017

Comp 5311 Database Management Systems. 4b. Structured Query Language 3

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Introduction to SQL Server 2005/2008 and Transact SQL

CS2300: File Structures and Introduction to Database Systems

Constraints, Views & Indexes. Running Example. Kinds of Constraints INTEGRITY CONSTRAINTS. Keys Foreign key or referential integrity constraints

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Introduction to Data Management CSE 344

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

Lab 4: Tables and Constraints

Announcements. Database Design. Database Design. Database Design Process. Entity / Relationship Diagrams. Introduction to Data Management CSE 344

SQL: Part III. Announcements. Constraints. CPS 216 Advanced Database Systems

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Introduction to SQL Server. nikos bikakis

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

The Relational Model of Data (ii)

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

Contains slides made by Naci Akkøk, Pål Halvorsen, Arthur M. Keller, Vera Goebel

Translating an ER Diagram to a Relational Schema

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

Introduction to Data Management CSE 344

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

CSE 344 MAY 14 TH ENTITIES

SQL: Part II. Introduction to Databases CompSci 316 Fall 2018

The Relational Model. Chapter 3. Comp 521 Files and Databases Fall

The Relational Model. Outline. Why Study the Relational Model? Faloutsos SCS object-relational model

1 INTRODUCTION TO EASIK 2 TABLE OF CONTENTS

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

The Relational Model. Roadmap. Relational Database: Definitions. Why Study the Relational Model? Relational database: a set of relations

user specifies what is wanted, not how to find it

2.9 Table Creation. CREATE TABLE TableName ( AttrName AttrType, AttrName AttrType,... )

Chapter 1 SQL and Data

Introduction to Data Management CSE 344

The Relational Model 2. Week 3

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Chapter Five Physical Database Design

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 2 The relational Model of data. Relational model introduction

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa

Slides by: Ms. Shree Jaswal

Functional Dependencies, Normalization. Rose-Hulman Institute of Technology Curt Clifton

An Introduction to Structured Query Language

The Relational Model. Relational Data Model Relational Query Language (DDL + DML) Integrity Constraints (IC)

The Relational Model. Chapter 3

Full file at

An Introduction to Structured Query Language

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

The Relational Model. Chapter 3. Database Management Systems, R. Ramakrishnan and J. Gehrke 1

Introduction to SQL Part 1 By Michael Hahsler based on slides for CS145 Introduction to Databases (Stanford)

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

Database Systems. Course Administration

Relational Databases BORROWED WITH MINOR ADAPTATION FROM PROF. CHRISTOS FALOUTSOS, CMU /615

BASIC SQL CHAPTER 4 (6/E) CHAPTER 8 (5/E)

Lab # 4. Data Definition Language (DDL)

Relational Model. Topics. Relational Model. Why Study the Relational Model? Linda Wu (CMPT )

Database Management System Dr. S. Srinath Department of Computer Science & Engineering Indian Institute of Technology, Madras Lecture No.

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Programming and Database Fundamentals for Data Scientists

Database Design Process Entity / Relationship Diagrams

Entity/Relationship Modelling

Introduction to Data Management. Lecture #4 (E-R Relational Translation)

SQL Server. Lecture3 Cascading referential integrity constraint

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

Data Modeling. Yanlei Diao UMass Amherst. Slides Courtesy of R. Ramakrishnan and J. Gehrke

DATA AND SCHEMA MODIFICATIONS CHAPTERS 4,5 (6/E) CHAPTER 8 (5/E)

Lecture 07. Spring 2018 Borough of Manhattan Community College

Announcements. Database Design. Database Design. Database Design Process. Entity / Relationship Diagrams. Database Systems CSE 414

Transcription:

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 Values Generating Scripts

Data Types

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

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

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

Creating and Altering Tables

Creating Tables Need: Table name Column names and types Basic Example: CREATE TABLE Soda( name CHAR(20), manf CHAR(20) );

How SQL Server Organizes Data Data Header Fixed Data NB VB Variable Data 4 bytes A Single Data Row Null Block Variable Block Slide based on MS-CreatingTables.ppt

Big @$$ Data Data row Text Pointer Root Structure Intermediate Node Intermediate Node block 1 block 2 block 1 block 2 Slide based on MS-CreatingTables.ppt

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;

Dropping Tables DROP TABLE Soda;

Constraints A requirement on data elements or the relationship between data elements that the DBMS is required to enforce

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

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

Foreign Key Constraints Consider foreign keys in Sells relation

Specifying Foreign Key Constraints CREATE TABLE Sells( rest CHAR(20) REFERENCES Rest(name), soda CHAR(20) REFERENCES Soda(name), price money ); or CREATE TABLE Sells( rest CHAR(20), soda CHAR(20), price money, FOREIGN KEY(rest) REFERENCES Rest(name), FOREIGN KEY(soda) REFERENCES Soda(name) );

Foreign Key Restriction Referenced attributes must be either: PRIMARY KEY or else UNIQUE (another element constraint)

Enforcing Foreign-Key Constraints What changes to the SodaBase data might break referential integrity?

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?

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?

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

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

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

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

Choosing a Policy Can independently choose policy For update For delete What policy should we use for Deleting soda? Why? Updating soda name? Why?

Specifying a Policy Follow foreign-key declaration with: [ON UPDATE {SET NULL CASCADE}] [ON DELETE {SET NULL CASCADE}] Omitted clause means default policy

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

Attribute-based Checks Can constrain single attribute values Syntax: CHECK( condition ) Condition can use: Name of checked attribute Subqueries Checked only upon insertion, update

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

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

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

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?

Generating Column Values Table identity columns Globally unique identifiers

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

Getting Last Identity Value Use @@identity in scripts INSERT INTO Users(name) VALUE ('Molly'); SELECT 'Last identity used: ' + CONVERT(char, @@identity) AS Answer;

GUIDs Globally unique identifiers Generated with newid() function Used with DEFAULT constraint

Example CREATE TABLE Household( HouseholdID uniqueidentifier NOT NULL DEFAULT newid(), );

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

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