Lecture Slides 4. SQL Summary. presented by Timothy Heron. Indexes. Creating an index. Mathematical functions, for single values and groups of values.



Similar documents
Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

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

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

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

3. Relational Model and Relational Algebra

Displaying Data from Multiple Tables

Oracle Database 10g: Introduction to SQL

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database 12c: Introduction to SQL Ed 1.1

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

Information Systems SQL. Nikolaj Popov

Oracle SQL. Course Summary. Duration. Objectives

Oracle Database: SQL and PL/SQL Fundamentals NEW

Where? Originating Table Employees Departments

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

Instant SQL Programming

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

Advance DBMS. Structured Query Language (SQL)

Programming with SQL


Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Querying Microsoft SQL Server

GET DATA FROM MULTIPLE TABLES QUESTIONS

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Oracle Database: SQL and PL/SQL Fundamentals

Database CIS 340. lab#6. I.Arwa Najdi

Displaying Data from Multiple Tables. Copyright 2006, Oracle. All rights reserved.

Relational Database: Additional Operations on Relations; SQL

Using SQL Queries to Insert, Update, Delete, and View Data: Joining Multiple Tables. Lesson C Objectives. Joining Multiple Tables

Course ID#: W 35 Hrs. Course Content

Introduction to database design

Querying Microsoft SQL Server 20461C; 5 days

Displaying Data from Multiple Tables. Copyright 2004, Oracle. All rights reserved.

Business Systems Analysis Certificate Program. Millennium Communications & Training Inc. 2013, All rights reserved

Relational Databases

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

Course 20461C: Querying Microsoft SQL Server Duration: 35 hours

Unit 3. Retrieving Data from Multiple Tables

SQL Server. 1. What is RDBMS?

IT2305 Database Systems I (Compulsory)

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

MOC QUERYING MICROSOFT SQL SERVER

Database Programming with PL/SQL: Learning Objectives

Databases 2011 The Relational Model and SQL

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

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Querying Microsoft SQL Server (20461) H8N61S

MOC 20461C: Querying Microsoft SQL Server. Course Overview

The Relational Algebra

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours

IT2304: Database Systems 1 (DBS 1)

Querying Microsoft SQL Server 2012

1 Structured Query Language: Again. 2 Joining Tables

Oracle 10g PL/SQL Training

Effective Use of SQL in SAS Programming

Course 10774A: Querying Microsoft SQL Server 2012

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

1. INTRODUCTION TO RDBMS

MySQL for Beginners Ed 3

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

How To Create A Table In Sql (Ahem)

In this Lecture SQL SELECT. Example Tables. SQL SELECT Overview. WHERE Clauses. DISTINCT and ALL SQL SELECT. For more information

SQL Query Evaluation. Winter Lecture 23

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

SQL (structured query language)

WRITING EFFICIENT SQL. By Selene Bainum

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT. COURSE CURRICULUM COURSE TITLE: DATABASE MANAGEMENT (Code: ) Information Technology

Querying Microsoft SQL Server 2012

SQL. Short introduction

- Eliminating redundant data - Ensuring data dependencies makes sense. ie:- data is stored logically

Database Query 1: SQL Basics

Relational Division and SQL

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

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

SQL JOINs and VIEWs. Chapter 3.3 V3.0. Napier University Dr Gordon Russell

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

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

SQL Programming. Student Workbook

Oracle Database 11g SQL

Structured Query Language (SQL)

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

14 Databases. Source: Foundations of Computer Science Cengage Learning. Objectives After studying this chapter, the student should be able to:

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

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

SQL SELECT Query: Intermediate

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

TIM 50 - Business Information Systems

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

Financial Data Access with SQL, Excel & VBA

Introduction to Querying & Reporting with SQL Server

Lecture 4: More SQL and Relational Algebra

CHAPTER 12. SQL Joins. Exam Objectives

Oracle Database 10g Express

DBMS / Business Intelligence, SQL Server

