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

Similar documents
Using SQL Server Management Studio

SQL Server An Overview

How To Create A Table In Sql (Ahem)

Chapter 6: Integrity Constraints

Ontrack PowerControls V8.1 for SQL ReadMe

CSC 443 Data Base Management Systems. Basic SQL

SQL Server Table Design - Best Practices

SQL NULL s, Constraints, Triggers

Introduction This document s purpose is to define Microsoft SQL server database design standards.

Comparison of Open Source RDBMS

Section of DBMS Selection & Evaluation Questionnaire

Physical Design. Meeting the needs of the users is the gold standard against which we measure our success in creating a database.

Darshan Institute of Engineering & Technology PL_SQL

A basic create statement for a simple student table would look like the following.

Ontrack PowerControls User Guide Version 8.0

The Relational Model. Why Study the Relational Model? Relational Database: Definitions. Chapter 3

MS SQL Performance (Tuning) Best Practices:

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

ATTACHMENT 6 SQL Server 2012 Programming Standards

ODBC Client Driver Help Kepware, Inc.

DbSchema Tutorial with Introduction in SQL Databases

Oracle Database 10g Express

Once the schema has been designed, it can be implemented in the RDBMS.

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Introduction to SQL and database objects

SQL. Short introduction

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Database Migration from MySQL to RDM Server

Data Modeling. Database Systems: The Complete Book Ch ,

Black Hat Briefings USA 2004 Cameron Hotchkies

Advance DBMS. Structured Query Language (SQL)

Creating Database Tables in Microsoft SQL Server

SQL Server Database Coding Standards and Guidelines

Information Systems SQL. Nikolaj Popov

IT2305 Database Systems I (Compulsory)

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

Working with DB2 UDB objects

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

Guide to Upsizing from Access to SQL Server

CIS 631 Database Management Systems Sample Final Exam

Brief background What the presentation is meant to cover: Relational, OLTP databases the type that 90% of our applications use

not at all a manual simply a quick how-to-do guide

A Brief Introduction to MySQL

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Lecture 6. SQL, Logical DB Design

Database Query 1: SQL Basics

Partitioning under the hood in MySQL 5.5

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

The Relational Model. Why Study the Relational Model?

T-SQL STANDARD ELEMENTS

BCA. Database Management System

IT2304: Database Systems 1 (DBS 1)

5.1 Database Schema Schema Generation in SQL

Title. Syntax. stata.com. odbc Load, write, or view data from ODBC sources. List ODBC sources to which Stata can connect odbc list

Schema Evolution in SQL-99 and Commercial (Object-)Relational DBMS

The Relational Model. Ramakrishnan&Gehrke, Chapter 3 CS4320 1

Choosing a Data Model for Your Database

Instant SQL Programming

Financial Data Access with SQL, Excel & VBA

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

Introduction to Database. Systems HANS- PETTER HALVORSEN,

SQL Server. 1. What is RDBMS?

Database Development and Management with SQL

4 Simple Database Features

ICAB4136B Use structured query language to create database structures and manipulate data

Evaluation of Sub Query Performance in SQL Server

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Introduction to Microsoft Jet SQL

DATABASE ADMINISTRATION SQL SERVER STANDARDS

Language Reference Guide

Programming Database lectures for mathema

Fundamentals of Database Design

MYSQL DATABASE ACCESS WITH PHP

MS ACCESS DATABASE DATA TYPES

Maintaining Stored Procedures in Database Application

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

Database Administration with MySQL

Introduction to Triggers using SQL


Jason S Wong Sr. DBA IT Applications Manager DBA Developer Programmer M.S. Rice 88, MBA U.H. 94(MIS)

Relational databases and SQL

EECS 647: Introduction to Database Systems

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

There are five fields or columns, with names and types as shown above.

SQL Server 2008 Core Skills. Gary Young 2011

SQL Server 2014 Development Essentials

Embedded SQL programming

Migrating from Sybase to SQL Server

How Strings are Stored. Searching Text. Setting. ANSI_PADDING Setting

3.GETTING STARTED WITH ORACLE8i

Performance Tuning for the Teradata Database

Oracle Database 10g: Introduction to SQL

Database Programming with PL/SQL: Learning Objectives

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

B.1 Database Design and Definition

Chapter 4: Database Design

Database Modeling. Creating E/R Diagrams with SQL Server Management Studio and MySQL Workbench. Telerik School Academy

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 Also 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