SQL: Structured Query Language Instructor: Mohamed Eltabakh 1.

Slides:



Advertisements
Similar presentations
Chapter 4: SQL  Basic Structure  Data Definition Language  Modification of the Database  Set Operations  Aggregate Functions  Null Values  Nested.
Advertisements

Ver 1,12/09/2012Kode :CCs 111,Sistem basis DataFASILKOM Chapter 3: SQL Bambang Irawan Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan.
CS4432: Database Systems II Query Operator & Algebraic Expressions 1.
1 Today’s Class  Relational Model  SQL CS F212 Database Systems.
E-R Diagram for a Banking Enterprise
Oct 28, 2003Murali Mani Relational Algebra B term 2004: lecture 10, 11.
SQL Sangeeta Devadiga CS157A, Fall Outline Background Data Definition Basic Structure Set Operation.
Dec 4, 2003Murali Mani SQL B term 2004: lecture 14.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Ordering the Display of Tuples List in alphabetic order the names of all customers having.
Murali Mani SQL: Updates (DML) and Views (DDL). Murali Mani SQL DML (Updating the Data) Insert Delete Update.
Database System Concepts, 5th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: SQL.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
SQL Structured Query Language Meizhen Huang. Content (4.1 – 4.4) Background Parts of SQL Basic Structure Set Operations Aggregate Functions.
Nov 24, 2003Murali Mani SQL B term 2004: lecture 12.
CS3431 SQL : Query Language. CS3431 SELECT-FROM-WHERE SELECT * FROM Student WHERE sName=“Greg” AND address=“320 FL”  (sName=“Greg” AND address=“320 FL”)
SQL Neyha Amar CS 157A, Fall Inserting The insert statement is used to add a row of data into a table Strings should be enclosed in single quotes,
Murali Mani SQL. Murali Mani SELECT-FROM-WHERE SELECT * FROM Student WHERE sName=“Greg” AND address=“320 FL”  (sName=“Greg” AND address=“320 FL”) (Student)
Cs3431 SQL: Updates (DML) and Views (DDL). cs3431 SQL DML (Updating the Data) Insert Delete Update.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Constraints, Triggers Chapter 5.
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
Instructor: Mohamed Eltabakh
CIS552SQL1 Data Definition Language Insertions Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations.
SQL I. SQL – Introduction  Standard DML/DDL for relational DB’s  DML = “Data Manipulation Language” (queries, updates)  DDL = “Data Definition Language”
Murali Mani Relational Algebra. Murali Mani What is Relational Algebra? Defines operations (data retrieval) for relational model SQL’s DML (Data Manipulation.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
Chapter 3 SQL. 2 Relational Commercial Languages  SQL (Structured Query Language)  the standard relational DB language  used interactively which transforms.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
SQL. Basic Structure SQL is based on set and relational operations with certain modifications and enhancements A typical SQL query has the form: select.
Lecture 6 Structured Query Language SQL Lecture 6 Structured Query Language SQL Instructor: Haya Sammaneh.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
Structured Query Language 2 Presented by: Annisa, M.Kom. Source: Database System Concepts 5 th edition.
Relational Algebra Instructor: Mohamed Eltabakh 1.
1 The Relational Model Instructor: Mohamed Eltabakh
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
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.
CS3431-B111 The Relational Model Instructor: Mohamed Eltabakh
Advanced SQL: Triggers & Assertions
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Relational Algebra Instructor: Mohamed Eltabakh 1 Part II.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
Relational Algebra Instructor: Mohamed Eltabakh 1.
CS34311 The Relational Model. cs34312 Why Relational Model? Currently the most widely used Vendors: Oracle, Microsoft, IBM Older models still used IBM’s.
SQL: Structured Query Language Instructor: Mohamed Eltabakh 1 Part II.
Relational Algebra Instructor: Mohamed Eltabakh 1.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Introduction to SQL.
SQL : Query Language Part II CS3431.
CS 405G: Introduction to Database Systems
SQL Views CS542.
Instructor: Mohamed Eltabakh
The Relational Model Relational Data Model
CS 405G: Introduction to Database Systems
SQL : Query Language CS3431.
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
SQL Views and Updates cs3431.
Advanced SQL: Views & Triggers
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
Instructor: Mohamed Eltabakh
SQL: Structured Query Language
CS4222 Principles of Database System
CMPT 354: Database System I
Contents Preface I Introduction Lesson Objectives I-2
SQL: Structured Query Language
SQL: Structured Query Language
Instructor: Mohamed Eltabakh
SQL: Structured Query Language
SQL: Structured Query Language
Presentation transcript:

SQL: Structured Query Language Instructor: Mohamed Eltabakh 1

First: Check Your Oracle Account cs34312

SQL Language Data Definition Language (DDL) Create tables, specifying the columns and their types of columns, the primary keys, etc. Drop tables, add/drop columns, add/drop constraints – primary key, unique, etc. Data Manipulation Language (DML) Update, Insert, Delete tuples Query the data 3 These are already covered Our focus today

Reminder About DDL 4 Create “Students” relation CREATE TABLE Students (sid: CHAR(20) Primary Key, name: CHAR(20) Not NULL, login: CHAR(10), age: INTEGER, gpa: REAL ); CREATE TABLE Courses (cid: Varchar(20) Primary Key, name: string, maxCredits : integer, graduateFlag: boolean ); Create “Courses” relation CREATE TABLE Enrolled (sid: CHAR(20) Foreign Key References (Students.sid), cid: Varchar(20), enrollDate: date, grade: CHAR (2), Constraints fk_cid Foreign Key cid References (Courses.cid)); Create “Enrolled” relation Alter Table Enrolled Add Constraints fk_cid Foreign Key cid References Courses(cid));

