SQL Recursion, Window Queries

Similar documents
SQL Recursion, Window Queries

Postgres Window Magic

Database Management Systems,

MySQL 8.0 Common Table Expressions & Windowing Functions

Database Systems CSE 303. Outline. Lecture 06: SQL. What is Sub-query? Sub-query in WHERE clause Subquery

Subquery: There are basically three types of subqueries are:

ASSIGNMENT NO Computer System with Open Source Operating System. 2. Mysql

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 6 Windowed Tables and Window Functions in SQL

Chapter 9 Windowed Tables and Window Functions in SQL. Recent Development for Data Models 2016 Stefan Deßloch

Real-World Performance Training SQL Introduction

Based on the following Table(s), Write down the queries as indicated: 1. Write an SQL query to insert a new row in table Dept with values: 4, Prog, MO

Chapter 6 Windowed Tables and Window Functions in SQL

20461: Querying Microsoft SQL Server 2014 Databases

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

CSC Web Programming. Introduction to SQL

COURSE OUTLINE MOC 20461: QUERYING MICROSOFT SQL SERVER 2014

What Are Group Functions? Reporting Aggregated Data Using the Group Functions. Objectives. Types of Group Functions

Querying Data with Transact-SQL

Querying Data with Transact SQL

Querying Data with Transact-SQL

CSE 530A SQL. Washington University Fall 2013

Database Lab Queries. Fall Term 2017 Dr. Andreas Geppert

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

$99.95 per user. Writing Queries for SQL Server (2005/2008 Edition) CourseId: 160 Skill level: Run Time: 42+ hours (209 videos)

Querying Microsoft SQL Server

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

SQL Data Query Language

Why Relational Databases? Relational databases allow for the storage and analysis of large amounts of data.

Intermediate SQL: Aggregated Data, Joins and Set Operators

Calculate the Running Total(Everything)

20461: Querying Microsoft SQL Server

Querying Microsoft SQL Server (MOC 20461C)

After completing this course, participants will be able to:

Duration Level Technology Delivery Method Training Credits. Classroom ILT 5 Days Intermediate SQL Server

CS2 Current Technologies Lecture 2: SQL Programming Basics

Lists and Recursion and Trees

Copyright 2017, Oracle and/or its aff iliates. All rights reserved.

Course Outline. Querying Data with Transact-SQL Course 20761B: 5 days Instructor Led

AVANTUS TRAINING PTE LTD

COSC 304 Introduction to Database Systems SQL. Dr. Ramon Lawrence University of British Columbia Okanagan

Querying Data with Transact-SQL

20761B: QUERYING DATA WITH TRANSACT-SQL

Lab # 6. Using Subqueries and Set Operators. Eng. Alaa O Shama

Querying Microsoft SQL Server

Querying Data with Transact-SQL

Querying Microsoft SQL Server 2008/2012

COURSE OUTLINE: Querying Microsoft SQL Server

Querying Microsoft SQL Server

Joins, NULL, and Aggregation

"Charting the Course... MOC C: Querying Data with Transact-SQL. Course Summary

Querying Data with Transact-SQL

Use the database company.accdb and finish the following exercises on SQL. Emp

Text Search and Similarity Search

Unit Assessment Guide

CS 582 Database Management Systems II

Microsoft Querying Data with Transact-SQL - Performance Course

T-SQL Training: T-SQL for SQL Server for Developers

Querying Data with Transact-SQL

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

Database Management Systems,

20761 Querying Data with Transact SQL

SQL Server 2012 Development Course

MTA Database Administrator Fundamentals Course

QUERYING MICROSOFT SQL SERVER COURSE OUTLINE. Course: 20461C; Duration: 5 Days; Instructor-led

Course 20461C: Querying Microsoft SQL Server

Querying Microsoft SQL Server 2012/2014

Querying Data with Transact-SQL

Aggregate Functions. Eng. Mohammed Alokshiya. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Dept. Database Lab (ECOM 4113)

Databases - 4. Other relational operations and DDL. How to write RA expressions for dummies

Querying Data with Transact-SQL

Full file at

CS2 Current Technologies Lecture 3: SQL - Joins and Subqueries

Assignment 5: SQL II Solution

School of Computing, Engineering and Information Sciences University of Northumbria. Set Operations

QMF: Query Management Facility

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

20461D: Querying Microsoft SQL Server

20761C: Querying Data with Transact-SQL

Querying Data with Transact-SQL (20761)

STRUCTURED QUERY LANGUAGE (SQL)

SQL DATA MANIPULATION. Prepared By: Dr. Vipul Vekariya.

Set theory is a branch of mathematics that studies sets. Sets are a collection of objects.

"Charting the Course to Your Success!" MOC D Querying Microsoft SQL Server Course Summary

RESTRICTING AND SORTING DATA

Microsoft Querying Microsoft SQL Server 2014

Querying Data with Transact-SQL (761)

Querying Microsoft SQL Server

Querying Microsoft SQL Server 2014

Rows and Range, Preceding and Following

Querying Microsoft SQL Server

Sample Question Paper

GIFT Department of Computing Science Data Selection and Filtering using the SELECT Statement

Oracle Database 10g: Introduction to SQL

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

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

Querying Microsoft SQL Server 2014

DB2 SQL Class Outline

2) SQL includes a data definition language, a data manipulation language, and SQL/Persistent stored modules. Answer: TRUE Diff: 2 Page Ref: 36

