376a. Database Design Dept. of Computer Science Vassar College

Slides:



Advertisements
Similar presentations
SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
Advertisements

COMPANY schema EMPLOYEE
OUTLINE OF THE LECTURE PART I GOAL: Understand the Data Definition Statements in Fig 4.1 Step1: Columns of the Tables and Data types. Step2: Single column.
Basic Queries. 2 Retrieval Queries in SQL SQL has one basic statement for retrieving information from a database; the SELECT statement This is not the.
SQL Query Slides Sharif University Of Technology Database Systems CE 384 Prepared By: Babak Bagheri Hariri
Your Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Instructor: Mr. Ahmed Al Astal Chapter 8 (Cont.) SQL-99: Schema Definition,
Displaying Data from Multiple Tables. EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS
Database technology Lecture 2: Relational databases and SQL
Company Database. CREATE TABLE DEPARMENT ( DNAME VARCHAR(10) NOT NULL, DNUMBER INTEGER NOT NULL, MGRSSN CHAR(9), MGRSTARTDATE CHAR(9), PRIMARY KEY (DNUMBER),
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1.
1 CSE 480: Database Systems Lecture 10: SQL - DML Reference: Read Chapter 4 of the textbook.
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
Database Systems Chapter 8 ITM 354. Data Definition, Constraints, and Schema Changes Used in SQL to Create, Drop, and Alter the descriptions of the tables.
More SQL: Complex Queries, Triggers, Views, and Schema Modification 1.
관계 연산자 & SQL. Selection SELECT * FROM r WHERE A=B AND D>5.
SQL The relational DB Standard CS-450 Dr. Ali Obaidi.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide 8- 1 CREATE/DROP/ALTER TABLE Data types : char, varchar, decimal, date CREATE TABLE DEPARTMENT.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
1 CSE 480: Database Systems Lecture 11: SQL. 2 SQL Query SELECT FROM WHERE –In MySQL, FROM and WHERE clauses are optional –Example:
SQL: Schema Definition, Constraints, & Queries and Views.
Relational Algebra - Chapter (7th ed )
Onsdag The concepts in a relation data model SQL DDL DML.
 Employee (fname, minit, lname, ssn, bdate, address, sex, salary, superssn, dno)  Department (dname, dnumber, mgrssn, mgrstartdate) 
Database Management Systems. NESTING OF QUERIES  Some queries require that existing values in the database be retrieved and then used in a comparison.
Announcements Written Homework 1 due Friday –If you have fourth edition make sure you do the right problems Program 3 out today, due next Friday Nov 10.
Chapter 3 MORE SQL Copyright © 2004 Pearson Education, Inc.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
SQL Chapter 8. SQL or SEQUEL - (Structured English Query Language) Based on relational algebra Developed in 1970's released in early 1980's Standardized.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Structured Query Language
Structured Query Language (2) The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems,
DatabaseIM ISU1 Fundamentals of Database Systems Chapter 6 The Relational Algebra.
Announcements Written Homework 1 due Nov 2 –See course web page –Exercises 5.12, 5.15, 6.17, 6.20, 6.22 (a,c,f only). Today –continue with SQL (chapter.
Riyadh Philanthropic Society For Science Prince Sultan College For Woman Dept. of Computer & Information Sciences CS 340 Introduction to Database Systems.
COMP163 Database Management Systems September 18, 2008 Lecture 8 – Sections SQL Queries.
ISC321 Database Systems I Chapter 5: SQL: Advanced Queries, Assertions, Triggers, and Views Fall 2015 Dr. Abdullah Almutairi.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL تنبيه : شرائح العرض (Slides) هي وسيلة لتوضيح الدرس واداة.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 Lecture # 10 July 10,2012 More SQL: Complex Queries, Triggers,
CS580 Advanced Database Topics Chapter 8 SQL Irena Pevac.
1 Chapter (8) SQL The Relational Database Standard Objectives Presenting the main features of SQL SQL is the Structured Query Language SQL commands SQL.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
The SQL Database Grammar
CS580 Advanced Database Topics
SQL: SchemaDefinition, Constraints, and Queries and Views
Chapter 4 Basic SQL.
6/22/2018.
CS580 Advanced Database Topics
Retrieval Queries in SQL(DML)
376a. Database Design Dept. of Computer Science Vassar College
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
More SQL: Complex Queries, Triggers, Views, and Schema Modification
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Session - 6 Sequence - 2 SQL: The Structured Query Language:
376a. Database Design Dept. of Computer Science Vassar College
Chapter 4 & 5 Basic SQL More SQL
Chapter 4 Basic SQL. Chapter 4 Basic SQL Chapter 4 Outline Overview of SQL SQL Data Definition (DDL) for Specifying a Relational Database Schema CREATE.
SQL (more).
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Structured Query Language (3)
SQL-99: Schema Definition, Constraints, and Queries and Views
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
SQL: Set Operations & Nested Queries. Presented by: Dr. Samir Tartir
Presentation transcript:

376a. Database Design Dept. of Computer Science Vassar College http://www.cs.vassar.edu/~cs376 Class 7: Domain Relational Calculus and beginning SQL Prof. Billibon Yoshimi 9/19/2018

Find employees with no dependents using Domain Relation Calculus. EMPLOYEE(FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO) DEPENDENT(ESSN, DEPENDENT_NAME,SEX,BDATE,RELATIONSHIP) EMPLOYEE(q-z) and NOT (exists l) (DEPENDENT (lmnop) and t=l) Prof. Billibon Yoshimi 9/19/2018

List names of all managers with at least one dependent. EMPLOYEE(FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) DEPENDENT(ESSN, DEPENDENT_NAME,SEX,BDATE,RELATIONSHIP) ] t ] j ] l EMPLOYEE(q-z) and DEPARTMENTand dep.mgrssn=employee.ssn and employee.ssn=dependent.essn Prof. Billibon Yoshimi 9/19/2018

