1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.

Slides:



Advertisements
Similar presentations
CSC271 Database Systems Lecture # 11.
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
Your Logo Fundamentals of Database Systems Fourth Edition El Masri & Navathe Instructor: Mr. Ahmed Al Astal Chapter 8 (Cont.) SQL-99: Schema Definition,
Database technology Lecture 2: Relational databases and SQL
FEN More about SELECT, Nested selects GROUP BY, HAVING, ORDER BY Other joins Aggregate functions Views More about SQL.
Data Warehousing/Mining 1 Data Warehousing/Mining Comp 150 Aggregation in SQL (not in book) Instructor: Dan Hebert.
SQL SQL (Structured Query Language) is used to define, query, and modify relational databases Every relational database system understands SQL SQL is standard:
Nov 24, 2003Murali Mani SQL B term 2004: lecture 12.
Database Systems More SQL Database Design -- More SQL1.
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.
Al-Imam University Girls Education Center Collage of Computer Science 1 ST Semester, 1432/1433H Chapter 8 Part 4 SQL-99 Schema Definition, Constraints,
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 )
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Onsdag The concepts in a relation data model SQL DDL DML.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Oracle DML Dr. Bernard Chen Ph.D. University of Central Arkansas.
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
 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.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.
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.
莊裕澤資料庫基本概念 1 Yuh-Jzer Joung 莊 裕 澤 Dept. of Information Management National Taiwan University February, 2002 資料庫管理與資訊科技.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
Structured Query Language Introduction. Basic Select SELECT lname, fname, phone FROM employees; Employees Table LNAMEFNAMEPHONE JonesMark SmithSara
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
Structured Query Language
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
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.
1/18/00CSE 711 data mining1 What is SQL? Query language for structural databases (esp. RDB) Structured Query Language Originated from Sequel 2 by Chamberlin.
Slide 6- 1 Additional Relational Operations Aggregate Functions and Grouping A type of request that cannot be expressed in the basic relational algebra.
1 CS 430 Database Theory Winter 2005 Lecture 5: Relational Algebra.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 The Relational Algebra and Relational Calculus.
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.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
Query Processing – Implementing Set Operations and Joins Chap. 19.
1 COMP 1100 Basic SQL David J. Stucki. Outline SQL Overview Retrievals Schema creation Table creation Constraints Inserts Updates 2.
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.
DQL Statements Lab - 3 COMP 353 Summer
More SQL: Complex Queries,
CS3220 Web and Internet Programming More SQL
CS580 Advanced Database Topics
Chapter # 6 The Relational Algebra and Calculus
Chapter 4 Basic SQL.
6/22/2018.
Retrieval Queries in SQL(DML)
376a. Database Design Dept. of Computer Science Vassar College
11/9/2018.
Company Requirements.
Session - 6 Sequence - 2 SQL: The Structured Query Language:
More SQL: Complex Queries, Triggers, Views, and Schema Modification
CS4222 Principles of Database System
SQL-99: Schema Definition, Constraints, and Queries and Views
CSC 453 Database Systems Lecture
SQL Grouping, Ordering & Arithmetics Presented by: Dr. Samir Tartir
SQL: Set Operations & Nested Queries. Presented by: Dr. Samir Tartir
Presentation transcript:

1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT

2 SELECT One statement for retrieving data: SELECT FROM WHERE ; Approximately:   (  ( ))  {t. | (t) AND }  Difference: SELECT does not eliminate duplicate rows

3 SELECT Multiple Tables Can have multiple tables in the FROM clause Retrieve names and address of Research department employees  SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARMENT WHERE DNAME = ‘Research’ AND DEPARTMENT.DNUMBER = EMPLOYEE.DNUMBER;

4 Notes:  SQL is officially case insensitive  However, there are situations where it makes a difference E.g. MySQL stores MyISAM tables in individual files making table names case sensitive Attribute names don’t require qualification if they are unique (among all the tables that are part of the query)

5 SELECT Qualifying Attribute Names We can qualify attribute names  Tablename.attribute Assume EMPLOYEE and DEPARTMENT both have NAME and DNUMBER attributes:  SELECT FNAME, EMPLOYEE.NAME, ADDRESS FROM EMPLOYEE, DEPARMENT WHERE DEPARTMENT.NAME = ‘Research’ AND DEPARTMENT.DNUMBER = EMPLOYEE.DNUMBER;

