SQL: WHERE Subqueries and Other Syntactic Sugar

Similar documents
SQL: Queries, Programming, Triggers

Introduction to tuple calculus Tore Risch

Relational Databases

SQL: Queries, Programming, Triggers

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

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

Oracle SQL. Course Summary. Duration. Objectives

Chapter 13: Query Optimization

Schema Mappings and Data Exchange

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

Execution Strategies for SQL Subqueries

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

Chapter 14: Query Optimization

Database Design and Database Programming with SQL - 5 Day In Class Event Day 1 Activity Start Time Length

Semantic Errors in SQL Queries: A Quite Complete List

SQL Tables, Keys, Views, Indexes

[Refer Slide Time: 05:10]

Chapter 5. SQL: Queries, Constraints, Triggers

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

Advance DBMS. Structured Query Language (SQL)

Instant SQL Programming

Oracle Database 12c: Introduction to SQL Ed 1.1

Introduction to database design

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

SQL Database queries and their equivalence to predicate calculus

Relational Division and SQL

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

MOC 20461C: Querying Microsoft SQL Server. Course Overview

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

Oracle Database: SQL and PL/SQL Fundamentals

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

Using Temporary Tables to Improve Performance for SQL Data Services

SQL Nested & Complex Queries. CS 377: Database Systems

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

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

Relational Algebra and SQL

Database Programming with PL/SQL: Learning Objectives

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

Oracle Database: SQL and PL/SQL Fundamentals NEW

Testing LTL Formula Translation into Büchi Automata

Oracle Database: SQL and PL/SQL Fundamentals

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

Inside the PostgreSQL Query Optimizer

Translating SQL into the Relational Algebra

Introduction to formal semantics -

Rigorous Software Development CSCI-GA

Semantic Analysis: Types and Type Checking

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Advanced SQL. Lecture 3. Outline. Unions, intersections, differences Subqueries, Aggregations, NULLs Modifying databases, Indexes, Views

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

1 Structured Query Language: Again. 2 Joining Tables

Temporal Database System

Databases 2011 The Relational Model and SQL

A Comparison of Database Query Languages: SQL, SPARQL, CQL, DMX

Cassandra. References:

SQL (structured query language)

SQL NULL s, Constraints, Triggers

MySQL for Beginners Ed 3

Monitoring Metric First-order Temporal Properties

Writing Control Structures

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

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

Lecture 1. Basic Concepts of Set Theory, Functions and Relations

Introduction to Microsoft Jet SQL

Oracle Database 11g SQL

Relational Calculus. Module 3, Lecture 2. Database Management Systems, R. Ramakrishnan 1

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

Home Assignment 4 OCL

Unit 3. Retrieving Data from Multiple Tables

Querying Microsoft SQL Server

CS2Bh: Current Technologies. Introduction to XML and Relational Databases. The Relational Model. The relational model

3. Relational Model and Relational Algebra

5.1 Database Schema Schema Generation in SQL

Discovering SQL. Wiley Publishing, Inc. A HANDS-ON GUIDE FOR BEGINNERS. Alex Kriegel WILEY

Chapter 1: Introduction

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Oracle 10g PL/SQL Training

Normal Form vs. Non-First Normal Form

Querying Microsoft SQL Server 2012

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

Physical Database Design and Tuning

Moving from CS 61A Scheme to CS 61B Java

How To Handle Missing Information Without Using NULL

Introduction to SQL for Data Scientists

1. Physical Database Design in Relational Databases (1)

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

Querying Microsoft SQL Server 2012

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

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Course ID#: W 35 Hrs. Course Content

Course 10774A: Querying Microsoft SQL Server 2012

Predicate Logic. For example, consider the following argument:

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

Querying Microsoft SQL Server 20461C; 5 days

Financial Data Access with SQL, Excel & VBA

Consulting. Personal Attention, Expert Assistance

DBMS / Business Intelligence, SQL Server

Transcription:

SQL: WHERE Subqueries and Other Syntactic Sugar David Toman School of Computer Science University of Waterloo Introduction to Databases CS348 David Toman (University of Waterloo) SQL Syntax Sugar 1 / 17

More on "WHERE" conditions Most queries are SELECT BLOCK queries. Early SQL developments tried to cram everything into the SELECT block 1 Esoteric predicates (atomic) range searches (for ordered types) Name BETWEEN C AND EZ almost matches (for strings) Name LIKE _A% "_" matches one character "%" matches any number of characters 2 Predicates defined by subqueries ) allow for really tricky formulation of queries. David Toman (University of Waterloo) SQL Syntax Sugar 2 / 17

Esoteric Predicates: Example Find all book titles starting with Logic and published between 1980 and 2000: SQL> select title 2 from publication, book 3 where publication.pubid=book.pubid 4 and title like Logic% 5 and year between 1980 and 2000 TITLE ----------------------------- Logics for Databases and Information Systems David Toman (University of Waterloo) SQL Syntax Sugar 3 / 17

WHERE Subqueries Additional (complex) search conditions ) query-based search predicates Advantages simplifies writing queries with negation Drawbacks complicated semantics (especially when duplicates are involved) very easy to make mistakes VERY COMMONLY used to formulate queries David Toman (University of Waterloo) SQL Syntax Sugar 4 / 17