SELECT statement No relation to sigma SQL tables are not sets (they’re multi-sets). Use DISTINCT to regain set-like quality. Basically: SELECT <attribute list> FROM <list of tables> WHERE <condition list> Prof. Billibon Yoshimi 9/19/2018

Get the birthdate and address of employees with the name “John B Get the birthdate and address of employees with the name “John B. Smith” R.A. SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME=“JOHN” and MINIT=“B” and LNAME=“SMITH” Prof. Billibon Yoshimi 9/19/2018

Can use SELECT to do join operation too FNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE DEPARTMENT=“RESEARCH” AND DNUMBER=DNO Print the firstname and address of all employees in the research department. Prof. Billibon Yoshimi 9/19/2018

Resolving ambiguous names Relationships may have same named attributes. Use relation.attribute to disambiguate. When using multiple instances of a relation in a SELECT, use aliases.. SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE as E, EMPLOYEE as S WHERE E.SUPERSSN = S.SSN Prof. Billibon Yoshimi 9/19/2018

Can also create attribute aliases, EMPLOYEE AS E(FN,MI,LN,SSN,BD,ADDR,S,SAL,SSSN,DNO) Prof. Billibon Yoshimi 9/19/2018

SELECT - FROM statements Unspecified WHERE is *. If multiple relations are specified in FROM then the tuples are formed from the cross product of all FROM relations. Prof. Billibon Yoshimi 9/19/2018

Other modifiers to SELECT SELECT * FROM - WHERE * - Selects all attributes SELECT ALL x FROM WHERE - get all values, including duplicates SELECT DISTINCT * FROM WHERE - removes duplicates *EXPENSIVE* Prof. Billibon Yoshimi 9/19/2018

UNION, EXCEPT and INTERSECT operations (SELECT *) UNION (SELECT *) Sub sets should be union compatible, same attribute tuples, same ordering. UNION gives the union of all tuples (duplicates eliminated). EXCEPT gives the set difference. INTERSECT gives the intersection of the tuples. Prof. Billibon Yoshimi 9/19/2018

Comparing strings In WHERE statements use LIKE WHERE NAME LIKE “%ITH%” % - replaces arbitrary numbers of characters _ - replaces a single character “_____5_____” In MySQL, use REGEX too. ^ - match beginning of line $- match end of line [bB] - match any one char in bracket * - zero or one instances of preceding thing Match anywhere in the input, unlike LIKE Prof. Billibon Yoshimi 9/19/2018

Operations on return values +,-,*,/, BETWEEN (SALARY BETWEEN X AND Y) || is string append Like this SELECT name||address, salary*1.3 You can also call functions using the select statement to do evaluations NOW( ), SIN(3.1415), 3*5 Prof. Billibon Yoshimi 9/19/2018

SELECT FROM WHERE ORDER BY ORDER BY attribute ASC|DESC, attribute ASC|DESC By default it is in ascending order. Order on first attribute, then second,then third. Prof. Billibon Yoshimi 9/19/2018

Nested queries SELECT FROM WHERE X IN (SELECT as argument); X is an attribute name to compare or is a tuple (attribute, attribute, etc.) In the case of ambiguity, attribute is associated with innermost nested SELECT. Prof. Billibon Yoshimi 9/19/2018

Example SELECT DISTINCT PNUMBER FROM PROJECT WHERE PNUMBER IN (SELECT PNUMBER FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME=‘Smith’ ) OR FROM WORKS_ON_EMPLOYEE WHERE ESSN=SSN AND LNAME=‘Smith’); Prof. Billibon Yoshimi 9/19/2018