The process of database development. Logical model: relational DBMS. Relation

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

Introduction to Microsoft Jet SQL

Paper An Introduction to SAS PROC SQL Timothy J Harrington, Venturi Partners Consulting, Waukegan, Illinois

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

Transcription:

CS252: Fundamentals of Relational Databases 1 CS252: Fundamentals of Relational Databases Lecture Slides 4 presented by Timothy Heron SQL Summary Mathematical functions, for single values and groups of values. Storing dates and times in the database. Creating views with CREATE VIEW... AS. Creating tables from tables with CREATE TABLE... AS. This session Indexes, Sequences, Relational Algebra and Advanced Joins E-mail: theron@dcs.warwick.ac.uk CS252: Fundamentals of Relational Databases 2 CS252: Fundamentals of Relational Databases 3 Indexes Indexes are redundant data structures that improve the performance of a database. An index makes it faster for a database to look up a row based on a value within that row. An index has a storage overhead. Updates on a table that has an index can take than one that hasn t. It is best to only put indexes on columns that are often used for a search. They are not required for correctness, they do not affect the result returned by a query. An index is automatically added to any column declared as a Primary Key. Database implementations have their own specific indexing schemes and in some you can specify exactly what kind of index to use. Creating an index Creating indexes is not part of the SQL standard but nearly all databases support a common syntax. An index can be created on a single column : CREATE INDEX year index ON CD Year (year); This will improve performance on queries that look up year. e.g. : SELECT barcode FROM CD Year WHERE year = 1994;

CS252: Fundamentals of Relational Databases 4 CS252: Fundamentals of Relational Databases 5 Sequences Creating a multiple-key index An index can also be created on a multiple columns : CREATE INDEX index ON Pop albums (artist,album); This will improve performance on queries that look up both artist and album. e.g. : SELECT barcode FROM Pop albums WHERE artist= U2 AND album= Rattle and Hum ; Some databases support an Identity data type that is automatically populated with a unique reference number (URN). This kind of column is useful when creating surrogate keys (a key that is not derived from any data in the database and whose only purpose is to act as a primary key). For example MS Access and MS SQL Server both have an Identity data type and a GUID (Globally Unique IDentifier) data type. MySQL has an AUTO INCREMENT data type. Oracle does not have a data type like this, it has Sequences. CS252: Fundamentals of Relational Databases 6 CS252: Fundamentals of Relational Databases 7 Creating a Sequence To create a sequence that starts at 1 and increments by 1 use : CREATE SEQUENCE seq1; To create a sequence that starts at 10 and increments by 2 use : CREATE SEQUENCE seq2 INCREMENT BY 2 START WITH 10; To delete a sequence use : DROP SEQUENCE seq2; Using a Sequence CREATE TABLE test ( urn NUMBER, name VARCHAR(10) ); To insert a row where one of the columns should be an URN : INSERT INTO test VALUES (seq1.nextval, Tim );

CS252: Fundamentals of Relational Databases 8 CS252: Fundamentals of Relational Databases 9 Relational Algebra SQL manipulates tables. Relational operators are closed over these tables. The result of a relational operator on one or more tables is another table. There are five primitive operators in relational algebra union, difference, product, projection, selection. NB The SQL keyword SELECT is associated with projection, not selection! Also have derived operators (cf operators in arithmetic, such as square(x) x * x). Examples include intersection and join. Primitive Relational Operators The 5 primitive relational operators: union A B Combines all tuples from A and B. difference A \ B All tuples from A with those common to B (A B) removed. product A B Cartesian product of A and B. project A[a, b...] Select only attributes a, b... from relation A. select A : C Select only those tuples satisfying the specified boolean condition C, where C is constructed from arithmetic comparisons involving attributes by using propositional connectives. CS252: Fundamentals of Relational Databases 10 CS252: Fundamentals of Relational Databases 11 Derived Relational Operators intersection A B Common tuples to A and B. join A(A.a = B.b) JOIN B Join tables A and B together for each row match attribute A.a with B.b, discarding duplicate columns. Another example of a derived operator is divideby this attempts to invert product, in so far as this is possible. Codd s completeness criterion: a query language is complete if it can express each of the five primitive relational operators. Union A B Union Use SQL keyword UNION. Tables must be compatible... have the same attributes (column headings). (SELECT artist FROM Pop_albums WHERE artist LIKE U% ) UNION (SELECT artist FROM Band_members WHERE mbr1 = Grohl ); Result is a one column table containing three entries: Foo Fighters, U2 and Underworld.

CS252: Fundamentals of Relational Databases 12 CS252: Fundamentals of Relational Databases 13 Intersection A B Intersection Use SQL keyword INTERSECT. Tables must be compatible. Query selects U2 and Foo Fighters. (SELECT artist FROM Pop_albums) INTERSECT (SELECT artist FROM Band_members); Difference Use SQL keyword MINUS. Difference (SELECT artist FROM Pop_albums) MINUS (SELECT artist FROM Band_members); Selects everything but U2 and Foo Fighters The Verve and Underworld. CS252: Fundamentals of Relational Databases 14 CS252: Fundamentals of Relational Databases 15 Product Product A B Part of the SELECT statement list more than one table after keyword FROM. SELECT f1, f2 FROM Forward, Reverse; Forward f1 1 2 Reverse f2 2 1 F R f1 f2 1 2 2 2 1 1 2 1 Project Project A[a, b...] Using keyword SELECT as from day 1. SELECT a, b FROM A; SELECT artist, album FROM Pop albums;

CS252: Fundamentals of Relational Databases 16 CS252: Fundamentals of Relational Databases 17 Join A(A.a = B.b) JOIN B Using SELECT as in last seminar: Join SELECT artist, album, year FROM Pop_albums, CD_year WHERE Pop_albums.barcode = CD_year.barcode; SELECT a, b FROM A, B WHERE A.a = B.b; Notice how join is a combination of the product of tables and a predicate selection. Advanced Joins We covered a simple (equi-)join between two tables earlier in the course. Joins combine rows from two or more tables to create a single result. Columns are compared with a Join Condition. Pairs of rows each containing one row from each table are combined when the join condition evaluates to TRUE. CS252: Fundamentals of Relational Databases 18 CS252: Fundamentals of Relational Databases 19 Join Types Joins can be classified into the following categories : Cartesian Products Inner Joins (Equijoins) Self Joins Outer Joins (Left, Right and Full) Cartesian Products (Cross Join) If a join is performed without a Join Condition then the cartesian product of the specified tables is returned. Cartesian products can generate many rows of meaningless data, for this reason they are often used for creating test data. Apart from this they have few practical uses. Cartesian products form the base of all the other types of join.

CS252: Fundamentals of Relational Databases 20 CS252: Fundamentals of Relational Databases 21 The example from before : Inner Join Example Inner Joins (Equijoins) An Inner Join (or Equijoin) is a join with a condition that compares columns for equality (=). Rows are combined that have equal values in the specified columns. The order of the tables listed in the FROM clause has no significance. SELECT artist, album, year FROM Pop_albums, CD_year WHERE Pop_albums.barcode = CD_year.barcode; ARTIST ALBUM YEAR -------------- ------------------------------------ ----- U2 The Unforgettable Fire 1984 U2 Rattle and Hum 1988 U2 Achtung Baby 1991 Underworld Second Toughest in the Infants 1996 The Verve Urban Hymns 1997 Foo Fighters The Colour and the Shape 1997 CS252: Fundamentals of Relational Databases 22 CS252: Fundamentals of Relational Databases 23 Self Join Example Self Joins A Self Join is a join of a table to itself. Put the table in the FROM clause twice. Self joins are very useful. Use aliases to distinguish columns in the WHERE clause. Determine artists that have released more than one album : SELECT DISTINCT a.artist FROM Pop_albums a, Pop_albums b WHERE a.artist = b.artist AND a.album <> b.album; Can you think of alternative way of expressing this in SQL?

CS252: Fundamentals of Relational Databases 24 CS252: Fundamentals of Relational Databases 25 Hierachical Data Self-joins can be useful when working with hierachical data. Consider the following table (EMPLOYEES) : EMPLOYEEID SUPERVISORID NAME ---------- ------------ -------------- 100 NULL John Balfour 101 100 Susan Saronnen 102 100 Eric La Sold 103 100 Martin Murphy 104 103 Erica Strange 105 103 Noah Tamil How do we write a query to find the name of each employee s supervisor? We can use a self-join : SELECT staff.name,supervisor.name FROM EMPLOYEES staff, EMPLOYEES supervisor WHERE staff.supervisorid = supervisor.employeeid; STAFF.NAME SUPERVISOR.NAME -------------- --------------- Susan Saronnen John Balfour Eric La Sold John Balfour Martin Murphy John Balfour Erica Strange Martin Murphy Noah Tamil Martin Murphy CS252: Fundamentals of Relational Databases 26 CS252: Fundamentals of Relational Databases 27 Example data Outer Joins An Inner Join excludes rows from either table that don t have a matching row in the other table. An Outer Join allows us to return unmatched rows. Outer Joins come in three varieties : LEFT - only unmatched rows from the left table are kept RIGHT - only unmatched rows from the right table are kept FULL - unmatched rows from both tables are retained Imagine we have two tables defined as : CD company barcode company 042282289827 Island 042284229920 Island 731451034725 Island 026734000524 Junior 724384491321 Virgin 724385583223 Capital 724383719020 EMI 891030505032 Naxos

CS252: Fundamentals of Relational Databases 28 CS252: Fundamentals of Relational Databases 29 Pop albums barcode artist album 042282289827 U2 The Unforgettable Fire 042284229920 U2 Rattle and Hum 731451034725 U2 Achtung Baby 026734000524 Underworld Second Toughest in the Infants 724384491321 The Verve Urban Hymns 724385583223 Foo Fighters The Colour and the Shape 722323583123 Leftfield Leftism Notice not all companies match up to an album and not all albums match to a company. Outer Left Join Example SELECT company,artist,album FROM CD Company LEFT JOIN Pop albums ON Pop albums.barcode = CD Company.barcode; COMPANY ARTIST ALBUM ------- ------------ ------------------------------ Capital Foo Fighters The Colour and the Shape EMI Island U2 The Unforgettable Fire Island U2 Rattle and Hum Island U2 Achtung Baby Junior Underworld Second Toughest in the Infants Naxos Virgin The Verve Urban Hymns CS252: Fundamentals of Relational Databases 30 CS252: Fundamentals of Relational Databases 31 Outer Right Join Example SELECT year,artist FROM Pop albums RIGHT JOIN CD year ON Pop albums.barcode = CD year.barcode ORDER BY year; Produces a summary of record labels and the artists they publish. Notice that the record labels EMI and Naxos are displayed even though there are no albums with these companies in the Pop albums table. YEAR ARTIST ---- ------------ 1984 U2 1988 U2 1991 U2 1992 1996 Underworld 1996 1997 Foo Fighters 1997 The Verve

CS252: Fundamentals of Relational Databases 32 CS252: Fundamentals of Relational Databases 33 Outer Full Join Example SELECT company,artist,album FROM CD Company FULL JOIN Pop albums ON Pop albums.barcode = CD Company.barcode; COMPANY ARTIST ALBUM ------- ------------ ------------------------------ Island U2 The Unforgettable Fire Island U2 Rattle and Hum Island U2 Achtung Baby Junior Underworld Second Toughest in the Infants Virgin The Verve Urban Hymns Capital Foo Fighters The Colour and the Shape Naxos EMI Leftfield Leftism