Structured Query Language (SQL) DML

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

SQL DESIGN AND IMPLEMENTATION CONTENT SOURCES: ELAMSARI AND NAVATHE, FUNDAMENTALS OF DATABASE MANAGEMENT SYSTEMSELAMSARI AND NAVATHE, FUNDAMENTALS OF.
Database Design -- Basic SQL
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Introduction to Structured Query Language (SQL)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 SQL: Data Definition, Constraints, and Basic Queries and Updates.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
CSE314 Database Systems Lecture 4 Basic SQL Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson Ed Slide Set.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
Announcements Read 6.7 – 6.10 for Wednesday Homework 6, due Friday 10/29 Project Step 4, due today Research paper –List of sources - due 10/29.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
Lecture6:Data Manipulation in SQL, Simple SQL queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture6 1.
Relational Algebra - Chapter (7th ed )
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Topic 1: Introduction to SQL. SQL stands for Structured Query Language. SQL is a standard computer language for accessing and manipulating databases SQL.
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.
Chapter 8 Part 2 SQL-99 Schema Definition, Constraints, Queries, and Views.
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
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
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Lectures 2&3: Introduction to SQL. Lecture 2: SQL Part I Lecture 2.
Query Processing – Implementing Set Operations and Joins Chap. 19.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Constraints and Views Chap. 3-5 continued (7 th ed. 5-7)
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Structured Query Language (SQL) DDL
slides by: Pavle Morgan & Hui Ma
SQL Query Getting to the data ……..
More SQL: Complex Queries,
Plan for Intro to DB Systems I
Chapter 3 Introduction to SQL
Chapter 3 Introduction to SQL(2)
COMP3017 Advanced Databases
Relational Database Design
Database Systems SQL cont. Relational algebra
Introduction to SQL.
Chapter 4 Basic SQL.
CS580 Advanced Database Topics
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
SQL: Structured Query Language DML- Queries Lecturer: Dr Pavle Mogin
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Chapter 7 Introduction to Structured Query Language (SQL)
CMPT 354: Database System I
CS4222 Principles of Database System
CMPT 354: Database System I
Contents Preface I Introduction Lesson Objectives I-2
CSC 453 Database Systems Lecture
Structured Query Language – The Basics
CSC 453 Database Systems Lecture
CSC 453 Database Systems Lecture
Presentation transcript:

Structured Query Language (SQL) DML SWEN 304 Trimester 2, 2017 1

Outline Reading: Modifying databases: INSERT, DELETE, and UPDATE SQL as Language Single table queries Multiple table queries Nested queries Aggregate functions Reading: Chapter 8 of the textbook PostgreSQL Manual SWEN304 Lect7: SQL(2) 2 2

UNIVERSITY Database UNIVERSITY ={STUDENT(StudId, Lname, Fname, Major), COURSE(CourId, Cname, Points, Dept), GRADES(StudId, CourId, Grade)} IC = {GRADES[Id]  STUDENT[Id], GRADES[Course_id]  COURSE[Course_id]} SWEN304 Lect6: SQL(1) 3 3 3

University Database Schema: STUDENT STUDENT(StudId, Lname, Fname, Major), CREATE TABLE STUDENT ( StudId INT NOT NULL DEFAULT 30000 CONSTRAINT stpk PRIMARY KEY CONSTRAINT StIdRange CHECK (StudId BETWEEN 300000 AND 399999), LName CHAR(15) NOT NULL, FName CHAR(15) NOT NULL, Major CHAR(25) DEFAULT ‘Comp’ ); SWEN304 Lect6: SQL(1) 4 4 4

University Database Schema: COURSE COURSE(CourId, Cname, Points, Dept), CREATE TABLE COURSE ( CourId CHAR(7) CONSTRAINT cspk PRIMARY KEY, CName CHAR(15) NOT NULL, Points INT NOT NULL CONSTRAINT pointschk CHECK (Points >= 0 AND Points <= 50), Dept CHAR(25) ); SWEN304 Lect6: SQL(1) 5 5 5