Overview of WHERE Subqueries presence/absence of a single value in a query Attr IN ( Q ) Attr NOT IN ( Q ) relationship of a value to some/all values in a query Attr op SOME ( Q ) Attr op ALL ( Q ) emptiness/non-emptiness of a query EXISTS ( Q ) NOT EXISTS ( Q ) In the first two cases Q has to be unary. David Toman (University of Waterloo) SQL Syntax Sugar 5 / 17

Example: "attr IN ( Q )" SQL> select title 2 from publication 3 where pubid in ( 4 select pubid from article 5 ) TITLE ------------------------------- Temporal Logic in Information Systems Datalog with Integer Periodicity Constraints Point-Based Temporal Extension of Temporal SQL David Toman (University of Waterloo) SQL Syntax Sugar 6 / 17

Pure SQL Equivalence Nesting in the WHERE clause is mere syntactic sugar: SELECT r.b SELECT r.b FROM r FROM r, ( WHERE r.a IN ( SELECT DISTINCT b SELECT b FROM s FROM s ) s ) WHERE r.a=s.b All of the remaining constructs can be rewritten in similar fashion... David Toman (University of Waterloo) SQL Syntax Sugar 7 / 17

Example: "attr NOT IN ( Q )" All author-publication ids for all publications except books and journals: SQL> select * 2 from wrote 3 where publication not in ( 4 ( select pubid from book ) 5 union 6 ( select pubid from journal ) ) AUTHOR PUBLICAT ------- ----- 1 ChTo98 1 ChTo98a 1 Tom97 2 ChTo98 2 ChTo98a... search conditions may contain complex queries. David Toman (University of Waterloo) SQL Syntax Sugar 8 / 17

"attr NOT IN ( Q )" (cont.)... another formulation: SQL> select * 2 from wrote 3 where publication not in ( 4 select pubid from book 5 ) and publication not in ( 6 select pubid from journal 7 )... and may be combined using boolean connectives. David Toman (University of Waterloo) SQL Syntax Sugar 9 / 17

Example: "attr op SOME/ALL ( Q )" Find article with most pages: SQL> select pubid 2 from article 3 where endpage-startpage>=all ( 4 select endpage-startpage 5 from article 6 ) PUBID ----- ChTo98... another way of saying max attr = SOME (Q) is the same as attr IN (Q) attr <> ALL (Q) is the same as attr NOT IN (Q) David Toman (University of Waterloo) SQL Syntax Sugar 10 / 17

Parametric Subqueries so far subqueries were independent on the main query ) not correlated ) not much fun (good only for simple queries) SQL allows parametric (correlated) subqueries: ) of the form Q(p1,...pk) where pis are attributes in the main query. ) The truth of a predicate defined by a subquery is determined for each substitution (tuple) in the main query 1 instantiate all the parameters and 2 check for the truth value as before... David Toman (University of Waterloo) SQL Syntax Sugar 11 / 17

Example: EXISTS Parametric subqueries are most common for existential subqueries: SQL> select * 2 from wrote r 3 where exists ( select * 4 from wrote s 5 where r.publication=s.publication 6 and r.author<>s.author ) AUTHOR PUBLICAT ---------- -------- 1 ChTo98 1 ChTo98a 2 ChTo98 2 ChTo98a 2 ChSa98 3 ChSa98 David Toman (University of Waterloo) SQL Syntax Sugar 12 / 17

Example: NOT EXISTS... and now it is easy to complement conditions: SQL> select * 2 from wrote r 3 where not exists ( 4 select * 5 from wrote s 6 where r.publication=s.publication 7 and r.author<>s.author 8 ) AUTHOR PUBLICAT ---------- -------- 1 Tom97 David Toman (University of Waterloo) SQL Syntax Sugar 13 / 17

Example: IN SQL> select * 2 from wrote r 3 where publication in ( 4 select publication 5 from wrote s 6 where r.author<>s.author 7 ) AUTHOR PUBLICAT ------- ----- 1 ChTo98 1 ChTo98a 2 ChTo98 2 ChTo98a 2 ChSa98 3 ChSa98 David Toman (University of Waterloo) SQL Syntax Sugar 14 / 17

More levels of Nesting WHERE subqueries are just queries ) we can nest again and again and... ) every nested subquery can use attributes from the enclosing queries as parameters. ) correct naming is imperative used to formulate very complex search conditions ) attributes present in the subquery only CANNOT be used to construct the result(s). David Toman (University of Waterloo) SQL Syntax Sugar 15 / 17

Example List all authors who always publish with someone else: SQL> select a1.name, a2.name 2 from author a1, author a2 3 where not exists ( 4 select * 5 from publication p, wrote w1 6 where p.pubid=w1.publication 7 and a1.aid=w1.author 8 and a2.aid not in ( 9 select author 10 from wrote 11 where publication=p.pubid 12 and author<>a1.aid 13 ) 14 ) David Toman (University of Waterloo) SQL Syntax Sugar 16 / 17

Summary WHERE subqueries easy formulation of queries of the form All x in R such that (a part of) x doesn t appear in S. subqueries only stand for WHERE conditions you can use input parameters... CANNOT be used to produce results but these must be bound in the main query all of these are just a syntactic sugar and can be expressed using queries nested in the FROM clause but it might be quite hard... easy to make mistakes though (be very careful) David Toman (University of Waterloo) SQL Syntax Sugar 17 / 17