TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS 31.03.2014 (Muscat, Oman)

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

SQL: The Query Language Part 1 R &G - Chapter 5 Life is just a bowl of queries. -Anon (not Forrest Gump)
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Basic SQL Introduction Presented by: Madhuri Bhogadi.
1 Advanced SQL Queries. 2 Example Tables Used Reserves sidbidday /10/04 11/12/04 Sailors sidsnameratingage Dustin Lubber Rusty.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
1 Query-by-Example (QBE). 2 v A “GUI” for expressing queries. –Based on the Domain Relational Calulus (DRC)! –Actually invented before GUIs. –Very convenient.
COMP 3715 Spring 05. Working with data in a DBMS Any database system must allow user to  Define data Relations Attributes Constraints  Manipulate data.
CS 166: Database Management Systems
Database Management Systems 3ed, Online chapter, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Online Chapter Example is the school of mankind,
SQL.
5/15/2015Lecture 31 CS 222 Database Management System Spring Lecture 3 Korra Sathya Babu Department of Computer Science NIT Rourkela.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5.
CS 405G: Introduction to Database Systems
Database Management Systems, R. Ramakrishnan and J. Gehrke1 Query-by-Example (QBE) Chapter 6 Example is the school of mankind, and they will learn at no.
SQL (2).
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
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)
Introduction to Structured Query Language (SQL)
RELATIONAL ALGEBRA (III) Prof. Sin-Min LEE Department of Computer Science.
Database Systems More SQL Database Design -- More SQL1.
Introduction to Structured Query Language (SQL)
RELATIONAL ALGEBRA (II) Prof. Sin-Min LEE Department of Computer Science.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Introduction to SQL J.-S. Chou Assistant Professor.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 3 Introduction to SQL Yonsei University 1 st Semester, 2015 Sanghyun Park.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
CSc-340 2b1 Introduction to SQL Chapter 3 [2 of 2] Null Values Aggregate Functions Nested Subqueries Modification of the Database.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
CS 370 Database Systems Lecture 12 Introduction to SQL.
Oracle Database Administration Lecture 2 SQL language.
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
SQL Examples CS3754 Class Note 11 CS3754 Class Note 11, John Shieh,
ICS 321 Fall 2009 SQL: Queries, Constraints, Triggers Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 9/8/20091Lipyeow.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
ICS 321 Fall 2011 The Relational Model of Data (i) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 8/29/20111Lipyeow.
1 Database Systems ( 資料庫系統 ) October 24, 2005 Lecture #5.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
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.
SQL SeQueL -Structured Query Language SQL SQL better support for Algebraic operations SQL Post-Relational row and column types,
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
ICS 321 Spring 2011 The Database Language SQL (iii) Asst. Prof. Lipyeow Lim Information & Computer Science Department University of Hawaii at Manoa 3/14/20111Lipyeow.
2/16/2016Lecture 31 CS 222 Database Management System Spring Lecture 3 b Korra Sathya Babu Department of Computer Science NIT Rourkela.
SQL: The Query Language Part 1 R &G - Chapter 5 The important thing is not to stop questioning. Albert Einstein.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
1 CS122A: Introduction to Data Management Lecture #7 Relational Algebra I Instructor: Chen Li.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
Relational Algebra Database Management Systems, 3rd ed., Ramakrishnan and Gehrke, Chapter 4.
SQL Query Getting to the data ……..
Chapter 3 Introduction to SQL
COP Introduction to Database Structures
01/31/11 SQL Examples Edited by John Shieh CS3754 Classnote #10.
Introduction to SQL.
Chapter 3 Introduction to SQL(3)
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
Database Applications (15-415) SQL-Part II Lecture 9, February 04, 2018 Mohammad Hammoud.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CS4222 Principles of Database System
SQL: Structured Query Language
Contents Preface I Introduction Lesson Objectives I-2
Presentation transcript:

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)

TURKISH STATISTICAL INSTITUTE 2 /34 OUTLINE Definition of SQL Main Categories Of Sql Basic Sql Commands Nested Queries and Subqueries Set Operators (minus, in, not in, all, some, intersect, exists) Aggregate Functions Join Operations Using View and Matearilized View Sequences Triggers And The Purpose Of Triggers

TURKISH STATISTICAL INSTITUTE 3 /34 SQL DEFINITION SQL (Structured Query Language) is a special-purpose programming language designed for managing data held in a RDBMS First developed in the early 1970s at IBM Commercially released by Relational Software Inc. Became a standard of the American National Standards Institute (ANSI) in 1986 International Organization for Standards (ISO) in 1987

TURKISH STATISTICAL INSTITUTE 4 /34 MAIN CATEGORIES

TURKISH STATISTICAL INSTITUTE 5 /34 Sql Commands Overview CREATE TABLE (, … ) INSERT INTO ( ) VALUES ( ) DELETE FROM WHERE UPDATE SET = WHERE SELECT (distinct is usable here) FROM WHERE

