SQL: Structured Query Language Nested Queries

Similar documents
SQL: Structured Query Language Nested Queries. Return Types. .. Cal Poly CPE/CSC 365: Introduction to Database Systems Alexander Dekhtyar..

Querying Data with Transact SQL

CMPT 354: Database System I. Lecture 4. SQL Advanced

Database Languages. A DBMS provides two types of languages: Language for accessing & manipulating the data. Language for defining a database schema

A subquery is a nested query inserted inside a large query Generally occurs with select, from, where Also known as inner query or inner select,

Missing Information. We ve assumed every tuple has a value for every attribute. But sometimes information is missing. Two common scenarios:

CMPT 354: Database System I. Lecture 2. Relational Model

Nested Queries. Dr Paolo Guagliardo. Aggregate results in WHERE The right way. Fall 2018

CS 464/564 Introduction to Database Management System Instructor: Abdullah Mueen

Chapter 7 Advanced SQL. Objectives

Relational Algebra for sets Introduction to relational algebra for bags

Querying Data with Transact-SQL

Lab 6 Counting with SQL

Querying Data with Transact-SQL

EECS 647: Introduction to Database Systems

Querying Data with Transact SQL Microsoft Official Curriculum (MOC 20761)

Intermediate SQL ( )

Lecture 3 SQL. Shuigeng Zhou. September 23, 2008 School of Computer Science Fudan University

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

COMP 430 Intro. to Database Systems

SQL. Dean Williamson, Ph.D. Assistant Vice President Institutional Research, Effectiveness, Analysis & Accreditation Prairie View A&M University

Database Management and Tuning

Database Applications (15-415)

Writing Queries Using Microsoft SQL Server 2008 Transact-SQL. Overview

The SELECT-FROM-WHERE Structure

Assignment 6: SQL III Solution

Querying Microsoft SQL Server 2014

Relational Model History. COSC 304 Introduction to Database Systems. Relational Model and Algebra. Relational Model Definitions.

Views and Virtual Tables

SQL - Lecture 3 (Aggregation, etc.)

MANAGING DATA(BASES) USING SQL (NON-PROCEDURAL SQL, X401.9)

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

The SELECT-FROM-WHERE Structure

EECS 647: Introduction to Database Systems

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

CSC 453 Database Technologies. Tanu Malik DePaul University

Carnegie Mellon Univ. Dept. of Computer Science Database Applications. General Overview - rel. model. Overview - detailed - SQL

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

Databases SQL2. Gordon Royle. School of Mathematics & Statistics University of Western Australia. Gordon Royle (UWA) SQL2 1 / 26

Structured Query Language (SQL)

Chapter 4: Intermediate SQL

Learning Alliance Corporation, Inc. For more info: go to

An Introduction to Structured Query Language

SQL: Structured Query Language Views. Database Views. Views in SQL. .. Cal Poly CPE/CSC 365: Introduction to Database Systems Alexander Dekhtyar..

Database Security: Transactions, Access Control, and SQL Injection

NESTED QUERIES AND AGGREGATION CHAPTER 5 (6/E) CHAPTER 8 (5/E)

An Introduction to Structured Query Language

Tables From Existing Tables

Chapter 7 Equijoins. Review. Why do we store data for articles and writers in two separate tables? How can we link an article to its writer?

An Introduction to Structured Query Language

Databases 2011 The Relational Model and SQL

Handout 9 CS-605 Spring 18 Page 1 of 8. Handout 9. SQL Select -- Multi Table Queries. Joins and Nested Subqueries.

SQL. SQL Data Manipulation: Queries

Test Bank for Database Processing Fundamentals Design and Implementation 13th Edition by Kroenke

SQL - Data Query language

Chapter 4: SQL. Basic Structure

Midterm Review. Winter Lecture 13

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Principles of Data Management

DATABASTEKNIK - 1DL116

An Introduction to Structured Query Language

Querying Data with Transact-SQL (20761)

