CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Views, Constraints, Triggers and Index James Wang.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Advertisements

MSc IT UFCE8K-15-M Data Management Prakash Chatterjee Room 2Q18
Database Administration, Integrity and Performance.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Chapter 7 Notes on Foreign Keys Local and Global Constraints Triggers.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 28 Database Systems I The Relational Data Model.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
Introduction to Structured Query Language (SQL)
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Concepts of Database Management Sixth Edition
Database Systems More SQL Database Design -- More SQL1.
A Guide to MySQL 7. 2 Objectives Understand, define, and drop views Recognize the benefits of using views Use a view to update data Grant and revoke users’
Introduction to Structured Query Language (SQL)
A Guide to SQL, Seventh Edition. Objectives Understand, create, and drop views Recognize the benefits of using views Grant and revoke user’s database.
Chapter 6: Integrity and Security Thomas Nikl 19 October, 2004 CS157B.
The Relational Model These slides are based on the slides of your text book.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Chapter 4 The Relational Model 3: Advanced Topics Concepts of Database Management Seventh Edition.
Database Technical Session By: Prof. Adarsh Patel.
Relational Database Management Systems. A set of programs to manage one or more databases Provides means for: Accessing the data Inserting, updating and.
CHAPTER:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Lecture 7 Integrity & Veracity UFCE8K-15-M: Data Management.
SQL Server 7.0 Maintaining Referential Integrity.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Constraints, Triggers and Index James Wang.
Chapter 6 Database Administration
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Chapter 4 Constraints Oracle 10g: SQL. Oracle 10g: SQL 2 Objectives Explain the purpose of constraints in a table Distinguish among PRIMARY KEY, FOREIGN.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Advanced SQL Concepts - Checking of Constraints CIS 4301 Lecture Notes Lecture /6/2006.
Physical Database Design Purpose- translate the logical description of data into the technical specifications for storing and retrieving data Goal - create.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 9 Database Triggers.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Session 1 Module 1: Introduction to Data Integrity
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
SQL Server 2012 Session: 1 Session: 12 Triggers Data Management Using Microsoft SQL Server.
Table Structures and Indexing. The concept of indexing If you were asked to search for the name “Adam Wilbert” in a phonebook, you would go directly to.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
SQL Basics Review Reviewing what we’ve learned so far…….
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1 Agenda TMA02 M876 Block 4. 2 Model of database development data requirements conceptual data model logical schema schema and database establishing requirements.
1 Constraints and Triggers in SQL. 2 Constraints are conditions that must hold on all valid relation instances SQL2 provides a variety of techniques for.
Data Integrity & Indexes / Session 1/ 1 of 37 Session 1 Module 1: Introduction to Data Integrity Module 2: Introduction to Indexes.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Fundamentals of DBMS Notes-1.
Constraints and Triggers
Instructor: Jason Carter
Lecturer: Mukhtar Mohamed Ali “Hakaale”
SQL DATA CONSTRAINTS.
A Guide to SQL, Eighth Edition
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Prof. Arfaoui. COM390 Chapter 9
SQL – Constraints & Triggers
Presentation transcript:

CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Views, Constraints, Triggers and Index James Wang

2 Database Architecture Many views, single conceptual (logical) schema and physical schema. Views describe how users see the data. Conceptual schema defines logical structure Physical schema describes the files and indexes used. Physical Schema Conceptual Schema View 1View 2View 3

3 Example: Course Database Conceptual schema: Students(sid: string, name: string, login: string, age: integer, gpa:real) Courses(cid: string, cname:string, credits:integer) Enrolled(sid:string, cid:string, grade:string) Physical schema: Relations stored as unordered files. Index on first column of Students. External Schema (View): Course_info(cid:string,enrollment:integer)

4 What are views in a database? A view in a database is created by applying a relational algebra expression to the base relations (tables). A view is a virtual relation (table) that is derived from one or many base relations. Therefore, no physical table is stored in the database for a view. The actual data are stored in base relations. Updates applied to the base relations are immediately visible to the view. Updates to values in the view may also be reflected in the base relations.

5 Why views? Views can subset the data contained in a table. Views can join multiple tables into a single virtual table to simplify the queries. Views can act as aggregated tables, where aggregated data (sum, average etc.) are calculated and presented as part of the data. Views can hide the complexity of data. Views do not incur any extra storage overhead Depending on the SQL engine used, views can provide extra security. Views control how a table or tables are exposed to outer world.

