INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.

Slides:



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

SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
Chapter 4: Immediate SQL Complex Queries Complex Queries Views Views Modification of the Database Modification of the Database Joined Relations Joined.
E-R Diagram for a Banking Enterprise
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
MySQL Tutorial (2) Introduction to Database. Banking Example branch (branch-name, branch-city, assets) customer (customer-name, customer-street, customer-city)
MySQL Tutorial Introduction to Database. Learning Objectives  Read and write Data Definition grammar of SQL  Read and write data modification statements.
CIS552SQL1 Data Definition Language Insertions Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Derived Relations.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts - 6 th Edition SQL Schema Changes and table updates instructor teaches.
SQL Overview Data Definition Basic Queries Set Operations Null Values Aggregate Functions Nested Subqueries Modification of the Database.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Chapter 3: SQL Data Definition Language Data Definition Language Basic Structure of SQL Basic Structure of SQL Set Operations Set Operations Aggregate.
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.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Chapter 4: SQL Basic Structure Set Operations Aggregate Functions Null Values Nested Subqueries.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
3.1 Chapter 3: SQL. 3.2 Chapter 3: SQL Basic Query Structure Set Operations Aggregate Functions Null Values Nested Subqueries Complex Queries Views Modification.
Chapter 3 Introduction to SQL Yonsei University 1 st Semester, 2015 Sanghyun Park.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Null Values It is possible for tuples to have a null value for some of their attributes The.
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)
Basic Structure Given sets A 1, A 2,..., A n a relation r is a subset of A 1 x A 2 x... x A n Thus a relation is a set of n-tuples (a 1, a 2,..., a n )
Structured Query Language 2 Presented by: Annisa, M.Kom. Source: Database System Concepts 5 th edition.
CSc-340 2b1 Introduction to SQL Chapter 3 [2 of 2] Null Values Aggregate Functions Nested Subqueries Modification of the Database.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
1 ICS 184: Introduction to Data Management Lecture Note 10 SQL as a Query Language (Cont.)
Chapter 6: Formal Relational Query Languages. 6.2 Chapter 6: Formal Relational Query Languages Relational Algebra Tuple Relational Calculus Domain Relational.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
INTRODUCTION TO SQL Database System Concepts. Agenda Overview of the SQL Query Language Data Definition Basic Query Structure Additional Basic Operations.
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
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Chapter 5-1: Introduction to SQL. 2 Overview of the SQL Query Language Data Definition Basic Query Structure Additional Basic Operations Set Operations.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
Database System Concepts, 6 th Ed. Chapter 6: Formal Relational Query Languages.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 3: Introduction.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 6: Formal Relational.
Database System Concepts, 6 th Ed. ©Silberschatz, Korth and Sudarshan See for conditions on re-usewww.db-book.com Chapter 6: Formal Relational.
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
CS 480: Database Systems Lecture 12 February 11, 2013.
Introduction to SQL.
Chapter 3 Introduction to SQL(3)
Subqueries Schedule: Timing Topic 25 minutes Lecture
Chapter 3: Introduction to SQL
Chapter 3: Introduction to SQL
CS 405G: Introduction to Database Systems
Chapter 3: Introduction to SQL
Chapter 3: Introduction to SQL
Chapter 3: Introduction to SQL
SQL: Structured Query Language
SQL: Structured Query Language
Subqueries Schedule: Timing Topic 25 minutes Lecture
Subqueries Schedule: Timing Topic 25 minutes Lecture
Chapter 3: Introduction to SQL
Lecture 3 Structure Query Language
CS 405G: Introduction to Database Systems
Presentation transcript:

INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS Dr. Adam Anthony Fall 2012

Lecture Overview  Aggregate Functions  Nested Queries  Set membership

Aggregate Functions  Functions that take a column and compute a single answer over all values in that column:  avg: average value  min: minimum value  max: maximum value  sum: sum of values  count: number of values

Simple Examples  Find the average salary of instructors in the Computer Science department  select avg (salary) from instructor where dept_name= ’Comp. Sci.’;  Find the total of all departmental budgets  select sum(budget) from department;  Find the highest and lowest paid professors:  Select max(salary) as highest, min(salary) as lowest from instructor;

Counting is a bit different  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  Find the total number of tuples in a result—use count(*)  Find the number of tuples in the course relation select count(*) from course;

Aggregate Functions – Group By  Find the average salary of instructors in each department  select dept_name, avg (salary) from instructor group by dept_name;  Note: departments with no instructor will not appear in result

Common Pitfall: Aggregation  Attributes in select clause outside of aggregate functions must appear in group by list  /* erroneous query */ select dept_name, ID, avg (salary) from instructor group by dept_name;  Why doesn’t it make sense to do this? How do we fix it? Is that result even useful?