Simple queries Set operations Aggregate operators Null values Joins Query Optimization. John Edgar 2

Microsoft Querying Microsoft SQL Server 2014

Assignment 6: SQL III

SQL Aggregation and Grouping. Outline

SQL Aggregation and Grouping. Davood Rafiei

SQL-Nested Queries & Aggregate functions. Lecture By Binu Jasim 02-Aug-2016

ACS-3902 Fall Ron McFadyen 3D21 Slides are based on chapter 5 (7 th edition) (chapter 3 in 6 th edition)

GUJARAT TECHNOLOGICAL UNIVERSITY

Aggregation in MongoDB: Additional Operations. Additional Aggregation Pipeline Operators. Faceted Filter

CGS 3066: Spring 2017 SQL Reference

Lecture 04: SQL. Wednesday, October 4, 2006

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

[AVNICF-MCSASQL2012]: NICF - Microsoft Certified Solutions Associate (MCSA): SQL Server 2012

Lecture 04: SQL. Monday, April 2, 2007

Database Programming with SQL

Announcements (September 14) SQL: Part I SQL. Creating and dropping tables. Basic queries: SFW statement. Example: reading a table

Oracle 1Z MySQL 5.6 Developer.

Teradata SQL Features Overview Version

Chapter 4: Intermediate SQL

DATABASE TECHNOLOGY - 1MB025

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

SQL Queries. COSC 304 Introduction to Database Systems SQL. Example Relations. SQL and Relational Algebra. Example Relation Instances

Introductory SQL SQL Joins: Viewing Relationships Pg 1

Objectives. After completing this lesson, you should be able to do the following:

Textbook: Chapter 4. Chapter 5: Intermediate SQL. CS425 Fall 2016 Boris Glavic. Chapter 5: Intermediate SQL. View Definition.

Databases (MariaDB/MySQL) CS401, Fall 2015

SQL: Data Manipulation Language. csc343, Introduction to Databases Diane Horton Winter 2017

SQL: csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Sina Meraji. Winter 2018

SQL Interview Questions

20461: Querying Microsoft SQL Server 2014 Databases

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

1. Data Definition Language.

An Introduction to Structured Query Language

CS425 Fall 2017 Boris Glavic Chapter 5: Intermediate SQL

Subquery: There are basically three types of subqueries are:

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

SQL. Chapter 5 FROM WHERE

Transcription:

.. Cal Poly Spring 2013 CPE/CSC 365 Introduction to Database Systems Alexander Dekhtyar Eriq Augustine.. SQL: Structured Query Language Nested Queries One of the most important features of SQL is that SQL SELECT statements can be nested within each other to produce complex queries. While some of the queries discussed below can be written without nesting, some queries require nested structure. Return Types In general, a SELECT statement returns a relational table as a result. However, there are situations, where the returned table can be cast to a more simple structure. In general, the following four cases are possible. We note, that in all four cases, it is always possible to treat the returned result as a relational table. Consider, for example, the following table (underlined values are the primary key): University(id INT, name VARCHAR(60), city VARCHAR(15), state CHAR(2), numstudents INT) The return type of a SELECT statement may be: 1. An atomic value. Returned when a single column of a relation is requested in the SELECT clause, and the information requested is unique in the table (only one tuple is returned). For example, the following query SELECT name WHERE id = 1 ; returns a single string: the name attribute for the university with id = 1. 2. A single tuple. Returned when the SELECT clause contains multiple attributes, but the information requested is unique in the table (only one tuple is returned). For example, consider the following query: SELECT WHERE id = 1 0 ; This query returns a single tuple, whose value for the primary key attribute is 10. 3. A single column. Returned when a single attribute is listed in the SELECT clause, and when the result contains more than one entry. This can be viewed as a set of atomic values. For example, the query below, returns the list of IDs for all universities in California. SELECT id WHERE s t a t e = CA ; 4. A relational table. This is the most general return type, used when the SELECT clause contains multiple columns, and the result of the query is multiple tuples. This return type can be viewed as a set of tuples. The following query returns as its result the list of all California campuses and their corresponding enrollments: 1

