CMU SCS Carnegie Mellon Univ. Dept. of Computer Science 15-415/615 - DB Applications C. Faloutsos – A. Pavlo Lecture#7: Fun with SQL (Part 2)

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

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos & A. Pavlo Lecture#6: Rel. model - SQL part1 (R&G, chapter.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
SQL Lecture 10 Inst: Haya Sammaneh. Example Instance of Students Relation  Cardinality = 3, degree = 5, all rows distinct.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos – A. Pavlo Lecture#6: Fun with SQL (part2)
Introduction to Relational Databases Obtained from Portland State University.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science Database Applications C. Faloutsos Lecture#7 (cont’d): Rel. model - SQL part3.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
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,
ASP.NET Database Connectivity I. 2 © UW Business School, University of Washington 2004 Outline Database Concepts SQL ASP.NET Database Connectivity.
Student(sid, name, addr, age, GPA) Class(dept, cnum, sec, unit, title, instructor) Enroll(sid, dept, cnum, sec) siddeptcnumsec 301CS CS AT00000.
Database Systems More SQL Database Design -- More SQL1.
CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos & A. Pavlo Lecture#7 : Rel. model - SQL part2 (R&G, chapters.
DBMS 3. course. Reminder Data independence: logical and physical Concurrent processing – Transaction – Deadlock – Rollback – Logging ER Diagrams.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
The Relational Model. Review Why use a DBMS? OS provides RAM and disk.
Database Management COP4540, SCS, FIU SQL (Continued) Querying Multiple Tables.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Relational Model – SQL Part II (based on notes by Silberchatz,Korth,
CSC 405: Web Application And Engineering II7.1 Database Programming with SQL Aggregation and grouping with GROUP BY Aggregation and grouping with GROUP.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to Relational Databases
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
1.1 CAS CS 460/660 Relational Model. 1.2 Review E/R Model: Entities, relationships, attributes Cardinalities: 1:1, 1:n, m:1, m:n Keys: superkeys, candidate.
CS146 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
IS 230Lecture 6Slide 1 Lecture 7 Advanced SQL Introduction to Database Systems IS 230 This is the instructor’s notes and student has to read the textbook.
Carnegie Mellon Carnegie Mellon Univ. Dept. of Computer Science Database Applications C. Faloutsos Rel. model - SQL part3.
Visual Programing SQL Overview Section 1.
 CS 405G: Introduction to Database Systems Lecture 6: Relational Algebra Instructor: Chen Qian.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
The Relational Model Jianlin Feng School of Software SUN YAT-SEN UNIVERSITY.
1 CS 430 Database Theory Winter 2005 Lecture 10: Introduction to SQL.
DBMS 3. course. Reminder Data independence: logical and physical Concurrent processing – Transaction – Deadlock – Rollback – Logging ER Diagrams.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
SQL constrains and keys. SORTED RESULTS Sort the results by a specified criterion SELECT columns FROM tables WHERE predicates ORDER BY column ASC/DESC;
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
There’s a particular style to it… Rob Hatton
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Chapter 3 The Relational Model. Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. “Legacy.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
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.
Select Complex Queries Database Management Fundamentals LESSON 3.1b.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Introduction to Database Programming with Python Gary Stewart
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CO887 – Lecture 8 SQL 2.
Logical DB Design: ER to Relational
SQL – Part 2.
Lecture#6: Fun with SQL (Part 1)
Instructor: Jason Carter
Database Systems: Design, Implementation, and Management Tenth Edition
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Introduction to Relational Databases
Lecture#7: Fun with SQL (Part 2)
Faloutsos/Pavlo C. Faloutsos – A. Pavlo Lecture#13: Query Evaluation
Database systems Lecture 3 – SQL + CRUD
CMPT 354: Database System I
CS 405G: Introduction to Database Systems
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
CSC 453 Database Systems Lecture
Presentation transcript:

CMU SCS Carnegie Mellon Univ. Dept. of Computer Science /615 - DB Applications C. Faloutsos – A. Pavlo Lecture#7: Fun with SQL (Part 2)

CMU SCS CMU SCS /6152 Last Class SELECT/INSERT/UPDATE/DELETE Table Definition (DDL) NULLs String/Date/Time/Set/Bag Operations Output Redirection/Control Aggregates/Group By Faloutsos/Pavlo

CMU SCS CMU SCS /6153 Today's Jam Complex Joins Views Nested Queries Common Table Expressions Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Example Database Faloutsos/PavloCMU SCS /6154 STUDENTENROLLED COURSE cidname Pilates101Pilates Reggae20320 th Century Reggae Topology112Topology + Squirrels Massage105Massage & Holistic Therapy sidnameloginagegpa sidcidgrade 53666Pilates101C 53688Reggae203D 53688Topology112A 53666Massage105D

CMU SCS Join Query Grammar Join-Type: The type of join to compute. Qualification: Expression that determines whether a tuple from table1 can be joined with table2. Comparison of attributes or constants using operators =, ≠,, ≤, and ≥. 5 SELECT... FROM table-name1 join-type table-name2 ON qualification [WHERE...] SELECT... FROM table-name1 join-type table-name2 ON qualification [WHERE...] CMU SCS /615Faloutsos/Pavlo

CMU SCS INNER JOIN 6 SELECT name, cid, grade FROM student INNER JOIN enrolled ON student.sid = enrolled.sid SELECT name, cid, grade FROM student INNER JOIN enrolled ON student.sid = enrolled.sid namecidgrade BieberReggae203D BieberTopology112A TrumpMassage105D TrumpPilates101C sidnameloginagegpa sidcidgrade 53666Pilates101C 53688Reggae203D 53688Topology112A 53666Massage105D SELECT name, cid, grade FROM student, enrolled WHERE student.sid = enrolled.sid SELECT name, cid, grade FROM student, enrolled WHERE student.sid = enrolled.sid

CMU SCS OUTER JOIN 7 SELECT name, cid, grade FROM student LEFT OUTER JOIN enrolled ON student.sid = enrolled.sid SELECT name, cid, grade FROM student LEFT OUTER JOIN enrolled ON student.sid = enrolled.sid sidnameloginagegpa sidcidgrade 53666Pilates101C 53688Reggae203D 53688Topology112A 53666Massage105D namecidgrade BieberReggae203D BieberTopology112A TrumpMassage105D TrumpPilates101C TupacNULL

CMU SCS OUTER JOIN 8 SELECT name, cid, grade FROM enrolled RIGHT OUTER JOIN student ON student.sid = enrolled.sid SELECT name, cid, grade FROM enrolled RIGHT OUTER JOIN student ON student.sid = enrolled.sid sidnameloginagegpa sidcidgrade 53666Pilates101C 53688Reggae203D 53688Topology112A 53666Massage105D namecidgrade BieberReggae203D BieberTopology112A TrumpMassage105D TrumpPilates101C ShakurNULL

CMU SCS Join Types 9CMU SCS /615 SELECT * FROM A JOIN B ON A.id = B.id Join TypeDescription INNER JOIN Join where A and B have same value LEFT OUTER JOIN Join where A and B have same value AND where only A has a value RIGHT OUTER JOIN Join where A and B have same value AND where only B has a value FULL OUTER JOIN Join where A and B have same value AND where A or B have unique values CROSS JOIN Cartesian Product Faloutsos/Pavlo

CMU SCS Faloutsos/PavloCMU SCS /61510

CMU SCS CMU SCS /61511 Today's Jam Complex Joins Views Nested Queries Common Table Expressions Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Views Creates a “virtual” table containing the output from a SELECT query. Mechanism for hiding data from view of certain users. Can be used to simplify a complex query that is executed often. –Won’t make it faster though! Faloutsos/PavloCMU SCS /61512

CMU SCS View Example Create a view of the CS student records with just their id, name, and login. 13 CREATE VIEW CompSciStudentInfo AS SELECT sid, name, login FROM student WHERE login LIKE CREATE VIEW CompSciStudentInfo AS SELECT sid, name, login FROM student WHERE login LIKE sidnameloginagegpa sidnamelogin Original Table View

CMU SCS View Example Create a view with the average age of the students enrolled in each course. 14 CREATE VIEW CourseAge AS SELECT cid, AVG(age) AS avg_age FROM student, enrolled WHERE student.sid = enrolled.sid GROUP BY enrolled.cid; CREATE VIEW CourseAge AS SELECT cid, AVG(age) AS avg_age FROM student, enrolled WHERE student.sid = enrolled.sid GROUP BY enrolled.cid; cidavg_age Massage Pilates Topology Reggae Faloutsos/Pavlo

CMU SCS Views vs. SELECT INTO 15 CREATE VIEW AvgGPA AS SELECT AVG(gpa) AS avg_gpa FROM student WHERE login LIKE CREATE VIEW AvgGPA AS SELECT AVG(gpa) AS avg_gpa FROM student WHERE login LIKE SELECT AVG(gpa) AS avg_gpa INTO AvgGPA FROM student WHERE login LIKE SELECT AVG(gpa) AS avg_gpa INTO AvgGPA FROM student WHERE login LIKE INTO →Creates static table that does not get updated when student gets updated. VIEW →Dynamic results are only materialized when needed.

CMU SCS Materialized Views Creates a view containing the output from a SELECT query that is automatically updated when the underlying tables change. Faloutsos/PavloCMU SCS /61516 CREATE MATERIALIZED VIEW AvgGPA AS SELECT AVG(gpa) AS avg_gpa FROM student WHERE login LIKE CREATE MATERIALIZED VIEW AvgGPA AS SELECT AVG(gpa) AS avg_gpa FROM student WHERE login LIKE

CMU SCS CMU SCS /61517 Today's Jam Complex Joins Views Nested Queries Common Table Expressions Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Queries containing other queries Inner query: –Can appear in FROM or WHERE clause SELECT cname FROM customer WHERE acctno IN (SELECT acctno FROM account) SELECT cname FROM customer WHERE acctno IN (SELECT acctno FROM account) Nested Queries “outer query”“inner query” Think of this as a function that returns the result of the inner query cname Johnson Smith Jones Smith

CMU SCS Nested Queries Find the names of students in ‘Massage105’ Faloutsos/PavloCMU SCS /61519 SELECT name FROM student WHERE... SELECT name FROM student WHERE... “sid in the set of people that take Massage105”

CMU SCS Nested Queries Find the names of students in ‘Massage105’ Faloutsos/PavloCMU SCS /61520 SELECT name FROM student WHERE... SELECT sid FROM enrolled WHERE cid = ‘Massage105’ SELECT name FROM student WHERE... SELECT sid FROM enrolled WHERE cid = ‘Massage105’

CMU SCS Nested Queries Find the names of students in ‘Massage105’ Faloutsos/PavloCMU SCS /61521 SELECT name FROM student WHERE sid IN ( SELECT sid FROM enrolled WHERE cid = ‘Massage105’ ) SELECT name FROM student WHERE sid IN ( SELECT sid FROM enrolled WHERE cid = ‘Massage105’ ) name Trump

CMU SCS Nested Queries ALL →Must satisfy expression for all rows in sub-query ANY →Must satisfy expression for at least one row in sub-query. IN → Equivalent to ‘ =ANY() ’. EXISTS → At least one row is returned. Nested queries are difficult to optimize. Try to avoid them if possible. Faloutsos/PavloCMU SCS /61522

CMU SCS Nested Queries Find the names of students in ‘Massage105’ Faloutsos/PavloCMU SCS /61523 SELECT name FROM student WHERE sid = ANY( SELECT sid FROM enrolled WHERE cid = ‘Massage105’ ) SELECT name FROM student WHERE sid = ANY( SELECT sid FROM enrolled WHERE cid = ‘Massage105’ ) name Trump

CMU SCS Nested Queries Find student record with the highest id. This won’t work in SQL-92: Runs in MySQL, but you get wrong answer: Faloutsos/PavloCMU SCS /61524 SELECT MAX(sid), name FROM student; X sidname 53688Tupac

CMU SCS Nested Queries Find student record with the highest id. Faloutsos/PavloCMU SCS /61525 SELECT sid, name FROM student WHERE... SELECT sid, name FROM student WHERE... “is greater than every other sid”

CMU SCS Nested Queries Find student record with the highest id. Faloutsos/PavloCMU SCS /61526 SELECT sid, name FROM student WHERE sid SELECT sid FROM enrolled SELECT sid, name FROM student WHERE sid SELECT sid FROM enrolled is greater than every

CMU SCS Nested Queries Find student record with the highest id. Faloutsos/PavloCMU SCS /61527 SELECT sid, name FROM student WHERE sid => ALL( SELECT sid FROM enrolled ) SELECT sid, name FROM student WHERE sid => ALL( SELECT sid FROM enrolled ) sidname 53688Bieber

CMU SCS Nested Queries Find student record with the highest id. 28 SELECT sid, name FROM student WHERE sid IN ( SELECT MAX(sid) FROM enrolled ) SELECT sid, name FROM student WHERE sid IN ( SELECT MAX(sid) FROM enrolled ) SELECT sid, name FROM student WHERE sid IN ( SELECT sid FROM enrolled ORDER BY sid DESC LIMIT 1 ) SELECT sid, name FROM student WHERE sid IN ( SELECT sid FROM enrolled ORDER BY sid DESC LIMIT 1 )

CMU SCS Nested Queries Find all courses that nobody is enrolled in. Faloutsos/PavloCMU SCS /61529 SELECT * FROM course WHERE... SELECT * FROM course WHERE... “with no tuples in the ‘enrolled’ table” cidname Pilates101Pilates Reggae20320 th Century Reggae Karate101Karate Kid Aerobics Topology112Topology + Squirrels Massage105Massage & Holistic Therapy sidcidgrade 53666Pilates101C 53688Reggae203D 53688Topology112A 53666Massage105D

CMU SCS Nested Queries Find all courses that nobody is enrolled in. Faloutsos/PavloCMU SCS /61530 SELECT * FROM course WHERE NOT EXISTS( ) SELECT * FROM course WHERE NOT EXISTS( ) tuples in the ‘enrolled’ table

CMU SCS Nested Queries Find all courses that nobody is enrolled in. Faloutsos/PavloCMU SCS /61531 SELECT * FROM course WHERE NOT EXISTS( SELECT * FROM enrolled WHERE course.cid = enrolled.cid ) SELECT * FROM course WHERE NOT EXISTS( SELECT * FROM enrolled WHERE course.cid = enrolled.cid ) cidname Karate101Karate Kid Aerobics

CMU SCS CMU SCS /61532 Today's Jam Complex Joins Views Nested Queries Common Table Expressions Window Functions Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Common Table Expressions Provides a way to write auxiliary statements for use in a larger query. Alternative to nested queries and views. Faloutsos/PavloCMU SCS /61533 WITH cteName AS ( SELECT 1 ) SELECT * FROM cteName WITH cteName AS ( SELECT 1 ) SELECT * FROM cteName

CMU SCS Common Table Expressions Find student record with the highest id that is enrolled in at least one course. Faloutsos/PavloCMU SCS /61534 WITH cteSource (maxId) AS ( SELECT MAX(sid) FROM enrolled ) SELECT name FROM student, cteSource WHERE student.sid = cteSource.maxId WITH cteSource (maxId) AS ( SELECT MAX(sid) FROM enrolled ) SELECT name FROM student, cteSource WHERE student.sid = cteSource.maxId

CMU SCS CTEs – Recursion Print 1 to 10. Postgres CTE Demo! Faloutsos/PavloCMU SCS /61535 WITH RECURSIVE cteSource (counter) AS ( (SELECT 1) UNION ALL (SELECT counter + 1 FROM cteSource WHERE counter < 10) ) SELECT * FROM cteSource WITH RECURSIVE cteSource (counter) AS ( (SELECT 1) UNION ALL (SELECT counter + 1 FROM cteSource WHERE counter < 10) ) SELECT * FROM cteSource

CMU SCS CMU SCS /61536 Today's Jam Complex Joins Views Nested Queries Common Table Expressions Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Database Triggers Procedural code that is automatically executed in response to certain events on a particular table or view in a database. BEFORE / AFTER –INSERT –UPDATE –DELETE Faloutsos/PavloCMU SCS /61537

CMU SCS Trigger Example Set a timestamp field whenever a row in the enrolled table is updated. First we need to add our timestamp field. Faloutsos/PavloCMU SCS /61538 ALTER TABLE enrolled ADD COLUMN updated TIMESTAMP; ALTER TABLE enrolled ADD COLUMN updated TIMESTAMP;

CMU SCS Trigger Example Register a function that sets the ‘updated’ column with the current timestamp. Faloutsos/PavloCMU SCS /61539 CREATE OR REPLACE FUNCTION update_col() RETURNS TRIGGER AS $$ BEGIN NEW.updated = NOW(); RETURN NEW; END; $$ language 'plpgsql'; CREATE OR REPLACE FUNCTION update_col() RETURNS TRIGGER AS $$ BEGIN NEW.updated = NOW(); RETURN NEW; END; $$ language 'plpgsql'; Postgres

CMU SCS Trigger Example Invoke the update_col function when a row in the enrolled table is updated. Faloutsos/PavloCMU SCS /61540 CREATE TRIGGER update_enrolled_modtime AFTER UPDATE ON enrolled FOR EACH ROW EXECUTE PROCEDURE update_col(); CREATE TRIGGER update_enrolled_modtime AFTER UPDATE ON enrolled FOR EACH ROW EXECUTE PROCEDURE update_col(); Postgres

CMU SCS MySQL Alternative Non-standard way to do this just for setting timestamps. Faloutsos/PavloCMU SCS /61541 CREATE TABLE enrolled ( ⋮ updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ); CREATE TABLE enrolled ( ⋮ updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );

CMU SCS CMU SCS /61542 Today's Party DDLs Complex Joins Views Nested Subqueries Triggers Database Application Example Faloutsos/Pavlo

CMU SCS Outline of an DB application Establish connection with DB server Authenticate (user/password) Execute SQL statement(s) Process results Close connection CMU SCS /615Faloutsos/Pavlo

CMU SCS Database Connection Libraries DBMS-specific Libraries “Universal” Libraries –Open Database Connectivity (ODBC) –Java Database Connectivity (JDBC) Application framework libraries Faloutsos/PavloCMU SCS /61544

CMU SCS ORM Libraries Object-Relational Mapping Automatically convert classes into database-backed objects. Method calls on objects are automatically converted into SQL queries. Removes the tediousness of writing SQL queries directly in application code. Faloutsos/PavloCMU SCS /61545

CMU SCS ORM Example 46 class Location(models.Model): zipcode = CharField(max_length=5,primary_key=True) state = USStateField() city = CharField(max_length=64) class Company(models.Model): name = CharField(max_length=64,unique=True) address1 = CharField(max_length=128) location = ForeignKey(Location) website = URLField() public = BooleanField(default=True) class Location(models.Model): zipcode = CharField(max_length=5,primary_key=True) state = USStateField() city = CharField(max_length=64) class Company(models.Model): name = CharField(max_length=64,unique=True) address1 = CharField(max_length=128) location = ForeignKey(Location) website = URLField() public = BooleanField(default=True)

CMU SCS ORM Example 47 CREATE TABLE location ( zipcode VARCHAR(5) NOT NULL, state CHAR(2) NOT NULL, city VARCHAR(64) NOT NULL, PRIMARY KEY (zipcode), ); CREATE TABLE company ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(64) NOT NULL, address1 VARCHAR(128) NOT NULL, location_id VARCHAR(5) NOT NULL \ REFERENCES location (zipcode), website VARCHAR(200) NOT NULL, public TINYINT(1) NOT NULL, PRIMARY KEY (id), ); CREATE TABLE location ( zipcode VARCHAR(5) NOT NULL, state CHAR(2) NOT NULL, city VARCHAR(64) NOT NULL, PRIMARY KEY (zipcode), ); CREATE TABLE company ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(64) NOT NULL, address1 VARCHAR(128) NOT NULL, location_id VARCHAR(5) NOT NULL \ REFERENCES location (zipcode), website VARCHAR(200) NOT NULL, public TINYINT(1) NOT NULL, PRIMARY KEY (id), );

CMU SCS ORM Libraries Standalone: –Hibernate (Java) –SQLAlchemy (Python) –Doctrine (PHP) Integrated: –Django (Python) –ActiveRecord (Ruby on Rails) –CakePHP (PHP) 48CMU SCS /615Faloutsos/Pavlo

CMU SCS Next Class We begin discussing storage internals. This material will be important for helping you pick up dates at parties. Faloutsos/PavloCMU SCS /61549