Other operators used like IN = ANY or = SOME > ANY < ANY, <= ANY, >= ANY, <> ANY (similar for SOME but only needs to find one case) Why isn’t there a NONE? Prof. Billibon Yoshimi 9/19/2018

When nested query is correlated to outer query. For each tuple satisfying the outside query, Apply the nested query. Select all employees with the same first name as one of their progeny. E.g. SELECT * FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE E.FNAME=DEPEND_NAME) Prof. Billibon Yoshimi 9/19/2018

All nested queries can ALWAYS be expressed as single block queries SELECT * FROM EMPLOYEE AS E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT WHERE E.FNAME=DEPEND_NAME); We explicitly indicate the JOIN. FROM EMPLOYEE AS E, DEPENDENT AS D WHERE E.SSN=D.ESSN AND E.FNAME=D.DEPEND_NAME; Prof. Billibon Yoshimi 9/19/2018

EXISTS Also used in WHERE clause SELECT * FROM EMPLOYEE AS E WHERE EXISTS (SELECT * FROM DEPENDENT WHERE E.SSN=ESSN AND E.FNAME=DEPEND_NAME); WHERE NOT EXISTS (SELECT * FROM DEPENDENT WHERE E.SSN=ESSN); Prof. Billibon Yoshimi 9/19/2018

General form of EXISTS EXISTS (Q) where Q is the query. Returns TRUE if the query returns at least one tuple. Returns FALSE if query returns no tuples. Can use multiple EXISTS in a WHERE statement e.g. WHERE EXISTS (employee who is a manager) AND EXISTS (EMPLOYEE HAS DEPENDENTS) What is same query without EXISTS (use one nested select) What is same query without any nesting? Select FNAME, LNAME FROM EMPLOYEE AS E, DEPARTMENT AS D, DEPENDENT AS CHILD WHERE E.SSN=D.MGRSSN AND E.SSN=CHILD.ESSN Prof. Billibon Yoshimi 9/19/2018

Explicit sets Another way to write the argument for IN or similar functions Normally, WHERE X IN (SELECT …) Can also be written WHERE NAME IN (‘Bill’, ‘Bob’, ‘Jack’) Prof. Billibon Yoshimi 9/19/2018

Comparison to NULL WHERE X IS NULL Compares the value of attribute X with NULL, returns TRUE when X is NULL. e.g. employees with no manager SELECT * FROM EMPLOYEE WHERE SUPERSSN IS NULL Prof. Billibon Yoshimi 9/19/2018

Use AS to rename any attribute or relation Remember SELECT FROM EMPLOYEE AS E, PROJECT AS P; Can rename columns returned in relation too. SELECT FNAME AS FIRST_NAME, LNAME AS LAST_NAME Will output a relation with new attribute names. Prof. Billibon Yoshimi 9/19/2018

Explicit JOINs In the select statement there is an implict join whenever there is more than 1 relation in the FROM section. Control the join explicitly by writing it in. SELECT * FROM EMPLOYEE JOIN DEPARTMENT AS D ON DNO=DNUMBER WHERE D.DNAME=‘RESEARCH’; By default any join is an INNER JOIN (added only if matching tuple is found in other relation.) Prof. Billibon Yoshimi 9/19/2018

JOIN types Remember different types again. NATURAL JOIN - removes duplicate attribute (by name). Joins on all same named attributes. EMPLOYEE(FNAME, MINIT, LNAME, SSN, BDATE, ADDRESS, SEX, SALARY, SUPERSSN, DNO) DEPARTMENT(DNAME, DNUMBER, MGRSSN, MGRSTARTDATE) SELECT * FROM EMPLOYEE NATURAL JOIN (DEPARTMENT AS DEPT(DNAME,DNO,MSSN,MSDATE)) WHERE … Prof. Billibon Yoshimi 9/19/2018

OUTER JOIN Show employee name and supervisor name for all employees. (some employees have null for superssn field!) SELECT E.FNAME| ‘ ‘ | E.LNAME, S.FNAME| ‘ ‘ | S.LNAME FROM EMPLOYEE AS E LEFT OUTER JOIN (EMPLOYEE AS S ON E.SUPERSSN = S.SSN); Why no WHERE clause? Prof. Billibon Yoshimi 9/19/2018

Rest of joins. INNER JOIN (or just JOIN), LEFT OUTER JOIN, FULL OUTER JOIN, RIGHT OUTER JOIN Note: in last 3 cases the OUTER can be left out. Prof. Billibon Yoshimi 9/19/2018

