SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.

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

TURKISH STATISTICAL INSTITUTE 1 /34 SQL FUNDEMANTALS (Muscat, Oman)
CMPT 354 Views and Indexes Spring 2012 Instructor: Hassan Khosravi.
 Database is SQL1.mdb ◦ import using MySQL Migration Toolkit 
7 7 Chapter 7 Structured Query Language (SQL) Database Systems: Design, Implementation, and Management 7th Edition Peter Rob & Carlos Coronel.
Relational Algebra Ch. 7.4 – 7.6 John Ortiz. Lecture 4Relational Algebra2 Relational Query Languages  Query languages: allow manipulation and retrieval.
M ATH IN SQL. 222 A GGREGATION O PERATORS Operators on sets of tuples. Significant extension of relational algebra. SUM ( [DISTINCT] A): the sum of all.
CREATE VIEW SYNTAX CREATE VIEW name [(view_col [, view_col …])] AS [WITH CHECK OPTION];
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 Relational Databases Obtained from Portland State University.
Information Resources Management February 27, 2001.
©Silberschatz, Korth and Sudarshan4.1Database System Concepts Ordering the Display of Tuples List in alphabetic order the names of all customers having.
Temple University – CIS Dept. CIS331– Principles of Database Systems V. Megalooikonomou Query by example (based on notes by Silberchatz,Korth, and Sudarshan.
1 Query Languages: How to build or interrogate a relational database Structured Query Language (SQL)
Unary Query Processing Operators Not in the Textbook!
--The SQL Query Language DML--1 LIKE  LIKE allows to select character strings which have some element in common by using wild cards:  Wild cards:  “%”
Slides adapted from A. Silberschatz et al. Database System Concepts, 5th Ed. SQL - part 2 - Database Management Systems I Alex Coman, Winter 2006.
SQL By: Toan Nguyen. Download Download the software at During the installation –Skip sign up for fast installation.
SQL: Interactive Queries (2) Prof. Weining Zhang.
INFS614 - Lecture week 9 1 More on SQL Lecture Week 9 INFS 614, Fall 2008.
SQL: Interactive Queries (1) John Ortiz Lecture 11SQL: Interactive Queries (1)2 Basic Select Statement  Basic form of the select statement: select target-attribute-list.
©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.
Chapter 3 Single-Table Queries
©Silberschatz, Korth and Sudarshan5.1Database System Concepts Chapter 5: Other Relational Languages Query-by-Example (QBE) Datalog.
3.1 Chapter 3: SQL Schema used in examples p (omit 3.8.2, , 3.11)
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
1 ICS 184: Introduction to Data Management Lecture Note 10 SQL as a Query Language (Cont.)
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
BACS--485 SQL 11 BACS 485 Structured Query Language.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Instructor: Jinze Liu Fall Basic Components (2) Relational Database Web-Interface Done before mid-term Must-Have Components (2) Security: access.
MIS 3053 Database Design & Applications The University of Tulsa Professor: Akhilesh Bajaj RM/SQL Lecture 5 © Akhilesh Bajaj, 2000, 2002, 2003, All.
BACS 287 Structured Query Language 1. BACS 287 Visual Basic Table Access Visual Basic provides 2 mechanisms to access data in tables: – Record-at-a-time.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Copyright © Curt Hill Queries in SQL More options.
1 CSE 480: Database Systems Lecture 12: SQL (Nested queries and Aggregate functions)
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
(C) 2000, The University of Michigan 1 Database Application Design Handout #5 February 4, 2000.
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.
©Silberschatz, Korth and Sudarshan3.1Database System Concepts Extended Relational-Algebra-Operations Generalized Projection Aggregate Functions Outer Join.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu Fall 2009.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
CS 405G: Introduction to Database Systems Instructor: Jinze Liu.
Chapter 7 SQL HUANG XUEHUA. SQL Select-From-Where Statements SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables;
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
1 Schema for Student Registration System Student Student (Id, Name, Addr, Status) Professor Professor (Id, Name, DeptId) Course Course (DeptId, CrsCode,
SQL: Structured Query Language Instructor: Mohamed Eltabakh 1 Part II.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL Query Getting to the data ……..
Chapter 3 Introduction to SQL
Chapter 3 Introduction to SQL(2)
Chapter 3 Introduction to SQL(3)
CS580 Advanced Database Topics
Concept of Aggregation in SQL
SQL: Advanced Options, Updates and Views Lecturer: Dr Pavle Mogin
CS 440 Database Management Systems
Lecture#7: Fun with SQL (Part 2)
CS 405G: Introduction to Database Systems
SQL – Entire Select.
CMPT 354: Database System I
CSC 453 Database Systems Lecture
Section 4 - Sorting/Functions
CSC 453 Database Systems Lecture
Presentation transcript:

SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu

Lecture 12SQL: Interactive Queries (2)2 Aggregate Functions  Functions that take a set of tuples and compute an aggregated value.  Five standard functions: count, min, max, avg, sum  They ignore null values.  Find the total number, the average, minimum, and maximum GPA of students whose age is 17. select count(*), avg(GPA), min(GPA), max(GPA) from Students where Age = 17

Lecture 12SQL: Interactive Queries (2)3 Aggregate Functions (cont.)  Find id and name of students who take 5 or more courses. select SID, Name from Students s where 5 <= (select count(distinct Cno) from Enrollment where SID = s.SID)  Count(distinct Cno)  distinct count(Cno). Why?  Must make sure the subquery generates a value comparable in the predicate.

Lecture 12SQL: Interactive Queries (2)4 Group By Clause  List id and name of students together with the number of hours still needed to graduate, assuming 120 hours are required. select s.SID, Name, sum(Hours) Hours-Needed from Students s, Enrollment e, Courses c where s.SID = e.SID and e.Cno = c.Cno and Grade <= ‘C’ group by s.SID, Name  Enrolled courses are grouped by students.

Lecture 12SQL: Interactive Queries (2)5 Group By Clause (cont.)  Aggregate functions often applied to groups.  One tuple is generated per group  When using group by, select clause can contain only grouping attributes and aggregate func.  Every grouping attribute must be in the select clause.The following is an illegal query (why?): select Age, SID, avg(GPA) from Students group by Age

Lecture 12SQL: Interactive Queries (2)6 Having Clause  For each student age group with more than 50 members, list the age and the number of students with that age. select Age, count(*) from Students group by Age having count(*) > 50  Conditions on aggregate functions are specified in the having clause.  Select & Having may have different functions.

Lecture 12SQL: Interactive Queries (2)7 Order By Clause  List student names in ascending order. select Name from Students order by Name asc  The default is ascending order.  List students with GPA higher than 3.5, first in descending order of GPA, and then in ascending order of name. select * from Students where GPA > 3.5 order by GPA desc, Name asc

Lecture 12SQL: Interactive Queries (2)8 Some Complex Queries  Find the average number of CS courses a student takes.  For non-CS major students who take more CS courses than he does with his major courses, and have taken at lease 2 CS courses, list their id, name, number of CS courses, number of major courses, sorted first in descending order of number of CS courses, then in ascending order of name.

Lecture 12SQL: Interactive Queries (2)9 Interactive SQL Summary  A query may have six clauses: select, from, where, group by, having, order by.  Conceptual evaluation of the query: 1.Evaluate From (cross product) 2.Evaluate Where (selection) 3.Evaluate Group By (form groups) 4.Evaluate Aggregate functions on groups 5.Evaluate Having (choose groups to output) 6.Evaluate Order By (sorting) 7.Evaluate remaining Select (projection)

Lecture 12SQL: Interactive Queries (2)10 Interactive SQL Summary (count.)  Many ways to express a query.  Flat queries may be more efficient.  Nested queries may be easier to understand.  Duplicate elimination may be costly.  <> (not equal) at predicate level often gives a wrong answer. Use set difference, not in, not exists, etc. instead.  Need to handle null values explicitly.  DBMSs often provide many convenient functions. But need to check the compatibility.

Lecture 12SQL: Interactive Queries (2)11 Expressive Power of SQL  SQL is relational complete.  Can express any relational algebraic query.  SQL is more powerful then relational algebra.  Can express aggregation, ordering, recursion, etc.  SQL is not computational complete.  Can not do everything a general programming language can do.

Lecture 12SQL: Interactive Queries (2)12 Create Table Re-visited  Can combine table creation with insertion of tuples using a query. create table Full-Professors as select FID, Name, Office from Faculty where Rank = ‘Full Professor’

Lecture 12SQL: Interactive Queries (2)13 Update By Queries  Relation: Top_Students (SID, Name, GPA)  Insert students with a GPA 3.8 or higher into the Top_Students table. insert into Top_Students select SSN, Name, GPA from Students where GPA >= 3.8  Delete all students who take no courses. delete from Students where SID not in (select SID from Enrollment)

Lecture 12SQL: Interactive Queries (2)14 Update Statement  For every student who takes Database I, set the Grade to ‘A’. update Enrollment set Grade = 'A' where Cno in (select Cno from Courses where Title = ‘Database I')

Lecture 12SQL: Interactive Queries (2)15 Truncate vs Delete *  Use delete to remove data and keep the table storage space. delete from Departments;  Use truncate to remove data and release table storage space. truncate table Departments;

Lecture 12SQL: Interactive Queries (2)16 Views  A view is a virtual table (as opposed to stored base table) defined by a query, directly or indirectly, on base tables. create view Top_Students as select SSN, Name, GPA from Students where GPA >= 3.8  A view may be defined in terms of other views.

Lecture 12SQL: Interactive Queries (2)17 Views (cont.)  The query in view definition is usually not executed until the view is queried. Typically, no data is stored for a view.  A view is queried as if it is a base table.  Find name and GPA of top students whose name starts with a `K'. select Name, GPA from Top_Students where Name like 'K%'

Lecture 12SQL: Interactive Queries (2)18 Query Modification  Queries on a view are translated into queries on base tables by folding the view.  Previous query is translated first into: select Name, GPA from (select SSN, Name, GPA from Students where GPA >= 3.8) where Name like 'K%‘ Then into select Name, GPA from Students where GPA >= 3.8 and Name like 'K%'

Lecture 12SQL: Interactive Queries (2)19 Why Use Views?  Data independence: keep existing application programs from changes of base table schemas.  Access control: provide a mechanism for hiding sensitive data from certain users.  Productivity improvement: make user queries easier to express.

Lecture 12SQL: Interactive Queries (2)20 Example of Using Views Consider following base tables and a view: Students (SID, Name, Birthday, GPA, Phone) Emrollment(SID, Cno, Grade) Courses(Cno, Title, Hours, Dept) create view Student-Course as select SID, Name, Age(Birthday) Age, GPA, c.Cno, Title from Students s, Enrollment e, Courses c where s.SID=e.SID and e.Cno = c.Cno

Lecture 12SQL: Interactive Queries (2)21 Example of Using Views (cont.)  Data independence: Applications using the view are not affected if Age is stored or derived.  Access control: Phone and Birthday of students are hidden from users.  Productivity improvement: “Find all courses taken by a given student” is much simpler: select Cno, Title from Student_Course where SID = X

Lecture 12SQL: Interactive Queries (2)22 Views and Updates  What should happen if a user changes the data in the Student-Course view? insert into Student-Course values (1234, ‘Dave Hall’, 32, 3.15, ‘CS334’, ‘B’)  A view can not be updated if  Contains group by and aggregate functions  Involves multiple tables  A single-table view can be updated if it contains a key of the table

Lecture 12SQL: Interactive Queries (2)23 View Update Example *  Which student should be deleted? create view Age_distribution as select Age, count(*) TotalNo from Students group by Age update Age_distribution set TotalNo = TotalNo – 1 where Age = 20  Which base relation should be changed? delete from Student_Course where SID = '1234'

Lecture 12SQL: Interactive Queries (2)24 Maintaining Materialized Views  One may want to materialize a view (i.e., run its definition query and store the result) as is commonly done in industry (data warehouse). (Why?)  View Maintenance: How to maintain the consistency between a view and its base tables, when base tables are updated?  Incremental View Maintenance: How to maintain a view without re-computing the entire view?