TURKISH STATISTICAL INSTITUTE 6 /34 Some Examples Sailors sidsnameratingage 22Dustin Brutus Lubber Andy Rusty Horatio Zorba Horatio Art Bob363.5 Reserves sidbidday Boats bidbnamecolor 101Interlakeblue 102Interlakered 103Clippergreen 104Marinered *Live Demo : install and use a DBMS for SQL s

TURKISH STATISTICAL INSTITUTE 7 /34 Example : select distinct sname, age from sailors Q1 : Find all sailors with a rating above 7. Q2 : Find the sailors that rating>7 Q3 : Find the sailors that whose name starts with ‘B’ letter Q4 : Find the names of the sailors who reserved at least one boat Examples of Basic SQL Queries

TURKISH STATISTICAL INSTITUTE 8 /34 Nested Queries and Subqueries A subquery is a select-from-where expression that is nested within another query. Example Query: Find courses offered in Fall 2009 and in Spring 2010 select distinct course_id from section where semester = ’Fall’ and year= 2009 and course_id in (select course_id from section where semester = ’Spring’ and year= 2010);

TURKISH STATISTICAL INSTITUTE 9 /34 Using Set Operators (MINUS, NOT IN, NOT EXISTS, IN, EXISTS, INTERSECT) Syntax : Query1 Query2 Example1: (difference) Select * from staff_1 Minus Select * from staff2; Select * from staff_1 where staff_number not in (select staff_number from staff_2); Select * from staff_1 a where not exists (select * staff_2 b where a.sid=b.sid); Example2: (intersect) Select * from staff_1 intersect Select * from staff2; Select * from staff_1 where staff_number in (select staff_number from staff_2); Select * from staff_1 a where exists (select * staff_2 b where a.sid=b.sid);

TURKISH STATISTICAL INSTITUTE 10 /34 Exercises: Q5: Find the sailors that rating of the one equals 3 times of the other (hint: result is Art, Bob, Horatio) Q6:Find the names of sailors who have red or green boat Q7: Find the names of sailors who have reserved a red and a green boat Q8: Find the sname of sailors who have reserved red boats but not green boats *Live Demo

TURKISH STATISTICAL INSTITUTE 11 /34 Answers: Q7 Answer -1 ( It is a complex query ) Select s.sname from sailors s, reserves r 1, boats b1, r 2, boats b2 where s.sid = r1.sid and r1.bid=b1.bid and s.sid = r2.sid and r2.bid=b2.bid and b1.color=‘red’ and b2.color=‘green’; Q7 Answer -2 – Using Intersect operation (easily to understand, write) Select s.sname from sailors s, reserves r, boats b where s.sid = r.sid and r.bid=b.bid and b.color=‘red’ INTERSECT Select s2.sname from sailors s2, reserves r 2, boats b2 where s2.sid = r2.sid and r2.bid=b2.bid and b2.color=‘red’ ;

TURKISH STATISTICAL INSTITUTE 12 /34 Q8 Answer: Find the sname of sailors who have reserved red boats but not green boats. Select s.sname from sailors s, reserves r, boats b where s.sid = r.sid and r.bid=b.bid and b.color=‘red’ MINUS Select s2.sname from sailors s2, reserves r2, boats b2 where s2.sid = r2.sid and r2.bid=b2.bid and b2.color=‘green’;

TURKISH STATISTICAL INSTITUTE 13 /34 ALL, SOME,ANY They are used to compare two datasets Example: Find names of instructors with salary greater than that of some (at least one) instructor in the Biology department. Answer-1 : select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = ’Biology’;

TURKISH STATISTICAL INSTITUTE 14 /34 Same query using some clause select name from instructor where salary > some (select salary from instructor where dept_name = ’Biology’); Same query using any clause select name from instructor where salary > any (select salary from instructor where dept_name = ’Biology’);

TURKISH STATISTICAL INSTITUTE 15 /34 Example Query for All Clause Find the names of all instructors whose salary is greater than the salary of all instructors in the Biology department. select name from instructor where salary > all (select salary from instructor where dept_name = ’Biology’);

TURKISH STATISTICAL INSTITUTE 16 /34 UNION vs UNION ALL They concetane the result of two different SQLs. They differ in the way they handle duplicates. Selected columns need to be of the same data type There is a performance hit when using UNION vs UNION ALL,

TURKISH STATISTICAL INSTITUTE 17 /34 AGGREGATE FUNCTIONS avg: average value min: minimum value max: maximum value sum: sum of values count: number of values Find the average salary of instructors in the Computer Science department : select avg (salary) from instructor where dept_name= ’Comp. Sci.’; Find the total number of instructors who teach a course in the Spring 2010 semester: select count (distinct ID) from teaches where semester = ’Spring’ and year = 2010;

TURKISH STATISTICAL INSTITUTE 18 /34..GROUP BY Attributes in select clause outside of aggregate functions must appear in group by list /* erroneous query */ select city, student_name, count(*), avg(average_note) note from student group by city