Reminder About: Insert, Update, Delete This is performed using Data Manipulation Language of SQL (DML) Insertion Insert into Students values (‘1111’, …); Deletion Delete from Students; Delete from Students Where sid = ‘1111’; Update Update Students Set GPA = GPA + 0.4; Update Students Set GPA = GPA Where sid = ‘1111’; 5

SQL Query Language SELECT Statement 6

Relation between Algebra and SQL-Select 7 SELECT FROM WHERE GROUP BY HAVING ORDER BY ; Will be mapped to the algebraic operators that we learned Query Plans

SELECT-FROM-WHERE SELECT FROM WHERE ; π σ relation name 8

SELECT-FROM-WHERE SELECT * FROM Student WHERE sName= ‘Greg’ AND address=‘320FL’;  (sName=‘Greg’ AND address=‘320FL’) (Student) sNumbersNameaddressprofessor 1Dave311FLMM 2Greg320FLMM 3Matt320FLER Student sNumbersNameaddressprofessor 2Greg320FLMM * Means “project all attributes” 9 Must terminate with ; to execute

SELECT-FROM-WHERE SELECT sNumber FROM Student WHERE sName=‘Greg’ AND address=‘320FL’; π sNumber (  (sName=‘Greg’ AND address=‘320FL’) (Student)) sNumbersNameaddressprofessor 1Dave311FLMM 2Greg320FLMM 3Matt320FLER Student sNumbersNameaddressprofessor 2Greg320FLMM 10

Select-From Query SELECT sNumber, sName FROM Student; sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER Student sNumbersName 1Dave 2Greg 3Matt 11 The WHERE clause is optional

Extended Projection SELECT FROM WHERE ; The select clause can have expressions and constants Can also rename the fields or expressions using “AS” keyword 12

Extended Projection SELECT ‘Name:’ || sName AS info, 0 AS gpa FROM Student WHERE address=‘320FL’; sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER Student infogpa Name:Dave0 Name:Greg0 Name:Matt0 13

Renaming Relations and Tuple Variables SELECT S1.sNumber AS num FROM Student S1 WHERE S1.sNumber >= 1; sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER Student num Tuple variable 14

Where Clause The comparison operator depends on the data type For Numbers:, =, =, <> What about Strings?? SELECT S1.sNumber AS num FROM Student S1 WHERE S1.sNumber >= 1; 15

String Operators Comparison Operators based on lexicographic ordering: =,, <>, >=, <= Concatenation operator: || Pattern match: s LIKE p p denotes a pattern Can use wild characters in p such as _, % _  matches exactly any single character %  matches zero or more characters 16 SELECT ‘Name:’ || sName FROM Student WHERE address=‘320FL’;