Chapter 6. SQL Data Manipulation

Transcription:

SQL Recursion, Window Queries PG 7.8; 3.5 & 9.21 Dr. Chris Mayfield Department of Computer Science James Madison University Mar 20, 2019

WITH clause Basic syntax: WITH R AS <definition of R> <query involving R> For example: Flights(airline, src, dst, departs, arrives) WITH den_flights AS ( SELECT * FROM Flights WHERE src = 'DEN' ) SELECT * FROM den_flights ORDER BY departs; Mar 20, 2019 SQL Recursion, Window Queries 2 of 14

Common table expressions Define temporary tables that exist for one query WITH can involve SELECT, INSERT, UPDATE, or DELETE Can be attached to SELECT, INSERT, UPDATE, or DELETE For example: WITH moved_rows AS ( DELETE FROM products WHERE "date" >= '2010-10-01' AND "date" < '2010-11-01' RETURNING * ) INSERT INTO products_log SELECT * FROM moved_rows; https://www.postgresql.org/docs/11/queries-with.html Mar 20, 2019 SQL Recursion, Window Queries 3 of 14

Famous mathematician Paul Erdős (1913 1996) One of the most prolific mathematicians of the 20th century More than 1500 articles Over 500 collaborators The Oddball s Oddball Tribute: Erdős number http://en.wikipedia.org/wiki/paul Erd%C5%91s Mar 20, 2019 SQL Recursion, Window Queries 4 of 14

Erdős numbers WITH e1 AS ( -- Erdos number is 1 SELECT DISTINCT b.author FROM auth AS a -- same paper, but different author JOIN auth AS b ON a.dblp_key = b.dblp_key AND a.author <> b.author WHERE a.author = 'Paul Erdös' ) -- Erdos number is 2 SELECT DISTINCT d.author FROM e1 -- first get all papers of e1 authors JOIN auth AS c ON e1.author = c.author -- same paper, but different author JOIN auth AS d ON c.dblp_key = d.dblp_key AND c.author <> d.author -- excluding e0 and e1 WHERE d.author <> 'Paul Erdös' AND d.author NOT IN (SELECT author FROM e1); Mar 20, 2019 SQL Recursion, Window Queries 5 of 14

Recursive queries using CTE s Not to be confused with Career & Technical Education

Recursive relations in SQL RECURSIVE modifer allows WITH queries to refer to their own output -- Result is 5050 WITH RECURSIVE t(n) AS ( VALUES (1) UNION ALL SELECT n+1 FROM t WHERE n < 100 ) SELECT sum(n) FROM t; General form: 1. Non-recursive term 2. UNION or UNION ALL 3. Recursive term Mar 20, 2019 SQL Recursion, Window Queries 7 of 14

Recursive query evaluation 1. Evaluate the non-recursive term Include all rows in the query result If UNION, eliminate duplicate rows Also place them in a working table 2. While the working table is not empty Evaluate the recursive term using working table If UNION, eliminate duplicates of any previous row Add rows to result and create intermediate table Replace working table with the intermediate table Strictly speaking, this process is iteration not recursion! Mar 20, 2019 SQL Recursion, Window Queries 8 of 14

Recursive flight example -- transitive closure of flights WITH RECURSIVE Reaches(src, dst) AS SELECT src, dst FROM Flights UNION SELECT R1.src, R2.dst FROM Reaches AS R1, Reaches AS R2 WHERE R1.dst = R2.src ) -- all cities reachable from Denver SELECT dst FROM Reaches WHERE src = 'DEN'; Mar 20, 2019 SQL Recursion, Window Queries 9 of 14

More Advanced SQL Analytical queries and Window functions

Analytical queries Calculate a running total Show the cumulative salary within a department row by row Find percentages within a group Show the percentage of the total salary paid to an individual Compute a moving average Average the current row s value with the previous N rows Perform ranking queries Show the relative rank of each salary within a department Top-N queries Find the top n sales by region Mar 20, 2019 SQL Recursion, Window Queries 11 of 14

Window functions Perform a calculation across related rows Partition: which rows are related Order: how to sort each partition Example: -- sort by salary in each dept SELECT depname, empno, salary, rank() OVER (PARTITION BY depname ORDER BY salary DESC) FROM empsalary; Window functions only allowed in SELECT and ORDER BY clauses Defined over output of FROM, WHERE, GROUP BY, and HAVING Mar 20, 2019 SQL Recursion, Window Queries 12 of 14

Example OVER clauses -- average salary in each dept SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary; -- running total of salaries SELECT depname, empno, salary, sum(salary) OVER (ORDER BY salary) FROM empsalary; -- GROUP BY without grouping SELECT depname, empno, salary, sum(salary) OVER () FROM empsalary; https://www.postgresql.org/docs/11/tutorial-window.html Mar 20, 2019 SQL Recursion, Window Queries 13 of 14

Other window functions SELECT depname, empno, salary, sum(salary) OVER w, -- and other aggregate functions row_number() OVER w, -- from 1 to number of rows in w rank() OVER w, -- rows with same value get same rank FROM empsalary WINDOW w AS (PARTITION BY depname ORDER BY salary DESC); There are many more options for OVER clauses https://www.postgresql.org/docs/11/sql-expressions.html#syntax- WINDOW-FUNCTIONS List of general-purpose window functions https://www.postgresql.org/docs/11/functions-window.html Mar 20, 2019 SQL Recursion, Window Queries 14 of 14