6 Read-only & updatable views If a DBMS system is able to determine the reverse mapping from the view schema to the schema of the underlying base tables, then the view is updatable. INSERT, UPDATE, and DELETE operations can be performed on updatable views. Read-only views do not support such operations because the DBMS is not able to map the changes to the underlying base tables. Materialized view is a pre-populated, non-virtual and read-only view used in data warehousing.

7 Views in MySQL Views (including updatable views) are implemented in MySQL Server 5.0, and are available in MYSQL binary releases from and up. Metadata about views can be obtained from the INFORMATION_SCHEMA.VIEWS table and by using the SHOW CREATE VIEW statement. View Operations: Creating or altering views with CREATE VIEW or ALTER VIEW Destroying views with DROP VIEW

8 Create a view CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION] Example: mysql> CREATE TABLE t (qty INT, price INT); mysql> INSERT INTO t VALUES(3, 50); mysql> CREATE VIEW v AS SELECT qty, price, qty*price AS value FROM t; mysql> SELECT * FROM v; | qty | price | value | | 3 | 50 | 150 |

9 Restrictions in MySQL view creation The SELECT statement cannot contain a subquery in the FROM clause. The SELECT statement cannot refer to system or user variables. The SELECT statement cannot refer to prepared statement parameters. Within a stored routine, the definition cannot refer to routine parameters or local variables.

10 Restrictions in MySQL view creation (cont.) Any table or view referred to in the definition must exist. However, after a view has been created, it is possible to drop a table or view that the definition refers to. In this case, use of the view results in an error. The definition cannot refer to a TEMPORARY table, and you cannot create a TEMPORARY view. The tables named in the view definition must already exist. You cannot associate a trigger with a view. ORDER BY is allowed in a view definition, but it is ignored if you select from a view using a statement that has its own ORDER BY.

11 Alter a view ALTER [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = { user | CURRENT_USER }] [SQL SECURITY { DEFINER | INVOKER }] VIEW view_name [(column_list)] AS select_statement [WITH [CASCADED | LOCAL] CHECK OPTION] Example: mysql> ALTER VIEW v AS SELECT qty, price FROM t; mysql> SELECT * FROM v; | qty | price | | 3 | 50 |

12 Drop a view DROP VIEW [IF EXISTS] view_name [, view_name]... [RESTRICT | CASCADE] Example: mysql> DROP VIEW v IF EXISTS; DROP VIEW removes one or more views. You must have the DROP privilege for each view. If any of the views named in the argument list do not exist, MySQL returns an error indicating by name which non-existing views it was unable to drop, but it also drops all of the views in the list that do exist. RESTRICT and CASCADE, if given, are parsed and ignored in MySQL.

13 Show the view create statement SHOW CREATE VIEW view_name This statement shows a CREATE VIEW statement that creates the given view. mysql> SHOW CREATE VIEW v; | View | Create View | | v | CREATE VIEW `test`.`v` AS select 1 AS `a`,2 AS `b` | Use of SHOW CREATE VIEW requires the SHOW VIEW privilege and the SELECT privilege for the view in question. You can also obtain information about view objects from INFORMATION_SCHEMA, which contains a VIEWS table.

14 Constraints SQL provides variety of techniques to express constraints to ensure the integrity and consistency of data. In DBMS, constraints and their associated “active” elements include: Key constraints. Referential constraints. Constraints on attributes or tuples. Interrelation constraints. Triggers.

15 Unique key and Primary key In a database table, keys are special attributes used to identify rows or represent relationships. Unique key and primary key: A unique key or primary key is a single column or a set of columns that uniquely identify each row in a table. No two distinct rows in a table can have the same value (or combination of values) in those columns. A database table may have arbitrarily many unique keys but at most one primary key.

16 Unique key and Primary key (cont.) Differences between unique key and primary key. A primary key is a special case of unique keys. A primary key is automatically enforced by NOT NULL constaint. The NOT NULL constraint is not implicitly enforced for a unique key. The relational model does not distinguish between primary keys and other kinds of keys. Primary keys were added to the SQL standard mainly as a convenience to the application programmer.

