SQL – Part 2.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
Review Session ER and Relational –ER  Relational –Constraints, Weak Entities, Aggregation, ISA Relational Algebra  Relational Calculus –Selections/Projections/Joins/Division.
Database Management System Module 3:. Complex Constraints In this we specify complex integrity constraints included in SQL. It relates to integrity constraints.
IC and Triggers in SQL. Find age of the youngest sailor with age
1 Lecture 11: Basic SQL, Integrity constraints
SQL: Queries, Constraints, Triggers
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Database Management Systems 1 Raghu Ramakrishnan SQL: Queries, Programming, Triggers Chpt 5.
SQL Constraints and Triggers
SQL: The Query Language Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY courtesy of Joe Hellerstein and etc for some slides.
CS 405G: Introduction to Database Systems
Cs3431 Constraints Sections 6.1 – 6.5. cs3431 Example CREATE TABLE Student ( sNum int, sName varchar (20), prof int, CONSTRAINT pk PRIMARY KEY (snum),
SQL 2 – The Sequel R&G, Chapter 5 Lecture 10. Administrivia Homework 2 assignment now available –Due a week from Sunday Midterm exam will be evening of.
SPRING 2004CENG 3521 SQL: Constraints, Triggers, Embedded SQL Chapters: 5, 6.
Rutgers University SQL: Queries, Constraints, Triggers 198:541 Rutgers University.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
1 SQL: Structured Query Language (‘Sequel’) Chapter 5 (cont.)
Database Systems More SQL Database Design -- More SQL1.
CMPT 354, Simon Fraser University, Fall 2008, Martin Ester 157 Database Systems I SQL Constraints and Triggers.
CSC343 – Introduction to Databases - A. Vaisman1 SQL: Queries, Programming, Triggers.
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.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
SQL Part I: Standard Queries. COMP-421: Database Systems - SQL Queries I 2 Example Instances sid sname rating age 22 debby debby lilly.
1 SQL: Constraints and Triggers Chapter 5,
Unit 5/COMP3300/ SQL: Queries, Programming, Triggers Chapter 5.
SQL: Queries, Programming, Triggers. Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for.
ICS 321 Fall 2011 Constraints, Triggers, Views & Indexes Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Constraints and Triggers Chapter 5,
Constraints, Triggers and Views COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
SQL Integrity Constraints. 421B: Database Systems - Integrity Constraints 2 Integrity Constraints (Review) q An IC describes conditions that every legal.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Example Instances R1 S1 S2  We will use these instances of the Sailors and Reserves relations in our.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
1 SQL: Queries, Constraints, Triggers Chapter 5. 2 Overview: Features of SQL  Data definition language: used to create, destroy, and modify tables and.
Hassan Tariq MULTIPLE TABLES: SQL provides a convenient operation to retrieve information from multiple tables.SQL provides a convenient operation to.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
1 SQL: Structured Query Language Chapter 5 (cont.)  Constraints  Triggers.
Assertions and Triggers in SQL
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 4: Intermediate.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
1 CS122A: Introduction to Data Management Lecture #4 (E-R  Relational Translation) Instructor: Chen Li.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL: Queries, Constraints, Triggers
SQL The Query Language R & G - Chapter 5
Database Systems October 14, 2009 Lecture #5.
Chapter 4: Intermediate SQL Joins
Aggregation.
SQL: Structured Query Language (‘Sequel’)
SQL: Queries, Constraints, Triggers
SQL: Queries, Programming, Triggers
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
Chapter 4: Intermediate SQL
The Relational Model Relational Data Model
CS 405G: Introduction to Database Systems
SQL: Queries, Constraints, Triggers
Advanced SQL: Views & Triggers
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CS4222 Principles of Database System
SQL: Structured Query Language
Chapter 4: Intermediate SQL
SQL: Queries, Programming, Triggers
SQL: Structured Query Language
SQL: Queries, Constraints, Triggers
SQL: Queries, Programming, Triggers
Presentation transcript:

SQL – Part 2

Joined Relations – Birleştirilmiş Çizelgeler Join operations take two relations and return as a result another relation. These additional operations are typically used as subquery expressions in the from clause Join condition – defines which tuples in the two relations match, and what attributes are present in the result of the join. Join type – defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated. 2

Joins Explicit join semantics needed unless it is an INNER join SELECT (column_list) FROM table_name [INNER | {LEFT |RIGHT | FULL } OUTER] JOIN table_name ON qualification_list WHERE … Explicit join semantics needed unless it is an INNER join (INNER is default)

Inner Join – İç Birleştirme Only the rows that match the search conditions are returned. SELECT s.sid, s.name, r.bid FROM Sailors s INNER JOIN Reserves r ON s.sid = r.sid Returns only those sailors who have reserved boats SQL-92 also allows: FROM Sailors s NATURAL JOIN Reserves r “NATURAL” means equi-join for each pair of attributes with the same name

SELECT s.sid, s.name, r.bid FROM Sailors s INNER JOIN Reserves r ON s.sid = r.sid

Outer Join – Dış Birleştirme An extension of the join operation that avoids loss of information. Computes the join and then adds tuples form one relation that does not match tuples in the other relation to the result of the join. Uses null values. 6

Left Outer Join (Sol Dış Birleştirme) Left Outer Join returns all matched rows, plus all unmatched rows from the table on the left of the join clause (use nulls in fields of non-matching tuples) SELECT s.sid, s.name, r.bid FROM Sailors s LEFT OUTER JOIN Reserves r ON s.sid = r.sid Returns all sailors & information on whether they have reserved boats

SELECT s.sid, s.name, r.bid FROM Sailors s LEFT OUTER JOIN Reserves r ON s.sid = r.sid

Right Outer Join (Sağ Dış Birleştirme) Right Outer Join returns all matched rows, plus all unmatched rows from the table on the right of the join clause SELECT r.sid, b.bid, b.name FROM Reserves r RIGHT OUTER JOIN Boats b ON r.bid = b.bid Returns all boats & information on which ones are reserved.

SELECT r.sid, b.bid, b.name FROM Reserves r RIGHT OUTER JOIN Boats b ON r.bid = b.bid

Full Outer Join Full Outer Join returns all (matched or unmatched) rows from the tables on both sides of the join clause SELECT r.sid, b.bid, b.name FROM Reserves r FULL OUTER JOIN Boats b ON r.bid = b.bid Returns all boats & all information on reservations

SELECT r.sid, b.bid, b.name FROM Reserves r FULL OUTER JOIN Boats b ON r.bid = b.bid Note: in this case it is the same as the ROJ because bid is a foreign key in reserves, so all reservations must have a corresponding tuple in boats.

Left Outer Join course prereq course natural left outer join prereq 13

Right Outer Join course natural right outer join prereq course prereq 14

Full Outer Join course prereq course natural full outer join prereq 15

Joined Relations in SQL – Examples course inner join prereq on course.course_id = prereq.course_id What is the difference between the above and a natural join? 16

Joined Relations in SQL – Examples course prereq course left outer join prereq on course.course_id = prereq.course_id 17

Views (Görünümler) In some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.) Consider a person who needs to know an instructors name and department, but not the salary. This person should see a relation described, in SQL, by select ID, name, dept_name from instructor A view provides a mechanism to hide certain data from the view of certain users. Any relation that is not of the conceptual model but is made visible to a user as a “virtual relation” is called a view. 18