SELECT name, numstudents WHERE s t a t e = CA ; Note: For some queries, the return type can be established statically, by analyzing constraints on the relational table. For other queries, the actual return type of the query run on some instances can be different than the statically predicted return type (e.g., the last query will return a single tuple if only one record about a California university exists in the table). Nested Queries in the FROM clause Since the return of any SELECT statement can be viewed as a relational table, a nested SELECT statement can be used in the FROM clause. This allows you to construct a temporary table which is useful for the purposes of the query, but does not need to be made persistent. Any attribute of the table resulting from the nested SELECT statement can be accessed from within the WHERE, GROUP BY, HAVING, and SELECT clauses of the main query, just like attributes of regular relational tables. Syntax: SELECT <select l i s t > FROM (SELECT query ) <a l i a s >,... [WHERE <c o n d i t i o n s > ] [GROUP BY <a t t r i b u t e l i s t > [HAVING <c o n d i t i o n s > ] ] Two rules must be followed: The nested SELECT statement must be enclosed in parentheses. The result of the nested SELECT statement must be given a table alias if it is in the FROM clause and all aggregate/expression attributes in the result of the nested SELECT statement that are to be referenced in the outer query must be given column aliases. Example. Consider the following tables (of university courses, students and student enrollments in courses): Course(major, num, name, room, instructor, capacity) Student(ssn, firstname, lastname, major, year) Enrollments(courseMajor, coursenum,studentid) Consider the following query: The nested query: SELECT C. major, C. num, room FROM Course C, (SELECT E. coursemajor, E. coursenum, COUNT( ) AS e n r o l l e d FROM Student S, Enrollments E WHERE S. year > 3 AND E. studentid = S. ssn GROUP BY E. coursemajor, E. coursenum ) S WHERE C. major = S. coursemajor AND C.num = S. coursenumber AND S. e n r o l l e d >= c a p a c i t y / 2 ; SELECT E. coursemajor, E. coursenum, COUNT( ) AS e n r o l l e d FROM Student S, Enrollments E WHERE S. year > 3 AND E. studentid = S. ssn GROUP BY E. coursemajor, E. coursenum 2

Finds all seniors (year > 3) and joins their information with the information about the courses they are taking. This information is then grouped by course id/number, resulting in the relation that reports a list of courses and the number of senior students enrolled in each 1. This information is reported back as a three-attribute relation with alias S to the main query, which, in turn, finds and reports the courses and the rooms of the courses, in which senior students occupy more than one half of the designated capacity. The same query can be rewritten as: SELECT C. major, C. num, room FROM Course C, Student S, Enrollments E WHERE S. year > 3 AND E. studentid = S. ssn AND C. Major = E. coursemajor AND C. num = E. coursenumber GROUP BY C. Major, E. coursenum, c a p a c i t y HAVING COUNT( ) >= c a p a c i t y / 2 ; Note, that in this query, capacity has to be included in the GROUP BY clause, to allow for its use in the HAVING clause. Nested Queries in the WHERE Clause Nested queries that return atomic values A SELECT statement that returns a single value can be used in any expression in the WHERE clause where the value of this type is expected. This, in particular, can be used to write joins in nested form. Example Consider the following tables (a list of bank accounts and a list of transactions for the account): each transaction either adds money (After > Before) or removes money (After < Before): Let us also assume that we have a UNIQUE(owner, type) constraint on Accounts. We can write the query that finds all dates on which John Smith added money to his savings account as follows: SELECT t r a n s a c t i o ndate FROM Transactions T WHERE T. b e f o r e < T. a f t e r AND AcctNo = (SELECT acctno WHERE A. owner = John Smith AND A. type = Savings ) ; Return Value Allowed Comparisons numeric <, >, <=, >=,! =, <>, = strings =,! =, <>, LIKE other =,! =, <> Nested queries that return single tuples SQL has a tuple (list) construct: (<Att>, <Att>,...,<Att>). When a SELECT statement returns a single tuple, tuples formed using this construct can be compared to the returned tuple. 1 For courses that have at least one senior student enrolled 3

