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

Similar documents
SQL Constraints and Triggers. Week 11

Simple queries Set operations Aggregate operators Null values Joins Query Optimization. John Edgar 2

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

The Relational Model

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

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

Introduction to SQL Server 2005/2008 and Transact SQL

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

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

Basic SQL. Basic SQL. Basic SQL

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

Domain Constraints Referential Integrity Assertions Triggers. Authorization Authorization in SQL

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

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

5. SQL Query Syntax 1. Select Statement. 6. CPS: Database Schema

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Principles of Data Management

Exact Numeric Data Types

Full file at

DATABASE DESIGN - 1DL400

DATABASE TECHNOLOGY - 1MB025 (also 1DL029, 1DL300+1DL400)

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

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

The Relational Model of Data (ii)

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types

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

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

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

DATABASE DESIGN - 1DL400

Slides by: Ms. Shree Jaswal

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

SQL Coding Guidelines

Views, assertions, and triggers

Lab 4: Tables and Constraints

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

SQL Server 2008 Tutorial 3: Database Creation

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

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

Lab # 4. Data Definition Language (DDL)

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

SQL Constraints and Triggers

DATABASDESIGN FÖR INGENJÖRER - 1DL124

618 Index. BIT data type, 108, 109 BIT_LENGTH, 595f BIT VARYING data type, 108 BLOB data type, 108 Boolean data type, 109

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

user specifies what is wanted, not how to find it

Relational Database Systems Part 01. Karine Reis Ferreira

CS W Introduction to Databases Spring Computer Science Department Columbia University

C Examcollection.Premium.Exam.58q

Angela Henry. Data Types Do Matter

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

An Introduction to Structured Query Language

CMPT 354: Database System I. Lecture 2. Relational Model

SQL: Data Definition Language

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

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

An Introduction to Structured Query Language

Relational Model. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

CSCC43H: Introduction to Databases. Lecture 4

Database System Concepts

Physical Design of Relational Databases

System Pages (Setup Admins Only)

Exam code: Exam name: Database Fundamentals. Version 16.0

Tables From Existing Tables

CMPT 354: Database System I. Lecture 4. SQL Advanced

SQL Data Definition Language: Create and Change the Database Ray Lockwood

SQL (Structured Query Language)

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

Integrity Constraints (Reminder)

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

Database and table creation

ColdFusion Summit 2016

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

CSE 530A. ER Model to Relational Schema. Washington University Fall 2013

SQL DATA DEFINITION LANGUAGE

Basis Data Terapan. Yoannita

Introduction to Database Systems CSE 414

CSC 453 Database Technologies. Tanu Malik DePaul University

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

SQL DATA DEFINITION LANGUAGE

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition)

Keys are fields in a table which participate in below activities in RDBMS systems:

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Introduction Aggregate data model Distribution Models Consistency Map-Reduce Types of NoSQL Databases

Introduction to Relational Database Management Systems

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

ColumnStore Indexes UNIQUE and NOT DULL

CONSTRAINTS AND UPDATES CHAPTER 3 (6/E) CHAPTER 5 (5/E)

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

Lecture 07. Spring 2018 Borough of Manhattan Community College

An Introduction to Structured Query Language

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

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

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

An Introduction to Structured Query Language

Building Better. SQL Server Databases

SQL DATA DEFINITION LANGUAGE

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

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

The Relational Model. Chapter 3

Transcription:

CMPT 354

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

firstname type balance city customerid lastname accnumber rate branchname phone Customer owns Account holds Branch birthdate income transacts works transnumber Transaction sin Employee amount transdate description firstname lastname salary startdate John Edgar 3

Customer = {customerid, firstname, lastname, birthdate, income} Account = {accnumber, type, balance, rate, branchname} branchname is a foreign key referencing Branch Owns = {customerid, accnumber} customerid and accnumber are foreign keys referencing Customer and Account Transaction = {accnumber, transnumber, amount, transdate, description} accnumber is a foreign key referencing Account Branch = {branchname, city, phone} Employee = {sin, firstname, lastname, salary, startdate, branchname} branchname is a foreign key referencing Branch John Edgar 4

Every table should have a primary key When a primary key constraint is created it specifies that: The attributes of the primary key cannot be null The primary key must be unique Violating a primary key causes the violating update to be rejected John Edgar 6