University Database Schema: GRADES GRADES(StudId, CourId, Grade) GRADES[Id]  STUDENT[Id], GRADES[Course_id]  COURSE[Course_id] CREATE TABLE GRADES ( StudId INT NOT NULL CONSTRAINT Gstidrange CHECK (StudId BETWEEN 300000 and 399999), CONSTRAINT gsri REFERENCES STUDENT ON DELETE CASCADE, CourId CHAR(8) NOT NULL CONSTRAINT gpri REFERENCES COURSE ON DELETE NO ACTION, Grade CHAR(2) CONSTRAINT grd CHECK (Grade IN ('A+', 'A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', NULL)), CONSTRAINT gpk PRIMARY KEY (StudId, CourId ) ); SWEN304 Lect6: SQL(1) 6 6 6

Modify databases Three commands used to modify the database: INSERT, DELETE, and UPDATE

INSERT Command Once a database schema has been created we can populate the database by using the INSERT command Specify the relation name and a list of values for the tuple INSERT INTO 〈table_name〉 [〈attribute_list〉] (VALUES (〈value_list〉) | SELECT …) SWEN304 Lect7: SQL(2) 8

INSERT Command Example: INSERT INTO STUDENT VALUES (111111, 'Bole', 'Ann', Math); Note: The values in VALUES have to appear in the same order as the attributes in the corresponding CREATE TABLE command, INSERT INTO STUDENT (FName, LName, StudId ) VALUES('Ann', 'Bole', 111111); Note: Useful when values of attributes declared as NULL, or having DEFAULT value are missing Not allowed if the missing attribute is declared NOT NULL SWEN304 Lect8: SQL(3) 9 9

INSERT Command (continued) A form of INSERT command that is suitable for creation of temporary tables CREATE TABLE StudentInfo ( StudId INT PRIMARY KEY, LName CHAR(15) NOT NULL, NoOfCourses INT); INSERT INTO StudentInfo SELECT s.StudId, LName, COUNT(*) AS NoOfCourses FROM Student s, Grades g WHERE s.StudId = g.StudId GROUP BY StudId, LName ; SWEN304 Lect8: SQL(3) 10 10

UPDATE Command Modify attribute values of one or more selected tuples UPDATE〈table_name〉 SET 〈attribute_name〉=〈value_expression〉 {, 〈attribute_name〉=〈value_expression〉} [WHERE 〈condition〉] Example: UPDATE GRADES SET Grade = 'A+' WHERE CourId = 'C302'; SWEN304 Lect8: SQL(3) 11 11

DELETE Command Removes tuples from a relation Includes a WHERE clause to select the tuples to be deleted DELETE FROM 〈table_name〉 [WHERE 〈condition〉] Examples: DELETE FROM STUDENT WHERE FName = 'Susan'; WHERE StudId IN (SELECT s.StudId FROM STUDENT s, GRADES g WHERE s.StudId = g.StudId AND CourId = 'C302'); DELETE FROM STUDENT ; SWEN304 Lect8: SQL(3) 12 12

DROP vs DELETE DELETE statement performs conditional based deletion, whereas DROP command deletes entire records in the table DELETE statement removes only the rows in the table and it preserves the table structure as same whereas DROP command removes all the data in the table and the table structure DELETE operation can be rolled back and it is not auto committed, while DROP operation cannot be rolled back in any way as it is an auto committed statement DROP is a DDL statement while DELETE is a DML statement SWEN304 Lect7: SQL(2) 13

Queries in SQL SELECT is the basic SQL statement for retrieving data from a database SELECT [ DISTINCT ] 〈attribute_list〉 FROM 〈table_list〉 [ WHERE 〈condition〉 ] 〈attribute_list〉= attributes whose values will be retrieved by query e.g. FName, LName, CName, Grade use “∗” to denote all table attributes SWEN304 Lect7: SQL(2) 14 14

Queries in SQL 〈table_list〉: refer to relations needed to process the query tables containing attributes from〈attribute_list〉 must be included e.g., STUDENT, CORUSE, GRADES 〈condition〉 is a Boolean expression defining the properties of the tuples to be retrieved, e.g., StudId = 007007 join conditions (optional clause) e.g., STUDENT.StudId = GRADES.StudId SWEN304 Lect7: SQL(2) 15 15