6 SELECT Qualifying Attribute Names (2) [AS] :  SELECT FNAME, E.NAME, ADDRESS FROM EMPLOYEE AS E, DEPARMENT AS D WHERE D.NAME = ‘Research’ AND D.NUMBER = E.NUMBER; Also can refer to same table more than once:  SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME FROM EMPLOYEE E, EMPLOYEE S WHERE E.SUPERSSN = S.SSN;

7 SELECT Where Clause is Optional SELECT FNAME, LNAME, SSN FROM EMPLOYEE; Including multiple tables:  SELECT FNAME, LNAME, DNAME FROM EMPLOYEE, DEPARTMENT  Result is a Cartesian Product (all combinations of one row from each table)

8 SELECT * Can use * in place of attributes: SELECT * FROM EMPLOYEE;  Attributes are listed in order of definition Can also qualify * with a table name: SELECT EMPLOYEE.*, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER; Style: Never use * in a program  Always ask for attributes in order expected by program

9 SELECT DISTINCT What is we want duplicates eliminated  That is, when we want a set of results  Usually costs some time to eliminate duplicates  In many cases there are no duplicates, e.g. when we select the key of a table  Usually don’t want to eliminate duplicates when using aggregate functions (e.g. SUM) Do SELECT DISTINCT:  SELECT DISTINCT SALARY FROM EMPLOYEE; Note: ALL is opposite of DISTINCT

10 SELECT Ordering the result Use an ORDER BY clause E.g. SELECT DNAME, LNAME, FNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER ORDER BY DNAME, LNAME, FNAME;

11 SELECT Ordering the result (2) By default ORDER BY sorts in ascending order, if you want the opposite use ASC and DESC:  SELECT DNAME, LNAME, FNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER ORDER BY DNAME DESC, LNAME ASC, FNAME ASC;

12 Operations There is a plethora of operations available. Some examples:  Arithmetic: +, -, *, /  Comparison: or !=, >=, >  Pattern Matching: LIKE Operations can appear as part of a condition and as part of attributes to be selected

13 Operations Examples SELECT FNAME, LNAME, 1.1 * SALARY FROM EMPLOYEE; SELECT FNAME, LNAME FROM EMPLOYEE E, EMPLOYEE S WHERE E.MGRSSN = S.SSN AND E.SALARY > 1.5 * S.SALARY; SELECT FNAME, LNAME, 1.1 * SALARY AS NEW_SALARY FROM EMPLOYEE;  Renames the result column (when it makes a difference)

14 Pattern Matching Field LIKE Pattern, Field NOT LIKE Pattern Patterns  % matches zero or more characters like Regular Expression *  _ matches one character like Regular Expression.  Use \ to escape _ and % Example:  ADDRESS LIKE ‘%Houston%’  Houston is anywhere in the address string (would include a street named Houston)

15 Note on Pattern Matching Consider performance when using pattern matching.  SELECT FNAME, LNAME FROM EMPLOYEE WHERE ADDRESS LIKE ‘%Houston%’;  This would require a full table scan of the EMPLOYEE table

16 Three Valued Logic NULLs have multiple meanings All comparison involving a NULL yield NULL or UNKNOWN  Even NULL = NULL, all NULLs are considered distinct AND, OR, NOT  FALSE AND UNKNOWN is FALSE  TRUE OR UNKNOWN is TRUE  NOT UNKNOWN is UNKNOWN

17 More Three Valued Logic Can explicitly test for NULL with IS NULL, IS NOT NULL Example: SELECT FNAME, LNAME FROM EMPLOYEE WHERE SUPERSSN IS NULL;

18 JOINing Tables SQL incorporate notion of JOINed tables  Can specify a join in the FROM clause Example:  SELECT FNAME, LNAME, ADDRESS FROM (EMPLOYEE JOIN DEPARMENT ON DNO = DNUMBER) WHERE DNAME = ‘Research’;

19 More JOINing Tables NATURAL JOIN  SELECT DNAME, DLOCATION FROM (DEPARTMENT NATURAL JOIN DEPT_LOCATIONS); OUTER JOINS  SELECT E.LNAME AS ENAME, S.LNAME AS SNAME FROM (EMPLOYEE E LEFT OUTER JOIN EMPLOYEE S ON E.SUPERSSN = S.SSN);

20 More JOINing Tables Kinds of JOINs  [INNER] JOIN Normal Join  CROSS JOIN Cross Join is a cartesian product (no join condition)  LEFT [OUTER] JOIN  RIGHT [OUTER] JOIN Left and Right Outer Joins  FULL [OUTER] JOIN Two sided outer join Not supported in MySQL