A primary key constraint can be specified in a number of ways Create or alter table statement PRIMARY KEY (<attribute>) Selecting the attribute(s) and choosing the primary key menu item in the context menu By default SQL server creates a clustered index on the primary key attributes Clustered indexes support range queries John Edgar 7

Represents a relationship between two tables If table R contains a foreign key, on attributes {a}, that references table S {a} must correspond to the primary key of S Must have the same number of attributes, and The same domains Values for {a} in R must also exist in S except that If {a} is not part of the primary key of R it may be null There may be values for {a} in S that are not in R John Edgar 8

Foreign keys specify the actions to be taken if referenced records are updated or deleted For example, create a foreign key in Account that references Branch Assign accounts of a deleted branch to Granville Cascade any change in branch names branchname CHAR(20) DEFAULT Granville, FOREIGN KEY (branchname) REFERENCES Branch ON DELETE SET DEFAULT ON UPDATE CASCADE) John Edgar 9

It is possible that there can be a chain of foreign key dependencies e.g. branches, accounts, transactions A cascading deletion in one table may cause similar deletions in a table that references it If any cascading deletion or update causes a violation, the entire transaction is aborted John Edgar 10

Foreign keys can be specified in a number of different ways A separate foreign key statement Very similar to the SQL standard A References statement following a column name Using the GUI Updates and deletions in the referenced table can be set to a number of actions No action (the default) the transaction is rejected Cascade, set null or set default John Edgar 11

To use the GUI to create constraints in SQL Server Select Design on the desired table using the context menu This opens design view for the selected table The schema can be changed Constraints can be added John Edgar 12

To add a constraint Use the context menu And select the desired constraint type Primary key constraints are added with no more input For other constraints, more input is required John Edgar 13

Foreign keys Shows relationship Press to change relationship John Edgar 14

Specify action on update and deletion John Edgar 15

By default SQL foreign keys reference the primary key (of the referenced table) It is possible to reference a list of attributes The list must be specified after the name of the referenced table The specified list of attributes must be declared as a candidate key of the referenced table (UNIQUE) In SQL Server in Create or Alter Table statement or Select Indexes/Keys from the context menu John Edgar 16

A general or table constraint is a constraint over a single table Included in a table's CREATE TABLE statement Table constraints may refer to other tables Defined with the CHECK keyword followed by a description of the constraint The constraint description is a Boolean expression, evaluating to true or false If the condition evaluates to false the update is rejected John Edgar 18

Check that a customer's income is greater than zero, and that customer ID is not equal to an employee SIN CREATE TABLE Customer (customerid CHAR(11), this wouldn t work in SQL Server, income REAL, PRIMARY KEY (customerid), CONSTRAINT zeroincome CHECK (income > 0), CONSTRAINT notemp CHECK (customerid NOT IN (SELECT sin FROM Employee))) John Edgar 19

SQL Server check constraint are limited to comparisons with scalar expressions That is, expressions that contain single values Expressions that contain SQL queries are therefore not allowed Check expressions can include comparisons to results of User Defined Functions (UDFs) As long as the function returns a scalar value John Edgar 20

A UDF is an SQL Server function UDFs purpose and output vary widely They can return scalar values or tables They can be written in T-SQL or a.net language UDF are useful for a number of reasons Modular programming Faster execution Reduced network traffic John Edgar 21

CREATE FUNCTION checkempnotcustomer() RETURNS int AS BEGIN DECLARE @result int if (select COUNT(*) from Employee e, Customer c where c.customerid = e.sin) = 0 SET @result = 1 ELSE END SET @result = 0 RETURN @result The corresponding check expression is dbo.checkempnotcustomer = 1 Warning: Check constraints that call UDFs introduce overhead Note that this constraint should also be added to the Customer table John Edgar 22

New domains can be created using the CREATE DOMAIN statement Each such domain must have an underlying source type (i.e. an SQL base type) A domain must have a name, base type, a restriction, and a default optional value The restriction is defined with a CHECK statement Domains are part of the DB schema but are not attached to individual table schemata John Edgar 24

Create a domain for minors, who have ages between 0 and 18 Make the default age 10 (!) CREATE DOMAIN minorage INTEGER DEFAULT 10 CHECK (VALUE > 0 AND VALUE <= 18) John Edgar 25

A domain can be used instead of one of the base types in a CREATE TABLE statement Comparisons between two domains are made in terms of the underlying base types e.g. comparing an age with an account number domain simply compares two integers SQL also allows distinct types to be created Types are distinct so that values of different types cannot be compared John Edgar 26