Example Consider the following tables: People(id, firstname, lastname, age, gender) Interests(firstName, lastname, interest) The following query returns all interests of the person who has the id number 1 in the People table. SELECT i. i n t e r e s t FROM I n t e r e s t s i WHERE ( i. firstname, i. lastname ) = (SELECT firstname, lastname FROM People WHERE id = 1 ) ; Return Value Allowed comparisons tuple (list) =,! =, <> Nested queries that return single columns When a SELECT statement returns a single column as a result, the result can be treated as a set of atomic values. SQL allows for a number of comparison operations between atomic values and sets: Operation Explanation EXISTS <SubQuery> true if <SubQuery> returns a non-empty table <AtomicValue> IN <SubQuery> true if <AtomicValue> is one of the elements in the result of <SubQuery> <AtomicValue> <Op> ALL (<SubQuery>) <Op> {>, <, >=, <=, =,! =, <>} universal comparison <AtomicValue> <Op> ANY (<SubQuery>) <Op> {>, <, >=, <=, =,! =, <>} existential comparison A universal comparison operation evaluates to true iff <AtomicValue> is in the required relationship (<Op>) with every member of the set returned by <Expression>. An existential comparison operation evaluates to true iff <AtomicValue> is in the required relationship (<Op>) with at least one member of the set returned by <Expression>. Examples. Consider the relational tables Accounts and Transactions defined above: The following query finds the account information for all accounts that had at least one $1000 deposit. SELECT A. acctno, A. owner, A. type WHERE A. acctno IN (SELECT DISTINCT acctno FROM Transactions WHERE a f t e r b e f o r e = 1000 AND transactiontype = d e p o s i t ) ; This query finds the information about all accounts with the maximum balance. SELECT A. acctno, A. owner, A. balance FROM Accounts WHERE balance >= ALL (SELECT Balance FROM Accounts ) ; Correlated Queries In examples above, nested queries can be evaluated once for the entire lifetime of the full query. In some situations, though, the result of the inner query depends changes as the evaluation of the outer query proceeds. Such queries are called correlated queries. 4

Examples. The query below reports the highest balance for each type of the account. SELECT DISTINCT A. type, A. balance WHERE A. balance >= ALL (SELECT Balance A WHERE AA. type = A. type ) ; Note, that in this case, correlating subquery and the main query is unavoidable the subquery has to select only the balances of accounts of the same type as the current account number being considered in the outer query. The next query is one possible way of finding all accounts that had transactions on October 1, 2007. SELECT A. acctno, A. owner WHERE EXISTS (SELECT FROM Transactions t WHERE t. transactiondate = DATE( 2007 10 01 ) AND t. acctno = A. acctno ) ; In this case the use of EXISTS operation naturally represents our intuition: we are not interested in the specific details of transactions that happened on October 1, 2007, rather, we are simply verifying that such transactions exist for each account. Nested queries that return relational tables SELECT statements that return multicolumn relational tables can also be used as subqueries. The table below shows operations which they can be used: Expression Allowed Operators EXISTS (<Subquery>) N/A <Tuple> IN (<SubQuery>) N/A <Tuple> <OP> ALL (<SubQuery>) =, <>,! = <Tuple> <OP> ANY (<SubQuery>) =, <>,! = Examples. Consider the Accounts and Transactions tables discussed above. The following query finds all dates when transactions like (same account type, same amount) any transactions on the accounts owned by Bob Brown occurred. SELECT t r a n s a c t i o n D a t e FROM T r a n s a c t i o n s WHERE ( transactiontype, A f t e r Before ) = ANY (SELECT transactiontype, a f t e r b e f o r e FROM T r a n s a c t i o n s T, Accounts A WHERE A. AcctNo = T. AcctNo AND A. Owner = Bob Brown ) ; 5