21 Aggregate Functions Aggregate Functions:  COUNT, SUM, MAX, MIN, AVG, and some more  SUM, AVG work on numeric values  MAX, MIN work on values with a “total order”  COUNT returns number of tuples or values Simple example: SELECT AVG(SALARY), MAX(SALARY) FROM EMPLOYEE; Note: Can include WHERE Clause and Joins SELECT AVG(SALARY), MAX(SALARY) FROM (EMPLOYEE JOIN DEPARTMENT ON DNO=DNUMBER) WHERE DNAME = ‘Research’;

22 COUNT() COUNT counts the number of tuples or values COUNT(*) will count the number of tuples in the query COUNT(SALARY) will count the number of tuples with a non-null SALARY COUNT(DISTINCT SALARY) will count the number of DISTINCT values for SALARY

23 GROUP BY Problem with simple aggregates: Can’t return more than one row  Relational Algebra: Group rows together and compute aggregate function over the group (“script F” operator) SQL: GROUP BY CLAUSE Simple example: SELECT DNO, COUNT(*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO;

24 MORE GROUP BY Restriction (Queries with GROUP BY): All attributes used in the SELECT clause (includes used in expressions) must be either:  Named in the GROUP BY clause  Or, Used in an Aggregate function Illegal Example (should be):  SELECT DNO, SALARY FROM EMPLOYEE GROUP BY DNO; Legal Example:  SELECT DNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DNO;

25 GROUP BY and NULLs If some of the rows being grouped have null attributes for a GROUPing attribute a separate group is created for those rows with that attribute being NULL Example:  Get number of employees supervised by each supervisor: SELECT SUPERSSN, COUNT(*) FROM EMPLOYEE GROUP BY SUPERSSN;

26 HAVING HAVING provides a condition that is tested after the rows are grouped:  Example: HAVING COUNT(*) > 2 (more than two tuples in the group). EXAMPLE: SELECT SUPERSSN, MAX(SALARY) FROM EMPLOYEE GROUP BY SUPERSSN HAVING COUNT(*) >= 2;

27 MORE GROUP BY and HAVING Semantics  The rest of the query (without GROUP BY and HAVING clauses) is processed first, resulting in a table of tuples  That table is then grouped according to the GROUP BY and Aggregate functions are computed as needed for the SELECT and HAVING clauses  Any HAVING clause is applied  The appropriate attributes from the resulting tuples are returned as the result

28 Nested Queries (Need MySQL 4.1 or later) Mini-example:  SELECT DISTINCT PNUMBER FROM PROJECT WHERE PNUMBER IN (SELECT PNUMBER FROM … WHERE … ); In general: Anything that can be done with a nested query can be done without

29 More Nested Queries IN can work with tuples: Example:  Find all employees who work the same (project, hours) combination on some project that SSN ‘ ’ works on. SELECT DISTINCT ESSN FROM WORKS_ON WHERE (PNO, HOURS) IN (SELECT PNO, HOURS FROM WORKS_ON WHERE SSN = ‘ ’);

30 More Nested Queries IN is the same as = ANY You can use ANY and ALL with any comparison (>, =, etc.) operator Example:  Find all employees whose salary is greater than all the employees in department 5  SELECT LNAME, FNAME FROM EMPLOYEE WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE WHERE DNO = 5);

31 Correlated Nested Queries Refers to queries where a nested query refers to attributes in an outer query Example:  Find the name of all employees who have a dependent with the same first name and sex  SELECT E.FNAME, E.LNAME FROM EMPLOYEE E WHERE E.SSN IN (SELECT ESSN FROM DEPENDENT E.FNAME = DEPENDENT_NAME AND E.SEX = SEX);

32 EXISTS and NOT EXISTS EXISTS and NOT EXISTS are predicates that can be applied to a subquery Example:  Find all employees having dependents  SELECT FNAME, LNAME FROM EMPLOYEE WHERE NOT EXISTS (SELECT * FROM DEPENDENT WHERE SSN = ESSN);

33 UNION You can get the result of more than one query combined into a single result: SELECT … UNION SELECT …  Results in a table whose rows are the union of the results from the two queries  SELECT DISTINCT is implied with UNIONS This is a set operation

34 SELECT Statement Summary Lots of options You can mix and match pretty much arbitrarily Build up queries much as you would relational algebra expressions