The SQL CREATE TYPE clause defines new types To create distinct ID and account number types: CREATE TYPE ID AS INTEGER CREATE TYPE Accounts AS INTEGER Assignments, or comparisons between ages and account numbers would now be illegal Although it is possible to cast one type to another John Edgar 27

bigint binary( n ) bit char( n ) 8 bytes fixed length binary single bit fixed length date datetime datetime2 datetimeoffset yyyy-mm-dd date and time larger range includes time zones decimal float image int select precision, scale approximate variable length binary 4 bytes money nchar( n ) ntext numeric 8 byte monetary fixed length unicode variable length unicode equivalent to decimal nvarchar( n max) real smalldatetime smallint variable length unicode 4 byte float limited range 2 bytes smallmoney sql_variant text time 4 byte monetary allows many types variable length time (not date) tinyint uniqueidentifier varbinary( n max) varchar( n max) 1 byte used for keys variable length binary variable length John Edgar 28

SQL Server allows types to be created using syntax similar to the SQL standard CREATE TYPE SSN FROM varchar(11); John Edgar 29

Table constraints apply to only one table Assertions are constraints that are separate from CREATE TABLE statements Similar to domain constraints, they are separate statements in the DB schema Assertions are tested whenever the DB is updated Therefore they may introduce significant overhead Transact-SQL (MS SQL) does not implement assertions John Edgar 31

Check that a branch's assets are greater than the total account balances held in the branch CREATE ASSERTION assetcoverage CHECK (NOT EXISTS (SELECT * FROM Branch B This prevents changes to both WHERE assets < the Branch and Account tables (SELECT SUM (A.balance) FROM Account A WHERE A.branchName = B.branchName))) John Edgar 32

There are some constraints that cannot be modeled with table constraints or assertions What if there were participation constraints between customers and accounts? Every customer must have at least one account and every account must be held by at least one customer An assertion could be created to check this situation But would prevent new customers or accounts being added! John Edgar 33

A trigger is a procedure that is invoked by the DBMS as a response to a specified change A DB that has a set of associated triggers is sometimes referred to as an active database Triggers are available in most current commercial DB products And are part of the SQL standard Triggers carry out actions when their triggering conditions are met Generally SQL constraints only reject transactions John Edgar 35

Triggers can implement business rules e.g. creating a new loan when a customer's account is overdrawn Triggers may also be used to maintain data in related database tables e.g. Updating derived attributes when underlying data is changed, or maintaining summary data Many trigger actions can also be performed by stored procedures John Edgar 36

Event A specified modification to the DB May be an insert, deletion, or change May be limited to specific tables A trigger may fire before or after a transaction Condition Action John Edgar 37

Event Condition A Boolean expression or a query If the query answer set is non-empty it evaluates to true, otherwise false If the condition is true the trigger action occurs Action John Edgar 38

Event Condition Action A trigger's action can be very far-ranging, e.g. Execute queries Make modifications to the DB Create new tables Call host-language procedures John Edgar 39

The SQL standard gives a syntax for triggers In practice, trigger syntax varies from system to system Many features of triggers are common to the major DBMS products, and the SQL standard John Edgar 40

Write a trigger to send a message when customer data is added or changed The trigger has three components Event insert or update of the Customer table Condition always! Acton print a message By printing an SQL Server error message CREATE TRIGGER reminder1 ON Sales.Customer Example from SQL Server Books Online AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10); John Edgar 41

CREATE TRIGGER trigger_name table that the trigger applies to ON { table view } { FOR AFTER INSTEAD OF } { [ INSERT ] [, ] [ UPDATE ] [, ] [ DELETE ] } AS { sql_statement } event action, may be preceded by a condition IF... Abbreviated trigger syntax, from SQL Server Books Online John Edgar 42

Triggers can apply to any change to a table Deletion, insertion or update Or any combination of the three Triggers can be specified as AFTER The default (sometimes referred to as for triggers) Occur after the transaction has taken place INSTEAD OF The trigger replaces the triggering statement Only one instead of trigger is allowed for each insert, update or delete statement for a table John Edgar 43

After triggers only fire after referential cascade actions and constraint checks Such constraints checks must succeed Otherwise the transaction would not take place Specifically the order is Enforce constraints Enforce foreign key constraints Create inserted and deleted tables Execute the triggering statement Execute after trigger John Edgar 44