17 Define Primary Key ALTER TABLE ADD [ CONSTRAINT ] PRIMARY KEY ( {, }... ) CREATE TABLE table_name ( id INT, col2 VARCHAR(20),... CONSTRAINT tab_pk PRIMARY KEY(id),... ) CREATE TABLE table_name ( id INT PRIMARY KEY, col2 VARCHAR(20),... ) Note: some DBMS systems require explicitly specify NOT NULL constraint for a primary key

18 Define Unique Key ALTER TABLE ADD [ CONSTRAINT ] UNIQUE ( {, }... ) CREATE TABLE table_name ( id INT, col2 VARCHAR(20), key1 SMALLINT,... CONSTRAINT key_uniqe UNIQUE(key1),... ) CREATE TABLE table_name ( id INT PRIMARY KEY, col2 VARCHAR(20),... key1 SMALLINT UNIQUE,... )

19 Foreign Keys The foreign key identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. We call it a referential constraint between two tables. The columns in the referenced table must be a primary key or unique key. The values in one row of the referencing columns must occur in a single row in the referenced table. Most of the time, a foreign key reflects a one to many relationship.

20 Define Foreign Key ALTER TABLE ADD [ CONSTRAINT ] FOREIGN KEY ( {, }... ) REFERENCES [ ( {, }... ) ] [ ON UPDATE ] [ ON DELETE ] Examples: CREATE TABLE table_name ( id INT PRIMARY KEY, col2 VARCHAR(20), col3 INT,... CONSTRAINT col3_fk FOREIGN KEY(col3) REFERENCES other_table(key_col) ON DELETE CASCADE,... ) CREATE TABLE table_name ( id INT PRIMARY KEY, col2 VARCHAR(20), col3 INT FOREIGN KEY REFERENCES other_table(column_name),... )

21 Referential Actions CASCADE: A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. RESTRICT: A row in the referenced table cannot be updated or deleted if dependent rows still exist. In that case, no data change is even attempted. NO ACTION: The UPDATE or DELETE SQL statement is executed on the referenced table only if none of the referential relationships is violated. This is different from the RESTRICT, which does not allow UPDATE or DELETE in any case. SET NULL or SET DEFAULT: The foreign key values in the referencing row are set to NULL or DEFAULT VALUE when the referenced row is updated or deleted.

22 Artificial Key An artificial key is used by the DBMS system to identify an instance of a relation. It is not derived from any application data in the database. Using an artificial key as the primary key insulates the database relationships from changes in data values or database design (making your database more agile) and guarantees uniqueness. An artificial key is also called a surrogate key.

23 Advantages of using an artificial key Database applications won't lose their "handle" on the row because the data changes; Many database systems do not support cascading updates of keys across foreign key constraints. This results in difficulty in modifying the primary key data. Using an artificial key may avoid the problem. Artificial keys are composed of a compact data type, such as four-byte integers. This allows the database to query faster than using primary keys consisting of multiple columns or a long attribute, such as an address.

24 Constraints on Attributes and Tuples When we create a database table, we can declare two kinds of constraints: A constraint on a single attribute. A constraint on a tuple as a whole. Not-Null constraints. CHECK constraints (not supported in MySQL yet): CREATE TABLE MovieStar ( name char(30) PRIMARY KEY, gender char(1), CHECK(gender=‘F’ or name NOT LIKE ‘Ms. %’) );

25 Assertions The most powerful active elements in SQL are not associated with particular tuples or components of tuples. These elements, called “triggers” and “assertions”, are part of the database schema, on a par with tables. An assertion is a boolean-valued SQL expression that must be true at all times. A trigger is a series of actions that are associated with certain events, such as insertions into a particular table. These actions will be performed whenever these events arises.

26 Creating Assertions CREATE ASSERTION CHECK( ) It is very easy to create an assertion for an SQL programmer. However, it is very hard for the DBMS system to implement the assertion. MySQL does not support assertion yet.

27 Triggers Triggers are sometimes called event- condition-action (ECA) rules. Triggers are only activated when certain events, specified by the database programmer, occur. These events include insert, delete, update and transaction end. When triggering event happens, the trigger tests a condition to determine whether to execute the actions associated with the trigger. If the condition of the trigger is satisfied, the action associated with the trigger is performed.

