SQL NULL s, Constraints, Triggers



Similar documents
SQL Tables, Keys, Views, Indexes

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

EECS 647: Introduction to Database Systems

Lecture 6. SQL, Logical DB Design

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

Databasesystemer, forår 2005 IT Universitetet i København. Forelæsning 3: Business rules, constraints & triggers. 3. marts 2005

Data Modeling. Database Systems: The Complete Book Ch ,

The Relational Model. Why Study the Relational Model?

CS143 Notes: Views & Authorization

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

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. The Relational Model. The relational model

Intermediate SQL C H A P T E R4. Practice Exercises. 4.1 Write the following queries in SQL:

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

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

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

Outline. Data Modeling. Conceptual Design. ER Model Basics: Entities. ER Model Basics: Relationships. Ternary Relationships. Yanlei Diao UMass Amherst

Chapter 6: Integrity Constraints

CSC 443 Data Base Management Systems. Basic SQL

Introduction to Triggers using SQL

Chapter 5. SQL: Queries, Constraints, Triggers

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL

Review Entity-Relationship Diagrams and the Relational Model. Data Models. Review. Why Study the Relational Model? Steps in Database Design

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

The Relational Data Model and Relational Database Constraints

Week 4 & 5: SQL. SQL as a Query Language

SQL: Queries, Programming, Triggers

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

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

Review: Participation Constraints

Relational Database Design: FD s & BCNF

SQL: Queries, Programming, Triggers

5.1 Database Schema Schema Generation in SQL

Instant SQL Programming

14 Triggers / Embedded SQL

Programming Database lectures for mathema

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Database Systems. Lecture 1: Introduction

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

5. CHANGING STRUCTURE AND DATA

How To Create A Table In Sql (Ahem)

Database Design Overview. Conceptual Design ER Model. Entities and Entity Sets. Entity Set Representation. Keys

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Using Temporary Tables to Improve Performance for SQL Data Services

Relational Databases

Relational model. Relational model - practice. Relational Database Definitions 9/27/11. Relational model. Relational Database: Terminology

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

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

Databases What the Specification Says

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

Databases 2011 The Relational Model and SQL

UNIT 6. Structured Query Language (SQL) Text: Chapter 5

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

Section of DBMS Selection & Evaluation Questionnaire

Relational Algebra and SQL

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

More SQL: Assertions, Views, and Programming Techniques

Oracle Database 10g Express

3.GETTING STARTED WITH ORACLE8i

AVOIDANCE OF CYCLICAL REFERENCE OF FOREIGN KEYS IN DATA MODELING USING THE ENTITY-RELATIONSHIP MODEL

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

types, but key declarations and constraints Similar CREATE X commands for other schema ëdrop X name" deletes the created element of beer VARCHARè20è,

1 SQL Data Types and Schemas

IT2305 Database Systems I (Compulsory)

Database Management Systems. Chapter 1

BCA. Database Management System

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

New York University Computer Science Department Courant Institute of Mathematical Sciences

The Structured Query Language. De facto standard used to interact with relational DB management systems Two major branches

Procedural Extension to SQL using Triggers. SS Chung

Databases and BigData

Winter Winter

Programming in postgresql with PL/pgSQL. Procedural Language extension to postgresql

IT2304: Database Systems 1 (DBS 1)

ATTACHMENT 6 SQL Server 2012 Programming Standards

The Entity-Relationship Model

Database Query 1: SQL Basics

Temporal Features in SQL standard

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

Information Systems SQL. Nikolaj Popov

Graham Kemp (telephone , room 6475 EDIT) The examiner will visit the exam room at 15:00 and 17:00.

Database Programming with PL/SQL: Learning Objectives

LiTH, Tekniska högskolan vid Linköpings universitet 1(7) IDA, Institutionen för datavetenskap Juha Takkinen

DATABASE MANAGEMENT SYSTEMS. Question Bank:

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

Database Constraints and Design

Answers included WORKSHEET: INTEGRITY CONTROL IN RELATIONAL DATABASES

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

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Introduction to Microsoft Jet SQL

SQL. Ilchul Yoon Assistant Professor State University of New York, Korea. on tables. describing schema. CSE 532 Theory of Database Systems

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

Oracle 10g PL/SQL Training

Introduction to SQL and database objects

Query-by-Example (QBE)

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Transcription:

CS145 Lecture Notes #9 SQL NULL s, Constraints, Triggers Example schema: CREATE TABLE Student (SID INTEGER PRIMARY KEY, name CHAR(30), age INTEGER, GPA FLOAT); CREATE TABLE Take (SID INTEGER, CID CHAR(10), PRIMARY KEY(SID, CID)); CREATE TABLE Course (CID CHAR(10) PRIMARY KEY, title VARCHAR(100) UNIQUE); NULL s NULL is a special value: Many possible interpretations: value unknown, value inapplicable, value withheld, etc. Often used as the default value INSERT INTO Student VALUES(135, Maggie, NULL, NULL); or INSERT INTO Student(SID, name) VALUES(135, Maggie ); Operations on NULL s When we operate on a NULL and another value (including another NULL) using,, etc., the result is NULL Aggregate functions ignore NULL, except COUNT(*) AVG(GPA) SUM(GPA) COUNT(*)? Three-Valued Logic TRUE FALSE UNKNOWN AND OR NOT When we compare a NULL with another value (including another NULL) using,, etc., the result is UNKNOWN SELECT clause only lists tuples if the condition evaluates to TRUE UNKNOWN is insufficient is (GPA > 3.0 OR GPA <= 3.0) always TRUE? Jun Yang 1 CS145 Spring 1999

