Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr.

Slides:



Advertisements
Similar presentations
Fundamentals of Database Systems Fourth Edition El Masri & Navathe
Advertisements

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
Displaying Data from Multiple Tables. EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS
Database technology Lecture 2: Relational databases and SQL
Database Design -- Basic SQL
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Chapter 8 SQL-99: SchemaDefinition, Constraints, and Queries and Views.
CS 104 Introduction to Computer Science and Graphics Problems Introduction to Database (2) Basic SQL 12/05/2008 Yang Song.
관계 연산자 & 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.
Al-Imam University Girls Education Center Collage of Computer Science 1 ST Semester, 1432/1433H Chapter 8 Part 4 SQL-99 Schema Definition, Constraints,
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
Structured Query Language The main reference of this presentation is the textbook and PPT from : Elmasri & Navathe, Fundamental of Database Systems, 4.
Other SQL Query Examples
Chapter 8 Part 1 SQL-99 Schema Definition, Constraints, Queries, and Views.
Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr.
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:
Relational Algebra - Chapter (7th ed )
 Employee (fname, minit, lname, ssn, bdate, address, sex, salary, superssn, dno)  Department (dname, dnumber, mgrssn, mgrstartdate) 
Chapter 5-1 CSE 4701 In Class SQL Queries – Part II n Homework 3 from Spring 2015 n Problem 6.18 from the 6 th edition done in SQL and NOT relational expressions.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
Slide 8- 1 THE HAVING-CLAUSE Provides a condition on the summary information Sometimes we want to retrieve the values of these functions for only those.
Structured Query Language
DatabaseIM ISU1 Fundamentals of Database Systems Chapter 6 The Relational Algebra.
Week 8-9 SQL-1. SQL Components: DDL, DCL, & DML SQL is a very large and powerful language, but every type of SQL statement falls within one of three main.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 (SQL Basics) Lecture # 9 July 7,2012.
Copyright © 2004 Pearson Education, Inc. Schema Definition, Basic Constraints, and Queries.
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) هي وسيلة لتوضيح الدرس واداة.
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.
The SQL Database Grammar
Chapter 3 Introduction to SQL
CS580 Advanced Database Topics
CHAPTER 6 Basic SQL. CHAPTER 6 Basic SQL Chapter 6 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries.
SQL: SchemaDefinition, Constraints, and Queries and Views
Chapter 4 Basic SQL.
6/22/2018.
CS580 Advanced Database Topics
Database Systems Basic SQL
Retrieval Queries in SQL(DML)
376a. Database Design Dept. of Computer Science Vassar College
Subject Name: DATA BASE MANAGEMENT SYSTEM Subject Code: 10cs54
376a. Database Design Dept. of Computer Science Vassar College
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
CS4222 Principles of Database System
Session - 6 Sequence - 2 SQL: The Structured Query Language:
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-1 Week 8-9.
Session - 6 Sequence - 1 SQL: The Structured Query Language:
Structured Query Language (3)
SQL-99: Schema Definition, Constraints, and Queries and Views
ISC321 Database Systems I Chapter 4: SQL: Data definition, Constraints, and Basic Queries and Updates Fall 2015 Dr. Abdullah Almutairi.
SQL Updating Database Contents Presented by: Dr. Samir Tartir
Session - 6 Sequence - 1 SQL: The Structured Query Language:
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
Presentation transcript:

Chapter 4 6e & 8 5e: Basic SQL Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 191 Auditorium Road, Box U-155 Storrs, CT 06269-3155 steve@engr.uconn.edu http://www.engr.uconn.edu/~steve (860) 486 - 4818 About one third of these slides are being used with the permission of Dr. Ling Lui, Associate Professor, College of Computing, Georgia Tech. About one-half of these slides have been adapted from the AWL web site for the textbook.

Relational Languages A Relational Language Defines Operations to Manipulate Relations Used to Specify Retrieval Requests (Queries) Query Result is Expressed in the Form of a Relation Classification Relational Algebra (We’ve Discussed) Relational Calculus To be Briefly Explored as the Basis of ... Structured Query Language (SQL) Relational calculus non-procedural state what the properties that should hold in the result relation are Relational algebra procedural closed: use operators which work on one or two relations and produce another relation chaining of operations