TURKISH STATISTICAL INSTITUTE 19 /34 SELECT List the columns (and expressions) that should be returned from the query FROM Indicate the table(s) or view(s) from which data will be obtained WHERE Indicate the conditions under which a row will be included in the result GROUP BY Indicate columns to group the results HAVING Indicate the conditions under which a group will be included ORDER BY Sorts the result according to specified columns Used for queries on single or multiple tables Clauses of the SELECT statement:

TURKISH STATISTICAL INSTITUTE 20 /34 AGGREGATE FUNCTIONS EXERCISES *Live Demo : Exercise: Using STUDENT table STUDENT(student_name, lesson_name, note) Find: a) The count of lessons for each student b) The average note, and maximum note of each student c) Find the students that have more than 1 record for the same lesson

TURKISH STATISTICAL INSTITUTE 21 /34 Solutions of the Exercise: select student_name, max(note), avg(note), count(lesson_name) from student group by student_name; select student_name, lesson_name, count(*) from student group by student_name, lesson_name having count(*) > 1;

TURKISH STATISTICAL INSTITUTE 22 /34 JOIN OPERATIONS Join operations take two relations and return as a result another relation. A join operation is a Cartesian product which requires that tuples in the two relations match (under some condition). It also specifies the attributes that are present in the result of the join The join operations are typically used as subquery expressions in the from clause

TURKISH STATISTICAL INSTITUTE 23 /34 JOIN EXAMPLES Course : Department:

TURKISH STATISTICAL INSTITUTE 24 /34 select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1, department t2 where t1.dept_id = t2.dept_id; JOIN EXAMPLES (Cont’d)

TURKISH STATISTICAL INSTITUTE 25 /34 JOIN EXAMPLES using Right Outer Join select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1, department t2 where t1.dept_id(+) = t2.dept_id; select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1 right outer join department t2 on t1.dept_id = t2.dept_id;

TURKISH STATISTICAL INSTITUTE 26 /34 JOIN EXAMPLES using Left Outer Join select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1, department t2 where t1.dept_id = t2.dept_id(+); select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1 left outer join department t2 on t1.dept_id = t2.dept_id;

TURKISH STATISTICAL INSTITUTE 27 /34 JOIN EXAMPLES using Full Outer Join select t1.course_id, t1.title, t1.credits, t2.* from COURSE t1 full outer join department t2 on t1.dept_id = t2.dept_id;

TURKISH STATISTICAL INSTITUTE 28 /34 Some Easy but useful SQL statements Create table t1 as select * from t2; Select * from t1 where rownum < 100; Deleting duplicate records example: for table Student(student_name, lesson_name, note) delete from STUDENT A1 where exists (Select 'x' from STUDENT A2 where A1.STUDENT_NAME = A2.STUDENT_NAME and A1.LESSON_NAME = A2.LESSON_NAME and A1.NOTE = A2.NOTE and A1.ROWID > A2.ROWID);

TURKISH STATISTICAL INSTITUTE 29 /34 Views and Materialized Views A view is a result set of a query By using views, showing only relevant data to the users is provided. Create view statement : create view as Materializing a view: create a physical table containing all the tuples in the result of the query defining the view (refresh is required) create materialize view as

TURKISH STATISTICAL INSTITUTE 30 /34 SEQUENCES A sequence is a database object that generates numbers in sequential order. Mostly used to generate primary key for a table Example: To create the sequence: CREATE SEQUENCE customer_seq INCREMENT BY 1 START WITH 100 To use the sequence to enter a record into the database: INSERT INTO customer (cust_num, name, address) VALUES (customer_seq.NEXTVAL, 'John Doe', '123 Main St.‘);

TURKISH STATISTICAL INSTITUTE 31 /34 TRIGGERS Trigger is a procedure that is automatically run by DBMS in response to specified changes to the database, and performs desired events Trigger has three parts : Event, Condition, Action Trigger Types Are : DML triggers for Insert, Update, Delete DDL triggers (instead of) for Create, Alter, Drop, etc.. Triggers can’t be defined for Select statement Transactions statements (commit, savepoint,rollback) can not be used in Triggers

TURKISH STATISTICAL INSTITUTE 32 /34 create or replace trıgger delete_forbidden before drop on database begın raıse_applıcatıon_error ( ,’dropping table is forbidden’); end; create or replace trigger trigger_1 before insert on tbl1 referencıng new as new old as old for each row begin :new.referenced_date := sysdate; end tr_1; TRIGGER EXAMPLES

TURKISH STATISTICAL INSTITUTE 33 /34 SUMMARY Basic SQL query has a Select, From,Where Use Distinct to avoid duplicates at queries SQL provides set operations: Union, Intersect, Minus, Queries that have subqueries are called Nested Queries. In, Exists, Unique, Any, All, Some is used for Nested Queries Aggregators operators are Count, Sum, Average, Max,Min Group by and Having SQL provides using of Sequences and Triggers Key Points: Be careful about recursive triggers ! Think about check constraints instead of triggers for database consistency.