View Definition A view is defined using the create view statement which has the form create view v as < query expression > where <query expression> is any legal SQL expression. The view name is represented by v. Once a view is defined, the view name can be used to refer to the virtual relation that the view generates. View definition is not the same as creating a new relation by evaluating the query expression Rather, a view definition causes the saving of an expression; the expression is substituted into queries using the view. 19

Example Views A view of instructors without their salary create view faculty as select ID, name, dept_name from instructor Find all instructors in the Biology department select name from faculty where dept_name = ‘Biology’ Create a view of department salary totals create view departments_total_salary(dept_name, total_salary) as select dept_name, sum (salary) from instructor group by dept_name; 20

Integrity Constraints (Review) (Bütünlük Kısıtları) An IC describes conditions that every legal instance of a relation must satisfy. Inserts/deletes/updates that violate IC’s are disallowed. Can be used to ensure application semantics (e.g., sid is a key), or prevent inconsistencies (e.g., sname has to be a string, age must be < 200) Types of IC’s: Domain constraints, primary key constraints, foreign key constraints, general constraints. Domain constraints: Field values must be of right type. Always enforced. 5

Integrity Constraints on a Single Relation not null primary key unique check (P), where P is a predicate 22

General Constraints Useful when more general ICs than keys are involved. Can use queries to express constraint. CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ) 8

General Constraints Constraints can be named. ( sname CHAR(10), CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid=bid))) Constraints can be named. ‘Interlake’ cannot be reserved constraint This works because bid is key for Boats and so B.bname returns unique name. Still the <> is hacky. 8

Domain Constraints A user can form a new domain using the CREATE DOMAIN statement, which makes use of CHECK constraints CREATE DOMAIN ratingval INTEGER DEFAULT 0 CHECK ( VALUE >= 1 AND VALUE <= 10 )

Constraints Over Multiple Relations CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT (B.bid) FROM Boats B) < 100) Number of boats plus number of sailors is < 100 Awkward and wrong! If the Sailors table is empty, the constraint is defined to hold always, so if Sailors is empty, the number of Boats tuples can be anything! 9

Constraints Over Multiple Relations Number of boats plus number of sailors is < 100 CREATE ASSERTION smallClub CHECK ( (SELECT COUNT (S.sid) FROM Sailors S) + (SELECT COUNT(B.bid) FROM Boats B) < 100) Table constraints are required to hold only if the associated table is nonempty. We can create ASSERTIONs. Assertions are not associated with any table. 9

Triggers Trigger: procedure that starts automatically if specified changes occur to the DBMS Three parts: Event: A change to the database that activates the trigger. Condition: tests whether the triggers should run Action: A procedure that is executed when the trigger is activated and its condition is true Triggers monitor the database

Triggers: Example: Oracle 7 Syntax

Triggers: Example (SQL:1999) Set-oriented trigger. Insets info for all new young sailors (less than 18).

Exercise 5.10 Consider the folllowing relational schema. An employee can work in more than one department; the pct_time field of the Works relation shows the percentage of time that a given employee works in a given department. Emp(eid: integer, ename: string, age: integer, salary: real) Works(eid: integer, did: integer, pct_time: integer) Dept(did: integer, budget: real, managerid: integer) Write SQL integrity constraints (domain, key, foreign key or CHECK constraints or assertions) to ensure each of the following, independently. Employees must make a minimum salary of $1000. A manager must always have a higher salary than any employee that he or she manages.

Read the examples from the textbook Chapter 5 End of SQL discussion Read the examples from the textbook Chapter 5