String Matching Example SELECT s1.sNumber AS num FROM Student S1 WHERE s1.sName LIKE ‘Da%’ Or S1.professor LIKE ‘M_’ ; sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER num

Set Operators in SQL Set Semantics Union, Intersect, Except The two relations R and S must have the same number of columns and data types (Union Compatible) Oracle allows columns to have different names They eliminate duplicates 18

Set Operations in SQL: Example 19 ; ; ;

Bag Operators in SQL Bag Semantics Union ALL, Intersect ALL, Except ALL Under bag semantics duplication is allowed 20

Example: Union ALL AB R AB S AB Suppose a tuple t appears in R m times, and in S n times. Then in the union, t appears m + n times. 21 Select * From R Union All Select * From S;

Example: Intersect ALL Select * From R Intersect All Select * From S; AB R AB S AB Suppose tuple t appears in R m times, and in S n times. Then in intersection, t appears min (m, n) times. 22

Example: Except ALL Suppose tuple t appears in R m times & in S n times. Then in R – S, t appears max (0, m - n) times. AB R AB S AB Select * From R Except All Select * From S;

Example Queries SELECT * FROM loan WHERE amount > 1200 ; SELECT L.loan_number FROM loan L WHERE L.amount > 1200 ; 24

Example Queries SELECT customer_name FROM depositor Union SELECT customer_name FROM borrower; 25

More on SQL SELECT 26

Cartesian Product in SQL SELECT * FROM Student, Professor; In Relation Algebra: R x S In SQL, add R and S to FROM clause No WHERE condition that links R and S SELECT sName, pNumber FROM Student, Professor; 27

Cross Product - Example sNumbersNameaddressprofessor 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddr 1MM141FL 2ER201FL Professor sNumbersNameaddressprofessorpNumberpNameaddr 1Dave320FL11MM141FL 1Dave320FL12ER201FL 2Greg320FL11MM141FL 2Greg320FL12ER201FL 3Matt320FL21MM141FL 3Matt320FL22ER201FL SELECT * FROM Student, Professor; 28

Theta Join in SQL SELECT * FROM Student, Professor WHERE Student.pNum = Professor.Number; In Relation Algebra: R ⋈ C S In SQL, add R and S to FROM clause WHERE condition that links R and S with the join condition C Join condition 29

Theta Join Example sNumbersNamepName 1DaveMM 2GregMM 3MattER sNumbersNameaddressprofNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddress 1MM141FL 2ER201FL Professor  sNumber,sName,pName (Student ⋈ (profNum=pNumber) Professor) SELECT sNumber, sName, pName FROM Student, Professor WHERE profNum = pNumber; 30

Theta Join Example sNumbersNameaddressprofNum 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddress 1MM141FL 2ER201FL Professor 31 If column names are the same  use relationName.attrName SELECT sName, pName, S.address FROM Student S, Professor P WHERE S.address = P.address;  sName,pName,S.address (ρ S (Student) ⋈ (S.address=P.address) ρ P (Professor))

Natural Join SELECT * FROM Student, Professor WHERE Student.pnumber = Professor.pnumber ; Student ⋈ Professor Reminder: Join columns must have same names in both relations (R ⋈ S) SELECT * FROM Student NATURAL JOIN Professor; Explicitly add the equality join condition 32

Difference between the two Queries below SELECT * FROM Student, Professor WHERE Student.pnumber = Professor.pnumber ; Student ⋈ Professor SELECT * FROM Student NATURAL JOIN Professor; Explicitly add the equality join condition 33 Common columns will appear once Common columns will appear twice

Natural Join - Example sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddr 1MM141FL 2ER201FL Professor sNumbersNameaddresspNumberpNameaddr 1Dave320FL1MM141FL 2Greg320FL1MM141FL 3Matt320FL2ER201FL 34 Must be the same name SELECT * FROM Student natural join Professor; Student ⋈ Professor Common cols appear once

Theta Join - Example sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student pNumberpNameaddr 1MM141FL 2ER201FL Professor sNumbersNameaddressS.pNumberP.pNumberpNameaddr 1Dave320FL11MM141FL 2Greg320FL11MM141FL 3Matt320FL22ER201FL 35 SELECT * FROM Student S, Professor P Where S.pNumber = P.pNumber; Student ⋈ Student.pNumber = Professor.pNumber Professor All columns will appear

Example Queries SELECT customer_name FROM borrower B, loan L WHERE B.loan_number = L.loan_number AND L.branch_name = “Perryridge”; DBMS is smart enough !!! (Select first, then joins) 36 Tested first Tested second

Example Queries Find customer names having account balance below 100 or above 10, SELECT customer_name FROM account A, depositor D WHERE A.account_number = D.account_number AND (balance < 100 OR balance >10,000); It is better to write the condition than using Natural Join These two conditions will execute first before the join.

Example Queries 38 For branches that gave loans > 100,000 or hold accounts with balances >50,000, report the branch name along whether it is reported because of a loan or an account SELECT branch_name, ‘Loan’ As Type FROM Loan WHERE amount > 100,000 Union SELECT branch_name, ‘Account’ As Type FROM account WHERE balance > 50,000;

Sorting: ORDER BY clause New optional clause that you can add to the SELECT statement called “ORDER BY” Allows sorting the returned records according to one or more fields SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber, sName; SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber ASC, sName DESC; Default is ascending order 39 -Order first based on the pNumber (ascending) -If many records exist with the same pNumber - order them based on sName (descending)

Sorting: ORDER BY clause SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber, sName; 40 Order By does not change the content of the output relation. It only change the order of tuples Must be the last clause in the SELECT statement.

Sorting: ORDER BY clause sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 Student SELECT * FROM Student WHERE sNumber >= 1 ORDER BY pNumber, sName DESC; sNumbersNameaddresspNumber 2Greg320FL1 1Dave320FL1 3Matt320FL2  (pNumber, sName DESC) (  (sNumber >= 1) (Student)) 41

Duplicate Elimination in SQL New optional keyword “DISTINCT” Added in the SELECT clause SELECT DISTINCT … FROM … … Eliminate any duplicates from the answer 42

Duplicate Elimination: Example SELECT DISTINCT sName, address FROM Student;  (  sName,address (Student))  (  (address) (  (sNumber > 1) (Student))) sNumbersNameaddressprofessor 1Dave320FLMM 2Greg320FLMM 3Matt320FLER Student address 320FL SELECT DISTINCT address FROM Student WHERE sNumber > 1; sNameaddress Dave320FL Greg320FL Matt320FL 43

Always Remember…. Only SELECT and FROM clauses are mandatory All the others are optional You can mix and match the optional ones But if you add a clause, then keep it in its order SELECT address FROM Student ORDER BY sNumber WHERE sNumber > 1; X SELECT address FROM Student ORDER BY sNumber; SELECT DISTINCT address FROM Student WHERE sNumber > 1; SELECT address FROM Student WHERE sNumber > 1 ORDER BY sNumber; 44

Aggregation + GroupBy 45

Possible Aggregations in SQL SELECT COUNT (*) FROM Student; SELECT COUNT (sNumber) FROM Student; SELECT MIN (sNumber) FROM Student; SELECT MAX (sNumber) FROM Student; SELECT SUM (sNumber) FROM Student; SELECT AVG (sNumber) FROM Student; 46

Grouping & Aggregation in SQL New optional clause called “GROUP BY” If the SELECT statement has “WHERE” Then WHERE conditions are evaluated first, then records are grouped SELECT pNumber, COUNT (sName), Min(gpa) FROM Student GROUP BY pNumber; First form groups for each pNumber 47 Then count the records in each group And get the minimum gpa for each group

GROUP BY: Example I sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Jan500MA2 Student SELECT count(*) AS CNT FROM Student;  cnt  count(*) (Student) CNT 4 SELECT pNumber, count(*) AS CNT FROM Student WHERE sNumber > 1 GROUP BY pNumber; pNumberCNT  pNumber,cnt  count(*) (  (sNumber > 1) (Student)) 48

GROUP BY: Example II sNumbersNameaddresspNumber 1Dave320FL1 2Greg320FL1 3Matt320FL2 4Jan500MA2 Student SELECT pNumber,address, count(sName) AS CNT, sum(sNumber) AS SUM FROM Student WHERE sNumber >= 1 GROUP BY pNumber, address; pNumberaddressCNTSUM 1320FL MA14  pNumber,address, CNT  count(sName), SUM  sum(sNumber) (  (sNumber > 1) (Student)) 49