Conditional Expression (Reference) Conditional expression of the WHERE clause can be any plausible combination of the following: [(A  a] [A  B ] [A IS [ NOT ] NULL] [A [ NOT ] BETWEEN a1 AND a2 ] [A [ NOT ] LIKE 〈pattern〉 ] (string matching ) [A [ NOT ] SIMILAR TO 〈regular expression〉 ] [A [ NOT ] IN 〈value_list〉] [A  ANY 〈value_list〉] [A  SOME 〈value_list〉] [A  ALL 〈value_list〉] [(EXIST | NOT EXIST) 〈sub query〉] where { =, <, <=, >, >=, < > }, A and B attributes or function of attributes, ai dom(A ), i = 1,… SWEN304 Lect7: SQL(2) 16 16

Queries in SQL SQL considers a relation/table to be a multiset (or bag) of tuples, not a set ⇒ allows duplicates! SQL relations can be constrained to be sets by specifying PRIMARY KEY or UNIQUE attributes SQL does not automatically eliminate duplicate tuples in query results Use the keyword DISTINCT in the SELECT clause Only distinct tuples should remain in the result SWEN304 Lect7: SQL(2) 17 17

Suppose for each student only pass grades are recorded in the database The University Database Suppose for each student only pass grades are recorded in the database STUDENT LName FName StudId Major Smith Susan 131313 Comp Bond James 007007 Math 555555 Cecil John 010101 GRADES StudId CourId Grade 007007 C302 A+ 555555 D C301 A M214 131313 C201 B- C 010101 COURSE PName CourId Points Dept DB Sys C302 15 Comp SofEng C301 DisMat M214 22 Math Pr&Sys C201 SWEN304 Lect7: SQL(2) 18 18

Single Table Queries Retrieve the first and last names of Comp students SELECT FName, LName FROM STUDENT WHERE Major = 'Comp'; Find all different grades SELECT DISTINCT Grade FROM GRADES ; FName LNam e Susan Smith Grade A+ A B- C SWEN304 Lect7: SQL(2) 19 19

Substring Comparisons Can extract part of a string with the function substring(〈string〉,〈start pos〉,〈length〉) Can match to SQL patterns: 〈string〉 LIKE 〈pattern〉 '%' to replace an arbitrary number of characters, and '_' to replace exactly one character e.g., Retrieve course names of all 300 level courses have '3' as the second character in CourId SELECT CName FROM COURSE WHERE CourId LIKE '_3%'; or SELECT CName FROM COURSE WHERE substring(CourId, 2,1) = ’3’; PNam e DB Sys SofEn g SWEN304 Lect7: SQL(2) 20 20

Arithmetic Operations, Sorting SQL provides capability to perform four basic arithmetic operations (+, -, *, / ) that can be applied to numeric attributes and constants only SELECT 2 + 2; Sorting of the query result tuples is done using ORDER BY {〈attribute_name〉[(ASC|DESC)],…} clause after the WHERE clause (ASC is default) SELECT * FROM GRADES ORDER BY StudId ASC, CourId DESC; SWEN304 Lect7: SQL(2) 21 21

SELECT CourId AS CourseId Qualification and Aliasing Attributes in different relation schemas can have the same names. How do we prevent ambiguity? In the SELECT clause, we prefix attributes by table name: SELECT STUDENT.StudId … To change name of an attribute in the result, alias the attribute name using AS : SELECT CourId AS CourseId In the FROM clause, specify a tuple variable from the table: …FROM COURSE c, GRADES g, STUDENT s In the WHERE clause, prefix an attribute by the tuple variable: WHERE c.CourId = g.CourId SWEN304 Lect7: SQL(2) 22 22

Multiple Table Queries and Joins To retrieve data from more than one table, we need a new operation: JOIN There are different joins: INNER (theta join, equi-join, natural join) OUTER (left, right, full) Most often, we use the equi-join Each join operation is based on concatenating those tuples from two relations, which have such join attribute values, which satisfy the join condition An equi-join concatenates tuples with equal join attribute values An equi-join is most frequently based on a (FK, PK) pair SWEN304 Lect7: SQL(2) 23 23

SELECT * FROM r1, r2 WHERE r1.B = r2.B ; A JOIN Example SELECT * FROM r1, r2 WHERE r1.B = r2.B ; Join Condition r1 r2 r1 EQUI-JOIN r2 A B C 1 b1 c1 2 b2 3 b3 4 b4 c2 5  If there is no join condition what is the result? SWEN304 Lect7: SQL(2) 24 24

Multiple Table Queries Retrieve course names with grades, and the surname for student James SELECT c.CName, Grade, LName AS Surname, FROM STUDENT s, GRADES g, COURSE c WHERE FName = 'James' AND s.StudId = g.StudId AND c.CourId = g.CourId ; Conditional expression is blue, Join condition is red CName Grade Surname DB Sys A+ Bond SofEng A DisMat Pr&Sys SWEN304 Lect7: SQL(2) 25 25

Nested Queries Some queries require comparing a tuple to a collection of tuples (e.g., students doing courses that have more than 100 students) This task can be accomplished by embedding a SQL query into WHERE clause of another query The embedded query is called nested query, The query containing the nested query is called outer query The comparison is made by using IN,  ANY,  SOME, and  ALL operators, where { =, <, <=, >=, >, < > } Note: IN  =ANY and IN  =SOME SWEN304 Lect7: SQL(2) 26 26

Example Nested Query Retrieve first names of students that passed M214 SELECT FName FROM STUDENT s WHERE s.StudId IN (SELECT StudId FROM GRADES WHERE CourId = 'M214' AND Grade IS NOT NULL); A nested query defined by using IN (or =ANY) operator can be expressed as a single block query SELECT FName FROM STUDENT s, GRADES g WHERE s.StudId = g.StudId AND g.CourId = 'M214' AND g.Grade IS NOT NULL; FName James SWEN304 Lect7: SQL(2) 27 27

Correlated Nested Queries Let the variable s contain the current tuple of the outer query If the nested query doesn’t refer to s : The nested query computes the same result for each tuple in s The outer query and the nested query are said to be uncorrelated If a condition in the WHERE clause of the nested query refers to some attributes of a relation declared in the outer query, the two queries are said to be correlated Have to compute the inner query for each tuple considered by the outer query Correlated nested queries consume more computer time than uncorrelated ones SWEN304 Lect7: SQL(2) 28 28

Correlated Nested Query Retrieve id's and surnames of those students that passed at least one course SELECT s.StudId, FName FROM Student s WHERE s.StudId IN (SELECT StudId FROM GRADES WHERE s.StudId = StudId AND Grade IS NOT NULL); Evaluation of the query: when s.Stud Id = 131313, ⇒ result of the nested query is StudId = {131313}, ⇒ (131313, Susan) is in the final result When s.Stud Id = 010101, ⇒ result of the nested query is StudId = { }, ⇒ (010101, John) is NOT in the final result SWEN304 Lect7: SQL(2) 29 29

Correlated Nested Query Again, the nested query can be expressed as a single block query: SELECT DISTINCT s.StudId, s.LName FROM STUDENT s, Grades g WHERE s.StudId = g.StudId AND Grade IS NOT NULL; Have to be careful of duplicates! This computes an Equi-Join of the relations SWEN304 Lect7: SQL(2) 30 30

EXISTS and NOT EXISTS Retrieve Id‘s and surnames of students who passed at least one course: SELECT s.StudId, s.LName FROM STUDENT s WHERE EXISTS (SELECT * FROM GRADES WHERE s.StudId = StudId AND Grade IS NOT NULL); Retrieve Id's and surnames of students who didn't pass any course: SELECT s.StudId, s.LName FROM STUDENT s WHERE NOT EXISTS (SELECT * FROM GRADES WHERE s.StudId = StudId AND Grade IS NOT NULL ); SWEN304 Lect7: SQL(2) 31 31

Summary SQL as DML: INSERT, UPDATE and DELETE SQL as a query language Basic Query structure Queries against a single table Queries against multiple tables Substring comparisons Arithmetic operations Sorting Nested queries (outer and inner-nested queries) Correlated nested queries SWEN304 Lect7: SQL(2) 32 32

Next lecture SQL advanced options: SQL set operations Joined tables, Aggregate functions Grouping Having SQL set operations SWEN304 Lect7: SQL(2) 33 33