DML, Constraints, Assertions, Triggers




CS157a

Chris Pollett

Nov 8, 2023

Outline

Introduction

Database Modifications

INSERTs with a Query

Deletion

Updates

In-Class Exercise

SQL Data Definition Commands

Specifying Integrity Constraints in SQL

Data Modification and Integrity Constraints

CHECK Constraints

Naming Constraints and Altering Them

Active Databases

Assertions

Triggers

Sqlite/Mysql Trigger Example

CREATE TABLE LOG_DATA (
   LEVEL CHAR(1),  
   MESSAGE VARCHAR(30)
);

CREATE TABLE LOG_COUNTS_BY_LEVEL (
  LEVEL CHAR(1),
  NUM_MESSAGES INT
);

CREATE TRIGGER UPDATE_LOG_COUNTS
AFTER INSERT ON LOG_DATA
BEGIN
  UPDATE LOG_COUNTS_BY_LEVEL 
  SET NUM_MESSAGES = NUM_MESSAGES + 1
  WHERE LEVEL = NEW.LEVEL; 
END;

INSERT INTO LOG_COUNTS_BY_LEVEL VALUES
  ('E', 0), ('W', 0), ('I', 0);
INSERT INTO LOG_DATA VALUES
   ('W', 'Oh! No! I forgot the camembert!');
SELECT * FROM LOG_COUNTS_BY_LEVEL;