28 Triggers in MySQL Support for triggers is included beginning with MySQL mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2)); Query OK, 0 rows affected (0.03 sec) mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account -> FOR EACH ROW + NEW.amount; Query OK, 0 rows affected (0.06 sec) MySQL triggers are activated by SQL statements only. They are not activated by changes in tables made by APIs that do not transmit SQL statements to the MySQL Server.

29 Create Trigger CREATE [DEFINER = { user | CURRENT_USER }] TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_stmt trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger activates before or after the statement that activated it. trigger_event indicates the kind of statement that activates the trigger.

30 Trigger Events and Statements The trigger_event can be one of the following: INSERT: The trigger is activated whenever a new row is inserted into the table; for example, through INSERT, LOAD DATA, and REPLACE statements. UPDATE: The trigger is activated whenever a row is modified; for example, through UPDATE statements. DELETE: The trigger is activated whenever a row is deleted from the table; for example, through DELETE and REPLACE statements. However, DROP TABLE and TRUNCATE statements on the table do not activate this trigger, because they do not use DELETE. trigger_stmt is the statement to execute when the trigger activates. If you want to execute multiple statements, use the BEGIN... END compound statement construct.

31 Example CREATE TABLE test1(a1 INT); CREATE TABLE test2(a2 INT); CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY); CREATE TABLE test4( a4 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, b4 INT DEFAULT 0 ); DELIMITER | CREATE TRIGGER testref BEFORE INSERT ON test1 FOR EACH ROW BEGIN INSERT INTO test2 SET a2 = NEW.a1; DELETE FROM test3 WHERE a3 = NEW.a1; UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1; END; | DELIMITER ;

32 Drop Trigger DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name This statement drops a trigger. The schema (database) name is optional. If the schema is omitted, the trigger is dropped from the default schema. Use IF EXISTS to prevent an error from occurring for a trigger that does not exist.

33 OLD and NEW keywords The OLD and NEW keywords enable you to access columns in the rows affected by a trigger. (OLD and NEW are not case sensitive.) In an INSERT trigger, only NEW.col_name can be used; there is no old row. In a DELETE trigger, only OLD.col_name can be used; there is no new row. In an UPDATE trigger, you can use OLD.col_name to refer to the columns of a row before it is updated and NEW.col_name to refer to the columns of the row after it is updated.

34 What is an index? A database index is a sequential file (or similar data structure) that improves the speed of operations in a table. Indexes can be created based on one or more columns. Indexes can make a SQL query more efficient. The disk space required to store the index is typically less than the storage of the table. It is possible to store indexes into memory from tables that would not fit into it. Not all indexes are good for all queries.

35 Clustered Index vs. Non- Clustered Index Index architectures can be classified as clustered or non- clustered. A clustered index forces the relational table physically ordered by the order of the index. Because a table can only be stored in one order physically only one clustered index may be created on a given database table. A non-clustered index does not care how records are stored physically. Clustered indexes can greatly increase access speed, but usually only where the data is accessed sequentially in the same or reverse order of the clustered index, or when a range of items are selected. Primary index vs. secondary index.

36 Dense index vs. sparse index A dense index in databases is a sequential file with pairs of keys and pointers for every record in the data file. Every key in this file is associated with a particular pointer to a record in the sorted data file. In clustered indexes with duplicate keys the dense index may point to the first record with that key. A sparse index in databases is a sequential file with index pointers pointing to the block of the sorted data file. In clustered indexes with duplicate keys the sparse index may point to the lowest search key in each block.

37 Create Index You may create indices in an existing table to improve query efficiency. It is possible to create an index on one or more columns of a table, and each index is given a name. Create a unique index: CREATE UNIQUE INDEX index_name ON table_name (column_name) Create a simple index: CREATE INDEX index_name ON table_name (column_name) Examples: CREATE INDEX PersonIndex ON Person (LastName) CREATE INDEX PersonIndex ON Person (LastName DESC) CREATE INDEX PersonIndex ON Person (LastName, FirstName)

38 References An Introduction to Database Systems, Eighth Edition, C. J. Date, Addison Wesley, 2004, ISBN: Database Management Systems, Third Edition, Raghu Ramakrishnan and Johannes Gehrke, McGraw-Hill, 2002, ISBN: