CSC 337. Multi-table SQL Queries (Joins) Rick Mercer, Marty Stepp

Similar documents
CSE 154 LECTURE 14: MULTI-TABLE SQL QUERIES (JOINS )

CSE 154 LECTURE 23:RELATIONAL DATABASES AND SQL

CSE3026: Web Application Development Relational Databases and SQL Scott Uk-Jin Lee

CSC 337. Database Design and More Commands. Rick Mercer.

Announcements (January 20) Relational Database Design. Database (schema) design. Entity-relationship (E/R) model. ODL (Object Definition Language)

Relational Database Design. Announcements. Database (schema) design. CPS 216 Advanced Database Systems. DB2 accounts have been set up

SQL AND MORE EVENT VALIDATION

Problem Description Earned Max 1 HTML/CSS 20 2 Javascript/DOM 20 3 Ajax/XML 20 5 PHP 20 4 SQL 20 X Extra Credit +1 TOTAL 100

Networks and Web for Health Informatics (HINF 6220)

SQLite, Firefox, and our small IMDB movie database. CS3200 Database design (sp18 s2) Version 1/17/2018

A hypothetical M:M student schedule example

FIT 100 More Microsoft Access and Relational Databases Creating Views with SQL

Problem Description Earned Max 1 PHP 25 2 JavaScript / DOM 25 3 Regular Expressions 25 TOTAL Total Points 100. Good luck! You can do it!

Lecture 19 Query Processing Part 1

Databases (MariaDB/MySQL) CS401, Fall 2015

The Relational Data Model. Data Models. Relational vs Semistructured. Structure Operations - Constraints

CSC 453 Database Technologies. Tanu Malik DePaul University

Database Design. Overview

Problem Description Earned Max 1 PHP 25 2 JavaScript/DOM 25 3 Regular Expressions 25 4 SQL 25 TOTAL Total Points 100

Introduction to MySQL /MariaDB and SQL Basics. Read Chapter 3!

Sample midterm extra questions

CSE 154, Autumn 2012 Final Exam, Thursday, December 13, 2012

MovieNet: A Social Network for Movie Enthusiasts

Module 3 MySQL Database. Database Management System

Unit 27 Web Server Scripting Extended Diploma in ICT

QUETZALANDIA.COM. 5. Data Manipulation Language

SQL: Part II. Announcements (September 18) Incomplete information. CPS 116 Introduction to Database Systems. Homework #1 due today (11:59pm)

Review Problems. Computer Science E-66 Harvard University David G. Sullivan, Ph.D. Tree-Based Index Structure Problem

CS 327E Class 3. February 11, 2019

Views and Virtual Tables

CSCB20 Week 4. Introduction to Database and Web Application Programming. Anna Bretscher Winter 2017

Introduction to Database Systems CSE 344

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?

Relational Model & Algebra. Announcements (Thu. Aug. 27) Relational data model. CPS 116 Introduction to Database Systems

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

CS40 Exam #2 November 14, 2001

IBM Software Group Information Management Software. The Informix Detective Game (Student Handout)

Announcements (September 18) SQL: Part II. Solution 1. Incomplete information. Solution 3? Solution 2. Homework #1 due today (11:59pm)

Section 3 Worksheet. Part 1. Movies and Directors

SQL Lab: Assignment 2 (due to )

Project 1. Yuji Shimojo CMIS 320. Instructor: Denton Guy-Williams

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

Writing Queries Using Microsoft SQL Server 2008 Transact- SQL

Content-Based Assessments

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

a) <div id="coffee"> <p>*('o')*</p> <ul> <li>aaa</li> <li id="c">bbb</li> <li>ccc</li> </ul> </div>

Relational Model, Key Constraints

Studywiz CSV Import Specification Single School

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

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

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

Problem Description Earned Max 1 HTML / CSS Tracing 20 2 CSS 20 3 PHP 20 4 JS / Ajax / JSON 20 5 SQL 20 X Extra Credit 1 TOTAL Total Points 100

Movie Explorer. Group Members: Name: Chen Wang JHED: cwang107 Section: 415 Name: Yang Xi JHED: yxi5 Section: 415. Domain Description:

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Almost all new data created today is digital Problem: How to organize the data and store it? Capacity Speed Life of the data Number of users

MovieNet: A Social Network for Movie Enthusiasts

Hash table example. B+ Tree Index by Example Recall binary trees from CSE 143! Clustered vs Unclustered. Example

6.1 Understand Relational Database Management Systems

Introduction to Database Systems CSE 414. Lecture 26: More Indexes and Operator Costs

Lecture 5. Monday, September 15, 2014

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

STIDistrict Query (Basic)

CSCI 1100L: Topics in Computing Lab Lab 07: Microsoft Access (Databases) Part I: Movie review database.

MongoDB Schema Design

Part 1: Access Privileges

Database Systems. Bence Molnár

EE221 Databases Practicals Manual

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

Introduction to Database S ystems Systems CSE 444 Lecture 1 Introduction CSE Summer

Database Systems CSE 414

MySQL. A practical introduction to database design

Querying Data with Transact-SQL

THE AUSTRALIAN NATIONAL UNIVERSITY. Mid-Semester Examination August 2006 RELATIONAL DATABASES (COMP2400)

How did Netflix Beat blockbuster? Database Systems Part 2

Montgomery County Schools Teacher Web Pages

Previously everyone in the class used the mysql account: Username: csci340user Password: csci340pass

Oracle 1Z Oracle Database 11g SQL Fundamentals I. Download Full Version :

CSE 154: Web Programming Autumn 2018

Part 3: Dynamic Data: Querying the Database

Simple Programs. 3-Tier Architectures. Databases and the Web. 3-Tier Architectures. Thin-Client 3-Tier Models. Thick-Client 3-Tier Models

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database: SQL Fundamentals I. Q&As: 292

Thinking of Databases

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

Implementing a Logical-to-Physical Mapping, Part II

SYSTEM CODE COURSE NAME DESCRIPTION SEM

A practical introduction to database design

Database Programming with SQL

Intro to Structured Query Language Part I

L12: ER modeling 5. CS3200 Database design (sp18 s2) 2/22/2018

Review. Objec,ves. Example Students Table. Database Overview 3/8/17. PostgreSQL DB Elas,csearch. Databases

Topic of most interest

SQL Programming Project Tables. OracleFlix Online Media Rentals. Create tables. 1. Create tables using the attached ERD. AND

Retrieving Data Using the SQL SELECT Statement. Copyright 2009, Oracle. All rights reserved.

CSC Web Programming. Introduction to SQL

Optimizing SQL. Kate Amorella Proff. AKA SQL Glitter Bombs. Research Analyst

Introduction to Database Systems CSE 344

Draft. Students Table. FName LName StudentID College Year. Justin Ennen Science Senior. Dan Bass Management Junior

PSUG National Information Exchange. Users helping users

SQL 2 (The SQL Sequel)

Oracle User Administration

Transcription:

CSC 337 Multi-table SQL Queries (Joins) Rick Mercer, Marty Stepp

Related tables and keys for Database simpsons id name email 123 Bart bart@fox.com 456 Milhouse milhouse@fox.com 888 Lisa lisa@fox.com 404 Ralph ralph@fox.com students id name 1234 Krabappel 5678 Hoover 9012 Obourn teachers id name teacher_id 10001 Computer Science 142 1234 10002 Computer Science 143 5678 10003 Computer Science 154 9012 10004 Informatics 100 1234 courses student_id course_id 123 10001 B- 123 10002 C 456 10001 B+ 888 10002 A+ 888 10003 A+ 404 10004 D+ grades Primary key: a column guaranteed to be unique for each record e.g. Lisa's ID 888 Foreign key: a column in table A storing a primary key value from table B (e.g. records in grades with student_id of 888 are Lisa's grades) Normalizing splitting tables to improve structure / redundancy (linked by unique IDs) grade

SQL Joins A SQL join is a Structured Query Language (SQL) instruction to combine data from two or more sets of data (two or more tables) There are several types of joins We'll use JOIN to selects records that have matching values in both tables Can match the primary key of one table with foreign key (s) in another table

General Form SELECT column-names FROM table-name1 JOIN table-name2 ON column-name1 = column-name2 WHERE condition JOIN combines records from 2 or more tables that satisfy certain conditions Creates a temporary table The ON clause specifies which records from each table are matched The rows are often linked by their key columns (id) The WHERE clause is optional

Easier to qualify table names SELECT table1.col2, table2.col2, table1.col3 FROM table1name JOIN table2name ON table1. col1 = table2. col1 WHERE condition Example SELECT students.name, grades.course_id, grades.grade FROM students JOIN grades ON students.id = grades.student_id WHERE students.name = 'Bart';

Filtered JOIN with ON and WHERE SELECT students.name, grades.course_id, grades.grade FROM students JOIN grades ON students.id = grades.student_id WHERE students.name = 'Bart'; +------+-----------+-------+ name course_id grade +------+-----------+-------+ Bart 10001 B- Bart 10002 C +------+-----------+-------+ FROM / JOIN glue tables together, WHERE filters results What goes in the ON clause, and what goes in WHERE? ON directly links columns of the joined tables WHERE sets additional constraints such as particular values (123, 'Bart')

Join Data from Two Tables select * from grades; +------------+-----------+-------+ student_id course_id grade +------------+-----------+-------+ 123 10001 B- 123 10002 C 456 10001 B+ 888 10002 A+ 888 10003 A+ 404 10004 D+ 404 10002 B 456 10002 D- +------------+-----------+-------+ SELECT column-names FROM table-name1 JOIN table-name2 ON column-name1 = column-name2 WHERE condition select * from students; +-----+----------+------------------+----------+ id name email password +-----+----------+------------------+----------+ 123 Bart bart@fox.com bartman 404 Ralph ralph@fox.com catfood 456 Milhouse milhouse@fox.com fallout 888 Lisa lisa@fox.com vegan +-----+----------+------------------+----------+ Let's get the student's names and grades where the grades are >= 'B' How many will there be? What is the 1st record stored in a new table?

Answer and result SELECT students.name, grades.grade FROM students JOIN grades ON students.id = grades.student_id WHERE grades.grade > 'B'; +----------+-------+ name grade +----------+-------+ Bart B- Bart C Ralph D+ Milhouse B+ Milhouse D- +----------+-------+

JOIN data in grades and courses select * from grades; +------------+-----------+-------+ student_id course_id grade +------------+-----------+-------+ 123 10001 B- 123 10002 C 456 10001 B+ 888 10002 A+ 888 10003 A+ 404 10004 D+ 404 10002 B 456 10002 D- +------------+-----------+-------+ SELECT column-names FROM table-name1 JOIN table-name2 ON column-name1 = column-name2 WHERE condition select * from courses; +-------+-----------------------+------------+ id name teacher_id +-------+-----------------------+------------+ 10001 Computer Science 142 1234 10002 Computer Science 143 5678 10003 Computer Science 190M 9012 10004 Informatics 100 1234 +-------+-----------------------+------------+ All grades for Computer Science 143 id is 10001 join data from tables courses and grades show grades.student_id courses.name and grades.grade

Answer and result SELECT courses.name, grades.grade, grades.student_id FROM courses JOIN grades ON courses.id = grades.course_id WHERE courses.id = '10001'; +----------------------+-------+------------+ name grade student_id +----------------------+-------+------------+ Computer Science 142 B- 123 Computer Science 142 B+ 456 +----------------------+-------+------------+ Can we switch the courses and grades tables?

