Simple SQL Queries (3)



Similar documents
Comp 5311 Database Management Systems. 3. Structured Query Language 1

Chapter 4: SQL. Schema Used in Examples

Advance DBMS. Structured Query Language (SQL)

Chapter 4: SQL. Schema Used in Examples. Basic Structure. The select Clause. modifications and enhancements! A typical SQL query has the form:

Chapter 6: Integrity Constraints

You can use command show database; to check if bank has been created.

Introduction to SQL ( )

SQL is capable in manipulating relational data SQL is not good for many other tasks

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

SUBQUERIES AND VIEWS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 6

We know how to query a database using SQL. A set of tables and their schemas are given Data are properly loaded

Chapter 14: Query Optimization

Boyce-Codd Normal Form

Lesson 8: Introduction to Databases E-R Data Modeling

Chapter 6: Integrity and Security. Domain Constraints

Evaluation of Expressions

Chapter 1: Introduction. Database Management System (DBMS)

Comp 3311 Database Management Systems. 2. Relational Model Exercises

Basic Concepts. Chapter A: Network Model. Cont.) Data-Structure Diagrams (Cont( Data-Structure Diagrams. General Relationships. The DBTG CODASYL Model

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Introduction to database management systems

Chapter 1: Introduction

A Novel Approach of Query Optimization for Distributed Database Systems

COMP 5138 Relational Database Management Systems. Week 5 : Basic SQL. Today s Agenda. Overview. Basic SQL Queries. Joins Queries

Chapter 7: Relational Database Design

Introduction to SQL C H A P T E R3. Exercises

Chapter 7: Relational Database Design

Functional Dependencies

SQL DATA DEFINITION: KEY CONSTRAINTS. CS121: Introduction to Relational Database Systems Fall 2015 Lecture 7

B2.2-R3: INTRODUCTION TO DATABASE MANAGEMENT SYSTEMS

Chapter 2: Entity-Relationship Model. Entity Sets. " Example: specific person, company, event, plant

Chapter 13: Query Processing. Basic Steps in Query Processing

Chapter 2: Entity-Relationship Model. E-R R Diagrams

Converting E-R Diagrams to Relational Model. Winter Lecture 17

Relational Database: Additional Operations on Relations; SQL

Data Structure: Relational Model. Programming Interface: JDBC/ODBC. SQL Queries: The Basic From

Relational Division and SQL

SQL: Queries, Programming, Triggers

Example Instances. SQL: Queries, Programming, Triggers. Conceptual Evaluation Strategy. Basic SQL Query. A Note on Range Variables

Relational Databases

Chapter 5. SQL: Queries, Constraints, Triggers

Instant SQL Programming

The SQL Query Language. Creating Relations in SQL. Referential Integrity in SQL. Basic SQL Query. Primary and Candidate Keys in SQL

SQL: Queries, Programming, Triggers

Chapter 13: Query Optimization

Quiz 2: Database Systems I Instructor: Hassan Khosravi Spring 2012 CMPT 354

Oracle SQL. Course Summary. Duration. Objectives

SQL SELECT Query: Intermediate

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

MySQL for Beginners Ed 3

Databases 2011 The Relational Model and SQL

Oracle Database: SQL and PL/SQL Fundamentals

1 Structured Query Language: Again. 2 Joining Tables

Financial Data Access with SQL, Excel & VBA

Data Models and Database Management Systems (DBMSs) Dr. Philip Cannata

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQL Nested & Complex Queries. CS 377: Database Systems

Oracle Database: SQL and PL/SQL Fundamentals

DBMS / Business Intelligence, SQL Server

Exercises. a. Find the total number of people who owned cars that were involved in accidents

Chapter 1: Introduction

SQL Tables, Keys, Views, Indexes

Query-by-Example (QBE)

Query Processing C H A P T E R12. Practice Exercises

Introduction to database design

CSE 233. Database System Overview

Introduction to Microsoft Jet SQL

Exercise 1: Relational Model

UNIT 6. Structured Query Language (SQL) Text: Chapter 5

Semantic Errors in SQL Queries: A Quite Complete List

Lecture 4: More SQL and Relational Algebra

Define terms Write single and multiple table SQL queries Write noncorrelated and correlated subqueries Define and use three types of joins

Recognizing and resolving Chasm and Fan traps when designing universes

ER modelling, Weak Entities, Class Hierarchies, Aggregation

Module 1: Getting Started with Databases and Transact-SQL in SQL Server 2008

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

4. SQL. Contents. Example Database. CUSTOMERS(FName, LName, CAddress, Account) PRODUCTS(Prodname, Category) SUPPLIERS(SName, SAddress, Chain)

Writing Queries Using Microsoft SQL Server 2008 Transact-SQL

Foundations of Information Management

SQL Query Evaluation. Winter Lecture 23

The Structured Query Language. De facto standard used to interact with relational DB management systems Two major branches

Boats bid bname color 101 Interlake blue 102 Interlake red 103 Clipper green 104 Marine red. Figure 1: Instances of Sailors, Boats and Reserves

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

? Database Management

SQL NULL s, Constraints, Triggers

Writing Queries Using Microsoft SQL Server 2008 Transact-SQL

Relational Algebra and SQL

Chapter 2: Entity-Relationship Model

IT2304: Database Systems 1 (DBS 1)

New York University Computer Science Department Courant Institute of Mathematical Sciences

MOC 20461C: Querying Microsoft SQL Server. Course Overview

IT2305 Database Systems I (Compulsory)

Advanced SQL - Subqueries and Complex Joins

Chapter 8. SQL-99: SchemaDefinition, Constraints, and Queries and Views

Oracle Database 12c: Introduction to SQL Ed 1.1

Introduction to SQL and SQL in R. LISA Short Courses Xinran Hu

Advanced Query for Query Developers

ICAB4136B Use structured query language to create database structures and manipulate data

DATABASE DESIGN AND IMPLEMENTATION II SAULT COLLEGE OF APPLIED ARTS AND TECHNOLOGY SAULT STE. MARIE, ONTARIO. Sault College

Transcription:

Simple SQL Queries (3)

What Have We Learned about SQL? Basic SELECT-FROM-WHERE structure Selecting from multiple tables String operations Set operations Aggregate functions and group-by queries Null values CMPT 354: Database I -- Simple SQL (3) 2

Nested Subqueries When a select-from-where expression is insufficient to express a (complex) query, a subquery as a select-from-where expression can be nested within another query Common use of subqueries Test for set membership Set comparisons Set cardinality CMPT 354: Database I -- Simple SQL (3) 3

Set Membership Find all customers who have both an account and a loan at the bank select distinct customer_name from borrower where customer_name in (select customer_name from depositor ) Find all customers who have a loan at the bank but do not have an account at the bank select distinct customer_name from borrower where customer_name not in (select customer_name from depositor) Can be written without sub-queries (how?) CMPT 354: Database I -- Simple SQL (3) 4

A More Complex Example Find all customers who have both an account and a loan at the Perryridge branch select distinct customer_name from borrower, loan where borrower.loan_number = loan.loan_number and branch_name = Perryridge and (branch_name, customer_name ) in (select branch_name, customer_name from depositor, account where depositor.account_number = account.account_number ) Can you write a simpler query? CMPT 354: Database I -- Simple SQL (3) 5

Set Comparison Find all branches that have greater assets than some branch located in Brooklyn select distinct T.branch_name from branch as T, branch as S where T.assets > S.assets and S.branch_city = Brooklyn Using > some clause select branch_name from branch where assets > some (select assets from branch where branch_city = Brooklyn ) CMPT 354: Database I -- Simple SQL (3) 6

All Clause Find the names of all branches that have greater assets than all branches located in Brooklyn select branch_name from branch where assets > all (select assets from branch where branch_city = Brooklyn ) CMPT 354: Database I -- Simple SQL (3) 7

Test for Empty Relations The exists construct returns the value true if the argument subquery is nonempty exists r r Ø not exists r r = Ø CMPT 354: Database I -- Simple SQL (3) 8

Example Query Find all customers who have an account at all branches located in Brooklyn select distinct S.customer_name from depositor as S where not exists ( (select branch_name from branch where branch_city = Brooklyn ) except (select R.branch_name from depositor as T, account as R where T.account_number = R.account_number and S.customer_name = T.customer_name )) X Y = Ø X Y This query cannot be written using = all and its variants CMPT 354: Database I -- Simple SQL (3) 9

Test for Absence of Duplicate Tuples The unique construct tests whether a subquery has any duplicate tuples in its result Find all customers who have exactly one account at the Perryridge branch select T.customer_name from depositor as T where unique (select R.customer_name from account, depositor as R where T.customer_name = R.customer_name and R.account_number = account.account_number and account.branch_name = Perryridge ) NOT supported by SQL Server CMPT 354: Database I -- Simple SQL (3) 10

Expressing UNIQUE in SQL Server Find all customers who have exactly one account at the Perryridge branch select T.customer_name from depositor as T where (select COUNT(R.customer_name) from account, depositor as R where T.customer_name = R.customer_name and R.account_number = account.account_number and account.branch_name = Perryridge ) = 1 CMPT 354: Database I -- Simple SQL (3) 11

Example Query Find all customers who have at least two accounts at the Perryridge branch select distinct T.customer_name from depositor as T where not unique ( select R.customer_name from account, depositor as R where T.customer_name = R.customer_name and R.account_number = account.account_number and account.branch_name = Perryridge ) How to rewrite this query in SQL Server? CMPT 354: Database I -- Simple SQL (3) 12

Derived Relations A subquery expression can be used in the from clause Conceptually, the result of a query is still a table Querying query results Query result Query Tables Query results CMPT 354: Database I -- Simple SQL (3) 13

Example Query Find the average account balances of those branches where the average account balance is greater than $1200 select branch_name, avg_balance from (select branch_name, avg (balance) from account group by branch_name) as branch_avg ( branch_name, avg_balance ) where avg_balance > 1200 Why don t we need to use the having clause here? The temporary (view) relation branch_avg in the from clause Attribute branch_avg can be used directly in the where clause Can you rewrite it using a having clause? CMPT 354: Database I -- Simple SQL (3) 14

With Clause Subqueries and views in a complex query can be organized using with clauses Find all accounts with the maximum balance with max_balance (value) as select max (balance) from account select account_number from account, max_balance where account.balance = max_balance.value Not supported by SQL Server CMPT 354: Database I -- Simple SQL (3) 15

With Clause: One More Example Find all branches where the total account deposit is greater than the average of the total account deposits at all branches with branch_total (branch_name, value) as select branch_name, sum (balance) from account group by branch_name with branch_total_avg (value) as select avg (value) from branch_total select branch_name from branch_total, branch_total_avg where branch_total.value >= branch_total_avg.value CMPT 354: Database I -- Simple SQL (3) 16

Summary and To-Do List Nested subqueries With clause Work on Assignment 1 CMPT 354: Database I -- Simple SQL (3) 17

Database Schema 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) CMPT 354: Database I -- Simple SQL (3) 18