A trigger s action can be almost anything Here is a second version of the reminder trigger that sends an email CREATE TRIGGER reminder2 ON Sales.Customer AFTER INSERT, UPDATE, DELETE Example from SQL Server Books Online AS EXEC msdb.dbo.sp_send_dbmail @profile_name = 'AdventureWorks Administrator', @recipients = 'danw@adventure-works.com', @body = 'Don''t forget to print a report for the sales force.', @subject = 'Reminder'; John Edgar 45

Trigger conditions are contained in an if statement IF should be followed by a Boolean expression The Boolean expression is commonly an SQL expression e.g. IF EXISTS(subquery) If statements in triggers may have an else clause John Edgar 46

Reject the insertion of new employees whose salary is greater than their manager CREATE TRIGGER TR_Richer_Boss ON Employee AFTER INSERT AS IF EXISTS (SELECT * Could also be implemented as FROM Manager m, Employee e a check constraint with a UDF WHERE e.brnumber = m.brnumber AND e.salary > m.salary) BEGIN ROLLBACK TRANSACTION RAISERROR( Error: salary too high, 16,1) END John Edgar 47

When a table is changed temporary tables are created containing the changed data The inserted table contains records that were inserted by a transaction The deleted table contains records that were removed by a transaction If a table is updated the inserted table contains the new rows and the deleted table the old rows John Edgar 48

Add the amount of a transaction to the balance of the associated account CREATE TRIGGER TR_Account_Balance ON Transactions AFTER INSERT AS This only works if there is only BEGIN UPDATE account one transaction being inserted SET balance = balance + (SELECT amount FROM inserted) END John Edgar 49

Add the amount of a transaction to the balance of its account corrected version ALTER TRIGGER TR_Account_Balance ON Transactions AFTER INSERT AS BEGIN UPDATE account SET balance = ins.newbalance FROM (SELECT a.accnumber, a.balance + SUM(i.amount) AS newbalance FROM Account a INNER JOIN inserted i ON i.accnumber = a.accnumber GROUP BY a.accnumber, a.balance) AS ins WHERE account.accnumber = ins.accnumber END John Edgar 50

Triggers can be used for many purposes Enforcing business rows Adding functionality to the database... Triggers do carry overhead Constraints should be enforced by PKs, FKs and simple check constraints where possible Triggers should be made as efficient as possible John Edgar 51

An index is a data structure that provides efficient access to records Based on the value of one or more attributes An index on a database is conceptually similar to an index at the back of a book The index provides data to efficiently locate a record in a table Without reading the entire table John Edgar 53

Database tables are typically resident on secondary storage such as hard drives A table may be too large to fit in main memory The basic method for finding a record it to read the table from disk Referred to as scanning a table This is a very inefficient way of finding one or two records in a large table John Edgar 54

An index is a secondary data structure that maps attribute values to record IDs A record ID contains the disk address of a record Indexes typically allow records to be looked up with a handful of disk reads Typical OLTP indexes are variations of two data structures Hash tables (Binary) search trees John Edgar 55

A hash index is a hash table where the hash function maps attribute values to record IDs Hash indexes are very fast Typically requiring one or two disk reads A good hash function is uniform and random So cannot map a range of attribute values to related locations in the hash table Therefore hash indexes cannot be used for range searches John Edgar 56

A tree index directs searches in much the same way as a binary search tree In practice, databases do not use binary search trees The common implementation is a B tree (or variant) which is an n-ary tree structure Where the value of n is derived from the size of attribute values, record IDs and disk pages Tree indexes are not as fast as hash indexes But do support range searches John Edgar 57

A database table may be supported by a number of indexes One, and only one, of these indexes can be a clustered index A clustered index is one where the underlying data file is sorted on the index search key That is, the attribute used to look up index entries Clustered indexes provide much more support for range queries than un-clustered indexes Provided that the index is a tree index John Edgar 58

Indexes increase the efficiency of operations requiring look-up of attribute values There is a cost to maintaining indexes Every insertion and deletion requires modification of each index on the table Updates may require modification of indexes John Edgar 59

Database tables can support multiple indexes With single attribute search keys, or Compound (multi-attribute) search keys The DB administrator is responsible for determining which indexes to create By analyzing table work loads Modern DBMS have tools to aid in determining which indexes are appropriate for a table Index tuning SQL Server 2008 allows 1 clustered and 999 un-clustered indexes per table John Edgar 60