Relational Calculus Based on First-Order Predicate Logic Symbol Alphabet Logic Symbols (e.g., ¬ a Set of Constants a Set of Variables a Set of n-ary Predicates a Set of n-ary Functions Parentheses Expressions (called well-formed formulae (wff)) Built from this Symbol Alphabet Classification: Tuple Relational Calculus Domain Relational Calculus Relational Calculus: Instead of specifying how to obtain the result, specify what the result is, i.e., the relationships that is supposed to hold in the result. Classification: according to the primitive variable used in specifying the queries tuple relational calculus domain relational calculus

Tuple Relational Calculus The Primitive Variable is a Tuple Variable Which Specifies a Tuple of a Relation Ranges Over the Tuples of a Relation In Tuple Relational Calculus, Queries are Specified as {t | F(t)} where t is a Tuple Variable and F is a Formula Consisting of the Atoms and Operators

Example EMP(ENO, ENAME, AGE) PROJ(PNO, PNAME, LOC, MGR) WORKS(ENO, PNO, DUR) Find the Names of Employees under age 30 { t[ENAME] | tEMP t[AGE]<30} Find the Names of Employees working on the CAD/CAM Project { t[ENAME] | tEMP u(u WORKS t[ENO]u v(vPROJu[PNO]=v[PNO] v[PNAME]=‘CAD/CAM’)) ENAME (AGE < 30 (EMP)) ENAME (PNAME=‘CAD/CAM” (PROJ) PNO (WORKS ENOEMP))

Tuple Relational Calculus A formula F is Composed of Atoms Boolean operators ¬ Existential Qualifier  Universal Qualifier  Formation rules: Each Atom is a Formula If F and G are Formulae, so are FG, FG, ¬F, and ¬G If F is a Formula, so is (F) If F is a Formula and t is a Free variable in F, then  t(F) and t(F) are also Formulae Nothing else is a Formula

Tuple Relational Calculus The Atoms are the Following : Tuple variables R.t or R(t) Conditions s[A] t where s and t are Tuple Variables and A and B are Components of s and t, Respectively, and <><=>= specifies that Component A of s stands in relation to component B of t (e.g., s[SALARY] > t[SALARY]) s[A] c where s, A and  are as Defined above and c is a Constant e.g., s[NAME] = 'Smith'.

Example Find the names of Employees who have Worked for a Project for more than Two Years { t[ENAME] | tEMP u(u WORKS t[ENO]u u[DUR]=‘24’)) Find all Managers who are less than 40 years old? { t[MGR] | tPROG u(u WORKS t[PNO]uPN v(vEMPu[ENO]=v[ENO] v[AGE]<40))  ENAME (DUR=24 (WORKS) ENO EMP) MGR (AGE<40 EMP ENO (WORKS PNOPROJ))

SQL: Tuple Relational Calculus-Based SQL is a Partial Example of a Tuple Relational Language Simple Queries are all Declarative More Complex Queries are both Declarative and Procedural (e.g., joins, nested queries) Find the names of employees working on the CAD/CAM project SELECT EMP.ENAME FROM EMP, WORKS, PROJ WHERE (EMP.ENO= WORKS.ENO) AND (WORKS.PNO = PROJ.PNO) AND (PROJ.PNAME = “CAD/CAM”) Tuple Variables are Implicit

Explicit Tuple Variables Find the Pairs of all Project Names for those Projects that are Located at the same Place SELECT (P1.PNAME, P2.PNAME) FROM PROJ P1, PROJ P2 WHERE P1.LOC = P2.LOC PNAME, PNAME1 (PROJ LOC = LOC1 PROJ1) Let Proj1(PNAME1, LOC1) = PNAME, LOC (PROJ)

SQL Components Data Definition Language (DDL) For External and Conceptual Schemas Views - DDL for External Schemas Data Manipulation Language (DML) Interactive DML Against External and Conceptual Schemas Embedded DML in Host PLs (EQL, JDBC, etc.) Others Integrity (Allowable Values/Referential) Catalog and Dictionary Facilities Transaction Control (Long-Duration and Batch) Authorization (Who can Do What When)

SQL DDL and DML Data Definition Language (DDL) Defining the Relational Schema - Relations, Attributes, Domains - The Meta-Data CREATE TABLE Student: Name(CHAR(30)), SSN(CHAR(9)), GPA(FLOAT(2)) CREATE TABLE Courses: Course#(CHAR(6)), Title(CHAR(20)), Descrip(CHAR(100)), PCourse#(CHAR(6)) Data Manipulation Language (DML) Defining the Queries Against the Schema SELECT Name, SSN From Student Where GPA > 3.00

History of SQL SQL is based on the Relational Tuple Calculus Evolved from SEQUEL: Structured English QUEry Language - part of IBM’s SYSTEM R, 1974 SQL2 Supported by ORACLE, SYBASE, INFORMIX, IBM DB2, SQL SERVER, … MS Access, MySQL, … SQL2 also called SQL/92 is evolved from SQL/86, SQL/89, all were ANSI & ISO standard Ongoing work on SQL3 with OO Extensions

Data Definition Language - DDL A Pre-Defined set of Primitive Types Numeric Character-string Bit-string Additional Types Defining Domains Defining Schema Defining Tables Defining Views Note: Each DBMS May have their Own DBMS Specific Data Types - Is this Good or Bad? primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

DDL - Primitive Types Numeric INTEGER (or INT), SMALLINT REAL, DOUBLE PRECISION FLOAT(N) Floating Point with at Least N Digits DECIMAL(P,D) (DEC(P,D) or NUMERIC(P,D)) have P Total Digits with D to Right of Decimal Note that INTs and REALs are Machine Dependent (Based on Hardware/OS Platform) primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

DDL - Primitive Types Character-String CHAR(N) or CHARACTER(N) - Fixed VARCHAR(N), CHAR VARYING(N), or CHARACTER VARYING(N) Variable with at Most N Characters Bit-Strings BIT(N) Fixed VARBIT(N) or BIT VARYING(N) Variable with at Most N Bits primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

DDL - Primitive Types These Specialized Primitive Types are Used to: Simplify Modeling Process Include “Popular” Types Reduce Composite Attributes/Programming DATE : YYYY-MM-DD TIME: HH-MM-SS TIME(I): HH-MM-SS-F....F - I Fraction Seconds TIME WITH TIME ZONE: HH-MM-SS-HH-MM TIME-STAMP: YYYY-MM-DD-HH-MM-SS-F...F{-HH-MM} NOTE: Different DBMS have Different Date/Time primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

DDL - What are Domains? Domains are Similar in Concepts to Programming Language Type Definitions A Domain can be Defined as Follows: CREATE DOMAIN CITY CHAR(15) DEFAULT ‘<Storrs>’; CREATE DOMAIN SSNFORMAT CHAR(9); Advantage of Using Domains Changing a Domain Definition in One Place Changes it Consistently Everywhere it is Used Default Values Can Be Defined for Domains Constraints Can Be Defined for Domains

DDL - Dropping a Domain A Domain is Dropped As Follows: DROP DOMAIN CITY RESTRICT; DROP DOMAIN SSNFORMAT CASCADE; Restrict: Drop Operation Fails If the Domain is Used in Column Definitions Cascade: Drop Operation Causes Columns to be Defined Directly on the Underlying Data Type

What is a SQL Schema? A Schema in SQL is the Major Meta-Data Construct Create a DB to Contain Multiple Tables Supports the Definition of: Relation - Table with Name Attributes - Columns and their Types Identification - Primary Key Constraints - Referential Integrity (FK) Two Part Definition CREATE Schema - Named Database or Conceptually Related Tables CREATE Table - Individual Tables of the Schema

DDL-Create/Drop a Schema Creating a Schema: CREATE SCHEMA MY_COMPANY AUTHORIZATION Demurjian; Schema MY_COMPANY bas Been Created and is Owner by the User “Demurjian” Tables can now be Created and Added to Schema Dropping a Schema: DROP SCHEMA MY_COMPANY RESTRICT; DROP SCHEMA MY_COMPANY CASCADE; Restrict: Drop Operation Fails If Schema is Not Empty Cascade: Drop Operation Removes Everything in the Schema

DDL - Create Tables CREATE TABLE EMPLOYEE ( FNAME VARCHAR(15) NOT NULL , MINIT CHAR , LNAME VARCHAR(15) NOT NULL , SSN CHAR(9) NOT NULL , BDATE DATE ADDRESS VARCHAR(30) , SEX CHAR , SALARY DECIMAL(10,2) , SUPERSSN CHAR(9) , DNO INT NOT NULL , PRIMARY KEY (SSN) , FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN) , FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ) ;

DDL - Create Tables (continued) CREATE TABLE DEPARTMENT ( DNAME VARCHAR(15) NOT NULL , DNUMBER INT NOT NULL , MGRSSN CHAR(9) NOT NULL , MGRSTARTDATE DATE , PRIMARY KEY (DNUMBER) , UNIQUE (DNAME) , FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN) ) ; CREATE TABLE DEPT_LOCATIONS (DNUMBER INT NOT NULL , DLOCATION VARCHAR(15) NOT NULL , PRIMARY KEY (DNUMBER, DLOCATION) , FOREIGN KEY (DNUMBER) REFERENCES DEPARTMENT(DNUMBER) ) ;

DDL - Create Tables (continued) CREATE TABLE PROJECT (PNAME VARCHAR(15) NOT NULL , PNUMBER INT NOT NULL , PLOCATION VARCHAR(15) , DNUM INT NOT NULL , PRIMARY KEY (PNUMBER) , UNIQUE (PNAME) , FOREIGN KEY (DNUM) REFERENCES DEPARTMENT(DNUMBER) ) ; CREATE TABLE WORKS_ON (ESSN CHAR(9) NOT NULL , PNO INT NOT NULL , HOURS DECIMAL(3,1) NOT NULL , PRIMARY KEY (ESSN, PNO) , FOREIGN KEY (ESSN) REFERENCES EMPLOYEE(SSN) , FOREIGN KEY (PNO) REFERENCES PROJECT(PNUMBER) ) ;

DDL - Create Tables with Constraints CREATE TABLE EMPLOYEE ( . . . , DNO INT NOT NULL DEFAULT 1, CONSTRAINT EMPPK PRIMARY KEY (SSN) , CONSTRAINT EMPSUPERFK FOREIGN KEY (SUPERSSN) REFERENCES EMPLOYEE(SSN) ON DELETE SET NULL ON UPDATE CASCADE , CONSTRAINT EMPDEPTFK FOREIGN KEY (DNO) REFERENCES DEPARTMENT(DNUMBER) ON DELETE SET DEFAULT ON UPDATE CASCADE );

DDL - Create Tables with Constraints CREATE TABLE DEPARTMENT ( . . . , MGRSSN CHAR(9) NOT NULL DEFAULT '888665555' , . . . , CONSTRAINT DEPTPK PRIMARY KEY (DNUMBER) , CONSTRAINT DEPTSK UNIQUE (DNAME), CONSTRAINT DEPTMGRFK FOREIGN KEY (MGRSSN) REFERENCES EMPLOYEE(SSN) ON DELETE SET DEFAULT ON UPDATE CASCADE );

Create and Drop: Summary Defines Types and Order of Attributes in a Relation May Specify Which Attribute Are Keys and Which Cannot Be Null Create a New Empty Table May Define DELETION Effect by Cascade/Restricted CREATE TABLE Supplier_Parts ( S# CHAR(5) NOT NULL, P# CHAR(6) NOT NULL, QTY INTEGER, PRIMARY KEY (S# P#) FOREIGN KEY S# REFERENCE SUPPLIER ON DELETE CASCADE, REFERENCE PART ON DELETE RESTRICT);

SQL Data Definition Drop Table A Relation Can Be Dropped at Any Time Drop Will Delete Both Definition and Data All Views, Indexes, and FKs are Dropped DROP TABLE SUPPLIER; Alter Table Add New Attributes or PK and FK to the Table All Existing Records are Expanded With Nulls, but Not Physically Changed. ALTER TABLE SUPPLIER ADD DISCOUNT SMALLINT;

DDL - Drop Tables Command: DROP TABLE EMPLOYEE RESTRICT; DROP TABLE DEPARTMENT CASCADE; Restrict: Drop Operation fails if the Table is Referenced by View and/or Constraint Definitions Cascade: Drop Operation Removes Referencing View and Constraint Definitions

DDL - Change Table Structure Add a Column to a Table: ALTER TABLE EMPLOYEE ADD JOB VARCHAR(12); No DEFAULT Implies NULL Values for all Tuples Drop a Column from a table ALTER TABLE EMPLOYEE DROP JOB RESTRICT (or CASCADE); Restrict: Drop Operation Fails if Column is Referenced Cascade: Drop Operation Removes Referencing View and Constraint Definitions

Chinook sql file

Chinook sql file

Chinook sql file

Chinook sql file

Chinook sql file

Data Manipulation Language - DML SQL has the SELECT Statement for Retrieving Info. from a Database (Not Relational Algebra Select) SQL vs. Formal Relational Model SQL Allows a Table (Relation) to have Two or More Identical Tuples in All Their Attribute Values Hence, an SQL Table is a Multi-set (Sometimes Called a Bag) of Tuples; it is Not a Set of Tuples SQL Relations Can Be Constrained to Sets by PRIMARY KEY or UNIQUE Attributes Using the DISTINCT Option in a Query primitive types numeric (integers, floating-point real number REAL, DOUBLE PRECISION, FLOAT(N) DECIMAL(P,D), with P digits of which D are to the right of the decimal point character-string CHAR(N) (or CHARACTER(N)) is a fixed-length character string VARCHAR(N) (or CHAR VARYING(N), or CHARACTER VARYING(N)) is a variable-length character string with at most N characters bit-strings BIT(N) is a fixed-length bit string VARBIT(N) (or BIT VARYING(N)) is a bit string with at most N bits

Interactive DML - Main Components Select-from-where Statement Contains: Select Clause - Chosen Attributes/Columns From Clause - Involved Tables Where Clause - Constrain Tuple Values Tuple Variables - Distinguish Among Same Names in Different Tables String Matching - Detailed Matching Including Exact Starts With Near Ordering of Rows - Sorting Tuple Results

Interactive DML - Main Components Select-from-where Statement Contains: Set Operations - Search to See if a Value is in Set Built-in Functions - Count, Mix, Max, Sum, Avg Nested Subqueries - Queries within Queries Joins - As Discussed for Relational Algebra Recursive Queries (Defer - Part of SQL3) Modification-Based Selects for Insert - Create a New Tuple Delete - Remove Existing Tuple(s) Update - Change Existing Tuple(s)

SQL Data Manipulation target-listconditionrelation-list Skeleton Query: SELECT target-list FROM relation-list WHERE condition or subquery GROUP BY attribute-list HAVING condition ORDER BY attribute-list SELECT - relational “project” WHERE - relational “select” and/or “join” In principle, a SQL query equals to an algebra expression target-listconditionrelation-list

Simple Select-From-Where Format: Equivalent Algebra Statement: SELECT Specifies the Columns of the Query Result FROM Specifies the Tables to Be Used in the Query WHERE Specifies the Query Condition Restriction: Must Refer to Columns of the Tables in the FROM Clause SELECT A1, A2, ... An FROM R1 , R2 , ... Rm WHERE Predicate (Boolean/Set Expression) p A 1 , 2 , ... n ( s P R  R m ))  ... 

Recall Prior Schema

…and Corresponding DB Tables Which Represent Tuples/Instances of Each Relation A S C null W B 1 4 5

…and Corresponding DB Tables

Simple SQL Queries Query 0: Retrieve the Birthdate and Address of the Employee whose Name is 'John B. Smith'. SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’ Which Row(s) are Selected? Note: While All of these Next Queries are from Chapter 4, Some are From “Earlier” Edition B S C null W

Simple SQL Queries Query 1: Retrieve Name and Address of all Employees who work for the 'Research' Department SELECT FNAME, MINIT, LNAME, ADDRESS, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO What Action is Being Performed?

Simple SQL Queries - Result Theta Join on DNO=DNUMBER

Simple SQL Queries – Fully Qualified The Full Table Name with “.” Notation Differentiates Among the Attributes Query 1: Retrieve Name and Address of all Employees who work for the 'Research' Department SELECT EMPLOYEE.FNAME, EMPLOYEE.MINIT, EMPLOYEE. LNAME,EMPLOYEE.ADDRESS, DEPARTMENT.DNAME FROM EMPLOYEE, DEPARTMENT WHERE DEPARTMENT.DNAME='Research' AND DEPARTMENT.DNUMBER= EMPLOYEE.DNO

Simple SQL Queries Query 2: For Every Project in 'Stafford', list the Project Number, the Controlling Dept. Number, and the Dept. Manager's Last Name, Address, and Birthdate SELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford' In Q2, there are Two Join Conditions: The Join Condition DNUM=DNUMBER Relates a Project to its Controlling Department The Join Condition MGRSSN=SSN Relates the Controlling Department to the Employee who Manages that Department

Query Results SELECT PNUMBER, DNUM, LNAME, BDATE,ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford' A S C null W B

Qualification of Attributes In SQL, the Same Name for Two (or More) Attributes is Allowed if Attributes are in Different Relations In Those Cases, Query Must Qualify by Prefixing the Relation Name to the Attribute Name EMPLOYEE.LNAME, DEPARTMENT.DNAME Aliases: When Queries Must Refer to the Same Relation Twice Alias is Akin to a Variable in a PL - Reference In These Situations, it is Considered that there are Two Different Copies of the Same Relation Let’s See Examples of Both Concepts

Attribute Qualification Query 8: For Each Employee, Retrieve the Employee's Name, and Name of his or her Immediate Supervisor SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E S WHERE E.SUPERSSN=S.SSN E and S are aliases for the EMPLOYEE relation E Represents Employees in the Role of Supervisees S Represents Employees in the Role of Supervisor Another Form of Query 8 is: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN

Query Results – Refer to Same Table Twice SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN A S C null W B

Conceptually There are two Separate Tables System Goes Through Every Row of Top Against Every Row of Bottom This is Conceptual In Reality – Only 1 Table Exists EMPLOYEE AS E A S C null W B EMPLOYEE AS S A S C null W B

Unspecified WHERE Clause A Missing Where-clause Indicates No Condition; All Tuples of Relations in From-clause Are Selected Query 9: Retrieve the SSN Values for All Employees SELECT SSN FROM EMPLOYEE

Unspecified WHERE Clause More Than One Relation and No Join Condition Results in the CARTESIAN PRODUCT of Tuples Query 10: SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT Overlooking Selection and Join Conditions in the Where-Clause Likely Yields Incorrect and Very Large Relations May Result – What Happens with these?

How Many Tuples are Generated? Every Row of Employee table is matched with Every Row of the Department table 8 times 3 – means 24 Rows Most are useless….

Use of * and Distinct When a * is Used, All of the Attributes are Chosen Q1C: SELECT * FROM EMPLOYEE WHERE DNO=5

Use of * and Distinct When a * is Used, All of the Attributes are Chosen Q1D: SELECT * FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNO=DNUMBER

Use of * and Distinct SQL Does Not Support Sets so Duplicates are Retrieved Q11: SELECT SALARY FROM EMPLOYEE Q11A: SELECT DISTINCT SALARY FROM EMPLOYEE

SELECT * in MySQL WorkBench

SELECT * in MySQL WorkBench

Set Operations - Union/Intersection/Minus Not all DBMS Support Intersection/Minus Union: The two Relations must have Same Attributes and the Attributes must Appear in the Same Order Query 4: All Project Numbers for Projects with Employee 'Smith' as a Worker or as a Manager (SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

Set Operations - Union/Intersection/Minus (SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

Set Operations - Union/Intersection/Minus Utilizing the DISTINCT KEYWORD Query 4: Make a list of all project numbers for projects that involve an employee whose last name is ‘Smith’, either as a worker or as a manager of the department that controls the project. (SELECT DISTINCT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT DISTINCT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith')

Substring Comparison in SQL Queries In Regard to Strings, Most DBMSs Support SQL Queries for Exact, Near, and Starts with Matching LIKE is Used to Compare Partial Strings '%' (or '*') Replaces an Arbitrary # of characters '_' replaces a single arbitrary character Query 12: Retrieve all Employees whose Address is in Houston, Texas. SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX% ' Houston, TX can be anywhere within the ADDRESS VAR CHAR String

Substring Comparison in SQL Queries The LIKE Operator Allows us to get Around the Fact that each Value is Considered Atomic and Indivisible SQL: Character String Attribute values are not Atomic Query 12A: Retrieve all employees who were born during the 1950s. SELECT FNAME, LNAME FROM EMPLOYEE WHERE BDATE LIKE ' __5_______' There are two “_” before 5 and seven “_” after 5 Underscores are “blanks”

Arithmetic Operations in SQL Queries Standard Arithmetic Operators '+', '-'. '*', and '/' can be Applied to Numeric Values in an SQL Query Result Query 13: Show the Effect of Giving all Employees who work on the 'ProductX' project a 10% raise. SELECT FNAME, LNAME, 1.1*SALARY FROM EMPLOYEE, WORKS_ON, PROJECT WHERE SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' This Doesn’t Change the Table – just Output!

ORDER BY Clause in SQL Queries ORDER BY used to Sort the Tuples in a Query Result based on the Values of one or More Attribute(s) Query 15: Retrieve a list of Employees and the Projects each works in, ordered by Dept., and within each Dept., alphabetically by Employee last name SELECT DNAME, LNAME, FNAME, PNAME FROM DEPARTMENT, EMPLOYEE, WORKS_ON, PROJECT WHERE DNUMBER=DNO AND SSN=ESSN AND PNO=PNUMBER ORDER BY DNAME, LNAME Default is Ascending - Can be ASC/DESC as we’ll see in a Later Example in Chapter 5

Natural Join Queries Specially Tells SQL that a Natural Join is Defined Between Tables SELECT * FROM COUNTRIES NATURAL JOIN CITIES SELECT * FROM COUNTRIES JOIN CITIES USING (COUNTRY, COUNTRY_ISO_CODE) Note that * Expands the JOIN in 1st Query to: All the common columns Every column in the first (left) table that is not a common column Every column in the second (right) table that is not a common column Natural Join in the FROM LIST

Homework 3 from Spr 2015 Problem 6.18 from the 6th edition done in SQL and NOT relational expressions

Problem 6.18 in 6th edition How many copies of the book titled The Lost Tribe are owned by the library branch whose name is ‘Sharpstown’? SELECT NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' AND BranchName='Sharpstown’ BaB= (BOOKCOPIES *(Title=‘The Lost Tribe’ (BOOK))) ) BookId Ans = No_Of_Copies( (BranchName=‘Sharpstown’ (LIBRARY-BRANCH)) * BaB) BranchID

Problem 6.18 in 6th edition BranchId b. How many copies of the book titled The Lost Tribe are owned by each library branch? SELECT BranchName, NoOfCopies FROM ( (BOOK NATURAL JOIN BOOK_COPIES ) NATURAL JOIN LIBRARY_BRANCH ) WHERE Title='The Lost Tribe' CaB = BOOKCOPIES * LIBRARY_BRANCH) BranchId Ans = BranchName, No_Of_Copies( (Title=‘The Lost Tribe’ (BOOK)) * CaB) BookId

Homework 3 from Spr 2015 Problem 4.10 in 6th edition

Problem 4.10 in 6th edition

Problem 4.10 in 6th edition (a) Retrieve the names of employees in department 5 who work more than 10 hours per week on the 'ProductX' project. SELECT LNAME, FNAME FROM EMPLOYEE, WORKS_ON, PROJECT WHERE DNO=5 AND SSN=ESSN AND PNO=PNUMBER AND PNAME='ProductX' AND HOURS>10 Result: LNAME FNAME Smith John English Joyce

Problem 4.10 in 6th edition Result (empty): (b) List the names of employees who have a dependent with the same first name as themselves. SELECT LNAME, FNAME FROM EMPLOYEE, DEPENDENT WHERE SSN=ESSN AND FNAME=DEPENDENT_NAME Result (empty):

Problem 4.10 in 6th edition (c) Find the names of employees that are directly supervised by 'Franklin Wong'. SELECT E.LNAME, E.FNAME FROM EMPLOYEE E, EMPLOYEE S WHERE S.FNAME='Franklin' AND S.LNAME='Wong' AND E.SUPERSSN=S.SSN Result: LNAME FNAME Smith John Narayan Ramesh English Joyce

Problem 4.10 in 6th edition Result: AVG(SALARY) 31000 (h) Retrieve the average salary of all female employees. SELECT AVG (SALARY) FROM EMPLOYEE WHERE SEX='F’ Result: AVG(SALARY) 31000

Other SQL Queries Hmwk 4 Spring 2015 Problem 3.4 for the Northwind Database Schema Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. Count and print the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. For each country (ShipCountry in Orders), total the Freight charges. The countries are: France, Germany, Brazil, Belgium, Switzerland, Venezuela, Austria, Mexico, USA, Sweden, Finland, Italy, Spain, UK, Ireland, Portugal, Canada, Denmark, Poland, Norway, Argentina

Explaining Northwind Schema Suppliers: A Suppliers Contact Info and web link. Products: Names, suppliers, and Prices Categories: Categories of Northwind products such as Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood Orders: For each Customer with dates &Shipping Order Details: Products, quantities, and price. Employees: Typical Info. Customers: Typical Info. Shippers: Typical Info.

Northwind Schema

Northwind Schema – Key Types

Find and print the company names and company addresses of all Suppliers that supply the category name Seafood. SELECT DISTINCT suppliers.CompanyName, suppliers.Address FROM northwind.suppliers, northwind.categories, northwind.products WHERE suppliers.SupplierID = products.SupplierID AND categories.CategoryID = products.CategoryID AND categories.CategoryName = 'Seafood';

Count/the number of suppliers for each of the eight different categories of food which by name are: Beverages, Condiments, Confections, Dairy Products, Grains/Cereals, Meat/Poultry, Produce, Seafood. SELECT categories.CategoryName, COUNT(suppliers.SupplierID) FROM northwind.categories, northwind.products, northwind.suppliers WHERE suppliers.SupplierID = products.SupplierID AND products.categoryID = categories.CategoryID GROUP BY categories.CategoryName;

For each country (ShipCountry in Orders), total the Freight charges. SELECT orders.ShipCountry, SUM(orders.Freight) FROM northwind.orders GROUP BY orders.ShipCountry;

Other SQL Queries Hmwk 2 Fall 2015 Problem 3.4 for the Northwind Database Schema Find the list of all customers from United Kingdom sorted by Company Name in ascending order and return the company Name and Country. Find the number of customers that are located in each country. Find the Product Name, UnitPrice, and UnitsInStock and Sorted by ProductName for all products where the product name starts with “Ch”.

Find list of all customers from United Kingdom SELECT northwind.suppliers.CompanyName, northwind.suppliers.country FROM northwind.suppliers WHERE northwind.suppliers.Country="UK" ORDER BY northwind.suppliers.CompanyName ASC Exotic Liquids UK Specialty Biscuits, Ltd.

Find number of customers in each country. Argentina 3 Austria 2 Belgium Brazil 9 Canada Denmark Finland France 11 Germany Ireland 1 Italy Mexico 5 Norway Poland Portugal Spain Sweden Switzerland UK 7 USA 13 Venezuela 4 SELECT northwind.customers.country, COUNT(*) FROM northwind.customers WHERE northwind.customers.country IS NOT NULL GROUP BY northwind.customers.country

Find the Product Name …starts with “Ch”. SELECT northwind.products.productid, northwind.products.productname, northwind.products.UnitsinStock FROM northwind.products WHERE northwind.products.productname LIKE 'CH%'; 1 Chai 39 2 Chang 17 Chartreuse verte 69 4 Chef Anton's Cajun Seasoning 53 5 Chef Anton's Gumbo Mix 48 Chocolade 15

INSERT SQL Queries Add one or more Tuples to a Relation, with Attribute values Listed in the order specified in the CREATE Update 1: INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC-52', '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 ) Another Form of Update 1: INSERT INTO EMPLOYEE (FNAME, LNAME, SSN) VALUES ('Richard','K','Marini') All PK and FK Values must be Provided Nulls are Allowed DDL Constraints are Enforced

INSERT SQL Queries More Sophisticated Insert can Involve Query Update 3A: CREATE TABLE DEPTS_INFO (DEPT_NAME VARCHAR(10), NO_OF_EMPS INTEGER, TOTAL_SAL INTEGER); Update 3B: INSERT INTO DEPTS_INFO (DEPT_NAME, NO_OF_EMPS, TOTAL_SAL) SELECT DNAME, COUNT (*), SUM (SALARY) FROM DEPARTMENT, EMPLOYEE WHERE DNUMBER=DNO GROUP BY DNAME ;

Program Level INSERTS Mass Import into DB Consider Chinook_MySql.sql

Program Level INSERTS Importing Excel Directly into MySQL Many Available Tools http://excel2mysql.net/ Importing an XML File directly into MySQL LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL; Tools such as: http://www.navicat.com/ Likewise – Ability to EXPORT as well SQL Data Export and Import Wizard For MySQL See: https://dev.mysql.com/doc/workbench/en/wb-admin-export-import-management.html

DELETE SQL Queries Sample Deletes Include DELETE FROM EMPLOYEE WHERE LNAME='Brown' DELETE FROM EMPLOYEE WHERE SSN='123456789’ DELETE FROM EMPLOYEE WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') DELETE FROM EMPLOYEE No. of Tuples Deleted Dependent on WHERE Clause Referential Integrity is Enforced During DELETE

UPDATE SQL Queries Used to Modify Attribute Values of One or More Selected Tuples A Where-clause Selects the Tuples to Be Modified An Additional Set-Clause Specifies the Attributes to Be Modified and Their New Values Each Command Modifies Tuples in the Same Relation Referential Integrity Must Be Enforced UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10

UPDATE SQL Queries Give all Employees in the 'Research' Dept. a 10% raise UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE DNO IN (SELECT DNUMBER FROM DEPARTMENT WHERE DNAME='Research') Modified SALARY Value Depends on the Original SALARY Value in each Tuple SALARY = SALARY *1.1 - Use PL Interpretation

Concluding Remarks What have we Seen in Chapter 4? Complete Data Definition in SQL Creating Schema Creating/Dropping Tables FKs and PKs Basic Data Manipulation in SQL Different Selects Aggregate Functions Insert, Update, and Delete Strongly Encouraged to Engage in Practice with your DBMS of Choice for your Project

Jump to Homework 2 in cse4701ann.pptx