Constraints Integrity constraints impose restrictions on allowable data in the database, in addition to the simple structure and type restrictions imposed by the basic schema definition Declared as a part of the schema Enforced by the DBMS: if a SQL statement causes a constraint to become violated then (in most cases) the statement is aborted and a runtime error is generated Why use integrity constraints? To protect the integrity of the database (e.g., to catch data-entry errors or enforce consistency across data) To tell the DBMS about the data (e.g., the DBMS may choose to create indexes or optimize queries accordingly) Types of constraints offered by SQL: Keys: PRIMARY KEY and UNIQUE NOT NULL: restricts attributes to not allow NULL values CREATE TABLE Course(..., title VARCHAR(100) UNIQUE NOT NULL); Referential integrity (a.k.a. foreign-key) constraints Attribute-based checks Tuple-based checks General assertions Referential Integrity If an SID appears in Take then it must also appear in Student If an CID appears in Take then it must also appear in Course The reverse is not necessarily true Terminology: Take.SID references Student.SID Take.CID references Course.CID Referential integrity means referenced value always exists When we join the referencing table with the referenced table, there are no dangling tuples in the referencing table (but okay in the referenced table) Jun Yang 2 CS145 Spring 1999

Referential integrity in SQL: Referenced attribute must be PRIMARY KEY Referencing attribute is called FOREIGN KEY Two ways to declare referential integrity: With the referencing attribute Separate within the referencing table Necessary if the foreign key contains more than one attribute CREATE TABLE Take (SID INTEGER REFERENCES Student(SID), CID CHAR(10), PRIMARY KEY(SID, CID), FOREIGN KEY CID REFERENCES Course(CID)); Referential Integrity Enforcement Take.SID references Student.SID Insert or update a Take tuple so it refers to a nonexistent student Always reject Delete or update a Student tuple with a SID value referenced by some Take tuple Reject (default) Set NULL: set all references to NULL Cascade: ripple changes to all referring tuples Desired policy can be specified in SQL: ON DELETE UPDATE CASCADE SET NULL Which policy makes sense for Take.SID/Student.SID? When Should Constraints Be Checked? Usually they are checked for each modification statement But sometimes deferred constraint checking is necessary Check only at the the end of a transaction the no-chicken-and-no-egg problem CREATE TABLE Dept (name CHAR(20) PRIMARY KEY, chair CHAR(20) NOT NULL REFERENCES Prof(name)); CREATE TABLE Prof (name CHAR(20) PRIMARY KEY, dept CHAR(20) NOT NULL REFERENCES Dept(name)); Jun Yang 3 CS145 Spring 1999

Attribute-Based Check Constraint on a single attribute: Syntax: follow the attribute by CHECK( ) Condition may involve the checked attribute Other attributes and tables may be involved, but only in subqueries Semantics: condition is checked only when the associated attribute changes (i.e., an insert or update occurs) GPA s must be between 0 and 4.3 referential integrity constraint? CREATE TABLE Take (SID INTEGER CHECK(SID IN (SELECT SID FROM Student)),...); No; not checked when a Student tuple is deleted! Tuple-Based Check Constraint on a single tuple: Syntax: CHECK( ), not associated with any particular attribute Condition may involve the all attributes of the table Other tables may be involved, but only in subqueries Semantics: condition is checked only when a tuple of the associated table changes (i.e., an insert or update occurs) only Lisa can have a GPA higher than 4.0 General Assertion Constraint on entire relation or entire database: Syntax: a stand-alone statement CREATE ASSERTION CHECK( ); Semantics: condition is checked for each modification that could potentially violate it all students with GPA higher than 3.0 take CS145 Jun Yang 4 CS145 Spring 1999

Triggers A trigger is an event-condition-action rule: When event occurs, test condition; if it is satisfied, execute action More general than constraints In SQL3 standard but not in SQL2 Trigger options: Possible events include: INSERT ON DELETE ON UPDATE [OF ] ON Trigger can be: Row-level: activated FOR EACH ROW modified Statement-level: activated for each modification statement Action can be executed: AFTER the triggering event BEFORE the triggering event INSTEAD OF the triggering event Condition and action can reference: OLD tuple and NEW tuple in a row-level trigger OLD TABLE and NEW TABLE in a statement-level trigger whenever there comes a new student with GPA higher than 3.0, make him/her take CS145 CREATE TRIGGER CS145AutoRecruit AFTER INSERT ON Student REFERENCING NEW AS newstudent WHEN (newstudent.gpa > 3.0) INSERT INTO Take VALUES(newStudent.SID, CS145 ) FOR EACH ROW; rewrite the same trigger without FOR EACH ROW maintain a list of students whose GPA dropped more than 1.0 to 2.0 or less Jun Yang 5 CS145 Spring 1999