Aggregate operations A few of these (many more) COUNT() - counts the number of tuples or values in the query SUM() - applied to set of multiset of attributes. MAX() - may be applied to any totally orderable domain. MIN() AVG() e.g. SELECT SUM(SALARY), MAX (SALARY), MIN(SALARY), AVG(SALARY FROM EMPLOYEE; Prof. Billibon Yoshimi 9/19/2018

COUNT() SELECT COUNT (*) FROM EMPLOYEE; SELECT COUNT (SALARY) SELECT COUNT (DISTINCT SALARY) First 2 results are different from 3rd. Prof. Billibon Yoshimi 9/19/2018

Use COUNT in nested SELECT Select all employees with 2 or more dependents SELECT * FROM EMPLOYEE WHERE ( SELECT COUNT (*) FROM DEPENDENT WHERE SSN=ESSN) >= 2; For each employee, if the number of dependents for that employee is > 2, include the tuple. Prof. Billibon Yoshimi 9/19/2018

Use GROUP BY to group statistics SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO; GROUP BY specifies the subgroups the statistics are applied to. What if GROUP BY is given a primary key? Prof. Billibon Yoshimi 9/19/2018

What does the following do? SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME; In this case, the JOIN happens first, then the GROUP BY statistics are applied. Remember there is one WORKS_ON tuple for every project every person works on. Prof. Billibon Yoshimi 9/19/2018

Use HAVING to filter GROUP BY results SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER, PNAME HAVING COUNT(*)>2; Same as before except, after the group statistics are calculated, the troups are passed through the HAVING clause. Prof. Billibon Yoshimi 9/19/2018

Be careful with the order though What does this do? SELECT DNAME, COUNT(*) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO AND SALARY>4000 GROUP BY DNAME HAVING COUNT(*) > 5; Prof. Billibon Yoshimi 9/19/2018

What if we really wanted Number of employees making over $40,000 in departments with greater than 5 employees…. Prof. Billibon Yoshimi 9/19/2018

Result Query SELECT DNAME, COUNT(*) FROM EMPLOYEE, DEPARTMENT WHERE DNO IN ( SELECT DNO FROM EMPLOYEE GROUP BY DNO HAVING COUNT(*) >5 ) GROUP BY DNAME; Prof. Billibon Yoshimi 9/19/2018

How to think about SELECT queries 1. FROM first 2. WHERE 3. GROUP BY 4. HAVING 5. ORDER BY 6. SELECT Prof. Billibon Yoshimi 9/19/2018

INSERT command INSERT INTO EMPLOYEE VALUES (‘john’,’q’,’public’,’111223333’,’2000-02-02’,’address’,’m’,20000,NULL,3) Or a list of values separated by commas. Can also specify attribute mapping INSERT INTO EMPLOYEE(LNAME,FNAME,SSN) VALUES (same order). Prof. Billibon Yoshimi 9/19/2018

INSERT constraints Values not specified map to NULL or default value if specified. All integrity checks are checked. - Entity integrity (no NULL primary key) - Referential integrity (Foreign key must be valid) Prof. Billibon Yoshimi 9/19/2018

How to implement nested queries in MySQL. CREATE TABLE TEMPTBL (DNAME VARCHAR(15), NO_EMPL INT, TOTAL_SAL INT); INSERT INTO TEMPTBL (DEPT_NAME, NO_EMPL, TOTAL_SAL) SELECT DNAME, COUNT(*),SUM(SALARY) FROM EMPLOYEE JOIN DEPARTMENT ON DNO=DNUMBER GROUP BY DNAME; Then use TEMPTBL where you’d normally use the nested SELECT. Prof. Billibon Yoshimi 9/19/2018

DELETE command DELETE FROM <relation> WHERE <condition>; DELETE FROM EMPLOYEE WHERE SSN=‘11122333’; DELETE FROM EMPLOYEE; Beware of the last one, it deletes all tuples from the EMPLOYEE relations. Depending on referential triggers, references to deleted tuples can cascase or delete referers. Prof. Billibon Yoshimi 9/19/2018

UPDATE command UPDATE <relation> SET <attribute=value pairs> WHERE <condition> Prof. Billibon Yoshimi 9/19/2018

Views Virtual tables. Prof. Billibon Yoshimi 9/19/2018

Project Groups of 2. Demonstrate projects instead of final exam.( Monday Dec 16. 9-11AM in class) Deadlines: Summary of system requirements Entity-relation diagram Relational database design Application program design Prof. Billibon Yoshimi 9/19/2018

Project Document all design decisions and justifications for those decisions. Include all instances used for the project in Appendix. Oct 21 - Prof. Billibon Yoshimi 9/19/2018

Prof. Billibon Yoshimi 9/19/2018