Aggregate Functions – Having Clause  Find the names and average salaries of all departments whose average salary is greater than Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups select dept_name, avg (salary) from instructor group by dept_name having avg (salary) > 42000;

Null Values and Aggregates  Total all salaries select sum (salary ) from instructor  Above statement ignores null amounts  Result is null if there is no non-null amount  All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes  What if collection has only null values?  count returns 0  all other aggregates return null

Nested Subqueries  The really exciting queries use subqueries: A query defined as part of another query  Remember lesson from relational algebra: the output of an operation results in something that can be used as input to a different operation.

Set Membership  To check if a proposed tuple is in another set, we can use the in keyword:  Find all 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);  Also useful: not in

Empty Sets  Sometimes the absence of data gives us insight  The exists keyword evaluates as true if the sub- query supplied to it is non-empty  Similarly, not exists can test for a query with no results  These can be useful with some careful planning

Correlated Subqueries  Remember, I said that re-naming would come back and be really useful!  Find all courses taught in both the Fall 2009 semester and in the Spring 2010 semester: select course_id from section as S where semester = ’Fall’ and year= 2009 and exists (select * from section as T where semester = ’Spring’ and year= 2010 and S.course_id= T.course_id);

The Not Exists…Except Technique  Find all students who have taken all courses offered in the Biology department. select distinct S.ID, S.name from student as S where not exists ( (select course_id from course where dept_name = ’Biology’) except (select T.course_id from takes as T where S.ID = T.ID));

Sub-queries in the FROM clause  The FROM clause accepts relation instances as input, it doesn’t care where they come from  Surround a query with parentheses, and be sure to use the renaming operator where appropriate  Which department costs the most in terms of total salary? select max(tot_salary) from (select sum(salary) as tot_salary from instructor group by dept_name) as dept_salary;

Scalar Subqueries  IF a query evaluates down to exactly one value, you may use it in any scenario where a single value is expected:  In a column: select dept_name, (select count(*) from instructor where department.dept_name = instructor.dept_name) as num_instructors from department;  More often in a WHERE or HAVING clause (next slide)

Scalar Subquery Example  Find all professors within 5% of the highest paid professor’s salary

Database Modification  3 operations  Delete tuples  Insert new tuples  Update existing tuples  Can be done individually or in bulk

Deletion  Delete Everything:  delete from students  Delete only some things—e.g., erasing the ECON department:  delete from student where dept_name = ‘Economics’;  delete from instructor where dept_name = ‘Economics’;  WHERE clause can be just as complex as for a SELECT query  May reference multiple tables in the subquery, though you can only delete from one table at a time

How things can go wrong  Delete all instructors whose salary is less than the average salary of instructors delete from instructor where salary< (select avg (salary) from instructor); Problem: as we delete tuples from deposit, the average salary changes Solution used in SQL: 1. First, compute avg salary and find all tuples to delete 2. Next, delete all tuples found above (without recomputing avg or retesting the tuples)

Modification of the Database – Insertion  Add a new tuple to course insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);  or equivalently insert into course (course_id, title, dept_name, credits) values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);  Add a new tuple to student with tot_creds set to null insert into student values (’3003’, ’Green’, ’Finance’, null);

Insertion (Cont.)  Add all instructors to the student relation with tot_creds set to 0 insert into student select ID, name, dept_name, 0 from instructor  The select from where statement is evaluated fully before any of its results are inserted into the relation (otherwise queries like insert into table1 select * from table1 would cause problems, if table1 did not have any primary key defined.

Modification of the Database – Updates  Increase salaries of instructors whose salary is over $100,000 by 3%, and all others receive a 5% raise  Write two update statements: update instructor set salary = salary * 1.03 where salary > ; update instructor set salary = salary * 1.05 where salary <= ;  The order is important  Can be done better using the case statement (next slide)

Case Statement for Conditional Updates  Same query as before but with case statement update instructor set salary = case when salary <= then salary * 1.05 else salary * 1.03 end

Updates with Scalar Subqueries  Recompute and update tot_creds value for all students update student S set tot_cred = ( select sum(credits) from takes natural join course where S.ID= takes.ID and takes.grade <> ’F’ and takes.grade is not null);  Sets tot_creds to null for students who have not taken any course  Instead of sum(credits), use: case when sum(credits) is not null then sum(credits) else 0 end

Insurance Database  Person(driver-id, name, address)  Car(license, model, year)  Accident(report-number, date, location)  Owns(driver-id, license)  Participated(report-number,license, driver_id, damage_amount)

Banking Database  branch(branch-name, branch-city, assets)  Customer(customer-name, customer_street, customer_city)  Loan(loan-number, branch_name, amount)  Borrower(customer-name, loan-number)  Account(account-number, branch_name, balance)  Depositor(customer-name,account-number)