WHERE is Optional select * from grades; +------------+-----------+-------+ student_id course_id grade +------------+-----------+-------+ 123 10001 B- 123 10002 C 456 10001 B+ 888 10002 A+ +------------+-----------+-------+ Get all grades for everyone SELECT * FROM grades JOIN students ON students.id = grades.student_id; select * from students; +-----+----------+------------------+----------+ id name email password +-----+----------+------------------+----------+ 123 Bart bart@fox.com bartman 404 Ralph ralph@fox.com catfood 456 Milhouse milhouse@fox.com fallout 888 Lisa lisa@fox.com vegan +-----+----------+------------------+----------+

Querying multi-table databases When we have larger datasets spread across multiple tables, we need queries that can answer high-level questions such as: What courses has Bart taken and gotten a B- or better? What courses have been taken by both Bart and Lisa? Who are all the teachers Bart has had? How many total students has Ms. Krabappel taught, and what are their names? To do this, we'll have to JOIN data from several tables Add more JOIN clauses

Multi-way join SELECT students.name, courses.name, grades.grade FROM courses JOIN grades ON grades.course_id = courses.id JOIN students ON grades.student_id = students.id WHERE grades.grade <= 'B-'; More than two tables can be joined Data from which tables are joined? What does the above query represent?

What MariaDB would look like MariaDB [simpsons]> SELECT students.name, courses.name, grades.grade FROM courses -> JOIN grades ON grades.course_id = courses.id -> JOIN students ON grades.student_id = students.id -> WHERE grades.grade <= 'B-'; +----------+-----------------------+-------+ name name grade +----------+-----------------------+-------+ Bart Computer Science 142 B- Ralph Computer Science 143 B Milhouse Computer Science 142 B+ Lisa Computer Science 143 A+ Lisa Computer Science 190M A+ +----------+-----------------------+-------+ 5 rows in set (0.00 sec)

Designing a query: Figure out the proper SQL queries in the following way: Which columns do I want in the result set? (SELECT) Which table(s) contain the critical data? (FROM) How are tables connected (JOIN) How are values filtered (WHERE)? Test on a real data base in MariaDB (imdb_small) Write the PHP code to run those same queries Fix all of those syntax errors

Our Lab 10 database: imdb id first_name last_name gender id name year rank actor_id movie_id role 433259 William Shatner M 112290 Fight Club 1999 8.5 433259 313398 Capt. James T. Kirk 797926 Britney Spears F 209658 Meet the Parents 2000 7 433259 407323 Sgt. T.J. Hooker 831289 Sigourney Weaver F 210511 Memento 2000 8.7 797926 342189 Herself actors movies roles movie_id genre id first_name last_name director_id movie_id 209658 Comedy 24758 David Fincher 24758 112290 313398 Action 66965 Jay Roach 66965 209658 313398 Sci-Fi 72723 William Shatner 72723 313398 movies_genres directors movies_directors

IMDb table relationships / ids

Our other database: imdb_small id first_name last_name gender id name year rank actor_id movie_id role 433259 William Shatner M 112290 Fight Club 1999 8.5 433259 313398 Capt. James T. Kirk 797926 Britney Spears F 209658 Meet the Parents 2000 7 433259 407323 Sgt. T.J. Hooker 831289 Sigourney Weaver F 210511 Memento 2000 8.7 797926 342189 Herself actors movies roles movie_id genre id first_name last_name director_id movie_id 209658 Comedy 24758 David Fincher 24758 112290 313398 Action 66965 Jay Roach 66965 209658 313398 Sci-Fi 72723 William Shatner 72723 313398 movies_genres directors movies_directors

Possible queries How many people played a part in the movie "Lost in Translation"? What are the names of all the people who played a part in the movie "Lost in Translation"? What are the names of all movies Clint Eastwood has directed? What are the names of every actor who has appeared in a movie directed by Christopher Nolan? Practice with Marty Stepp's CSE 154 Query Tester http://www.martystepp.com/query/?username=cse154&password=cse154 It can be a bit flaky