CM2020: Introduction to Database Systems Queries In Relational Databases Database Systems 4 th edition Connolly and Begg Chapter 5 Dr Nirmalie Wiratunga.

Slides:



Advertisements
Similar presentations
SQL – Lesson II Grade 12.
Advertisements

Advanced SQL Topics Edward Wu.
Structured Query Language (SQL)
Database Queries and Structured Query Language (SQL) J.G. Zheng May 16 th 2008.
Data Definition and Integrity Constraints
© Abdou Illia MIS Spring 2014
Database Systems: Design, Implementation, and Management Tenth Edition
Copyright © by Royal Institute of Information Technology Introduction To Structured Query Language (SQL) 1.
Introduction to Structured Query Language (SQL)
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
© 2002 by Prentice Hall 1 David M. Kroenke Database Processing Eighth Edition Chapter 9 Structured Query Language.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
1 Introduction to Web Application Introduction to Data Base.
Structured Query Language Part I Chapter Three CIS 218.
Structured Query Language Chapter Three (Excerpts) DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
Concepts of Database Management Sixth Edition
A Guide to SQL, Seventh Edition. Objectives Retrieve data from a database using SQL commands Use compound conditions Use computed columns Use the SQL.
Microsoft Access 2010 Chapter 7 Using SQL.
Chapter 7: SQL, the Structured Query Language Soid Quintero & Ervi Bongso CS157B.
SQL Operations Aggregate Functions Having Clause Database Access Layer A2 Teacher Up skilling LECTURE 5.
Introduction to SQL J.-S. Chou Assistant Professor.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
Chapter 3 Single-Table Queries
2440: 141 Web Site Administration Database Management Using SQL Professor: Enoch E. Damson.
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
Fundamentals, Design, and Implementation, 9/e CPE 481 Database Processing Chapter 6 Structured Query Language (SQL) Instructor:Suthep Madarasmi, Ph.D.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
Using Special Operators (LIKE and IN)
Concepts of Database Management Seventh Edition
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
BY SATHISH SQL Basic. Introduction The language Structured English Query Language (SEQUEL) was developed by IBM Corporation, Inc., to use Codd's model.
Database Processing: Fundamentals, Design, and Implementation, 9/e by David M. KroenkeChapter 6/1 Copyright © 2004 Please……. No Food Or Drink in the class.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Chapter 8: SQL. Data Definition Modification of the Database Basic Query Structure Aggregate Functions.
Concepts of Database Management Eighth Edition Chapter 3 The Relational Model 2: SQL.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
1 DBS201: Introduction to Structure Query Language (SQL) Lecture 1.
Database Management COP4540, SCS, FIU Structured Query Language (Chapter 8)
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 7 Introduction to Structured Query Language (SQL)
DBSQL 5-1 Copyright © Genetic Computer School 2009 Chapter 5 Structured Query Language.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
ITEC 3220A Using and Designing Database Systems Instructor: Prof. Z. Yang Course Website: 3220a.htm
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
April 2002 Information Systems Design John Ogden & John Wordsworth 1 Database Design SQL (1) John Wordsworth Department of Computer Science The University.
1 Chapter 3 Single Table Queries. 2 Simple Queries Query - a question represented in a way that the DBMS can understand Basic format SELECT-FROM Optional.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL: Structured Query Language It enables to create and operate on relational databases, which are sets of related information stored in tables. It is.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL: Interactive Queries (2) Prof. Weining Zhang Cs.utsa.edu.
Concepts of Database Management, Fifth Edition Chapter 3: The Relational Model 2: SQL.
SQL Query Getting to the data ……..
Chapter 3 Introduction to SQL(3)
SQL FUNDAMENTALS CDSE Days 2018.
Prof: Dr. Shu-Ching Chen TA: Yimin Yang
Prof: Dr. Shu-Ching Chen TA: Hsin-Yu Ha
Chapter # 7 Introduction to Structured Query Language (SQL) Part II.
Prof: Dr. Shu-Ching Chen TA: Haiman Tian
Access: SQL Participation Project
Chapter 7 Introduction to Structured Query Language (SQL)
Presentation transcript:

CM2020: Introduction to Database Systems Queries In Relational Databases Database Systems 4 th edition Connolly and Begg Chapter 5 Dr Nirmalie Wiratunga

Tutorials and Labs Jointly organised with Dr Robin Boswell and Hatem Ahriz Tutorials: Tuesdays 2-3pm –A (Robin): C39/39a SAS (CS2, CIM2) –B (Nirmalie): C411 Schoolhill (BIS2, MMD3, CIMD3) –C (Hatem):B40 SAS (ISTD2, ISTD3, CGA2) Labs: Tuesday 3-5pm –A (Nirmalie): C18 SAS (CS2, CIM2) –B (Hatem): C24 SAS (BIS2, MMD3, CIMD3) –C (Robin): C26 St Andrew street (ISTD2, ISTD3, CGA2)

Last week … student# name address age course 100 Bobby Dundee 17 C Helen Aberdeen 21 C Helen Stirling 18 C Freddy Perth 30 C300 course# course_name location C100 Computing St Andrews St C200 Pharmacy Schoolhill C300 Architecture Garthdee Relational Databases (DB)s Consists of relations or tables Tables consists of rows and columns Primary Key uniquely identifies each row Composite primary keys are allowed and formed by combining multiple columns Foreign key is an attribute / set of attributes, within one relation that matches the primary key of another relation Table: Students Table: Courses

SQL Structured Query Language (SQL) Data Manipulation Language –SELECT Single table Multi table –MS Access (Query by Example) –GROUP BY with SELECT –INSERT, UPDATE, DELETE Data Definition Language –CREATE TABLE, DROP TABLE, ALTER TABLE

Querying allows retrieval of data in response to a question about the data in the DB Relational DBMSs translates queries into SQL (a.k.a Structured Query Language or SEQUEL) SQLs SELECT construct –extracts data from the tables of the database –allows specification of conditions –does not facilitate modification to the tables or the data contained in tables Querying with SELECT

SELECT SELECT {* | [column1 [AS newName]] [,column2, …]} [ALL | DISTINCT] FROM table1 [alias] [, table2,…] [WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions"] [ORDER BY "column-list" [ASC | DESC] ]; Everything within [ ] is optional Standard syntax is: ; denotes end of SELECT statement

Single-Table Select Queries Drivers driver# name address points D010 FredPerth7 D020 Jimmy Dundee4 D030 DavidDundee2 D040 JohnStirling3 D050 BobbyAberdeen12 The result of a query is another table - this table is not permanent - this table is called a DYNASET (a.k.a Dynamic Data Set) in Microsoft Access

SELECT Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List all the ids (driver#) from the Drivers table. SELECT driver# FROM Drivers; driver# D010 D020 D030 D040 D050 SELECT driver#

SELECT cont Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List all the ids (driver#) and points from the Drivers table SELECT driver#, points FROM Drivers; driver# points D010 7 D020 4 D030 2 D040 3 D SELECT driver#, points We use commas to separate fields

SELECT with Wildcards SELECT * FROM Drivers; Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List all the details (i.e. all the fields) from the Drivers table SELECT * We use * for all fields

SELECT with WHERE Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List all the ids (driver#) of the drivers from Dundee from the Drivers table SELECT driver# FROM Drivers WHERE address = Dundee; driver# D020 D030 SELECT driver# WHERE address = Dundee;

Extending SELECT We can extend SELECT in a number of ways: 1. Can pattern match within certain fields of a table - can use the LIKE clause 2. Can check if a field has a value from a set of values - can use the IN operator 3. Can perform calculations on values in a table - can use COLUMN FUNCTIONS 4. Can make your queries have a choice or be more specific - can use the OR and AND clauses 5. Can sort output of a query into ascending/descending order - can use the ORDER BY clause

The LIKE clause Sometimes we may want to pattern match within certain fields of a table ?matches a single characterLike Sm?th *matches any number of characters Like St* #matches a single digit [0-9]Like D0#0 [list]matches any character in listLike [A-F]* [!list]matches any character not in list Like [!A-F]*

SELECT LIKE Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List all the names and addresses of the drivers whose address begins with the letters Du from the Drivers table SELECT name, address FROM Drivers WHERE address Like Du*; name address jimmy Dundee David Dundee SELECT name, address WHERE address Like Du*;

The IN Operator Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 The IN operator is used to check if an attribute(s) has a value from a set of values [NOT] IN ( ) name Jimmy David Bobby Syntax is: a) List the names of drivers from Dundee or Aberdeen SELECT name FROM Drivers WHERE address IN (Dundee, Aberdeen); b) List the names of drivers not from Dundee or Aberdeen SELECT name FROM Drivers WHERE address NOT IN (Dundee, Aberdeen); name Fred John

Column / Aggregate Functions Column functions perform calculations on the values in the column of a table COUNT - calculates the number of values in a column SUM - calculates the sum (total) of all values in a column AVG - calculates the average of all values in a column MAX - calculates the maximum value in a column MIN - calculates the minimum value in a column

SELECT with Aggregates Drivers driver# name address points D010 Fred Perth 7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: Calculate the number of drivers, the total number of points, the average number of points, the maximum points value and the range of points from the Driver SELECT COUNT(driver#), SUM(points), AVG(points), MAX(points), MIN(points), MAX(points) - MIN(points) FROM Drivers; COUNT(driver#) SUM(points) AVG(points) MAX(points) MIN(points) MAX(points) - MIN(points)

SELECT with ORDER BY Drivers driver# name address points D010 Fred Perth 7 D020 Bobby Dundee 4 D030 David Dundee2 D040 John Stirling 3 D050 Jimmy Aberdeen 12 List in alphabetical order, names of drivers with a Dundee or Aberdeen address SELECT name FROM Drivers WHERE address IN (Dundee, Aberdeen) ORDER BY name; name Bobby David Jimmy NOTE: Default is ascending SELECT name IN (Dundee, Aberdeen);

SELECT with ORDER BY List in reverse alphabetical order, names of drivers with a Dundee or Aberdeen address SELECT name FROM Drivers WHERE address IN (Dundee, Aberdeen) ORDER BY name DESC; name Jimmy David Bobby Drivers driver# name address points D010 Fred Perth 7 D020 Bobby Dundee 4 D030 David Dundee2 D040 John Stirling 3 D050 Jimmy Aberdeen 12 IN (Dundee, Aberdeen); SELECT name DESC means descending

Complex Conditions with WHERE Mathematical operators –=,, <>, = Logical operators AND, OR, NOT

Combining Operators AND Drivers driver# name address points D010 Fred Perth7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List the names of drivers whose licence points are between 4 and 15 from the Drivers table and not from Dundee SELECT name FROM Drivers WHERE points >= 4 AND points <= 15 AND (address <> Dundee'); name Fred Bobby SELECT name WHERE points >= 4 AND points <= 15 AND (address <> Dundee);

Drivers driver# name address points D010 Fred Perth7 D020 Jimmy Dundee 4 D030 David Dundee 2 D040 John Stirling 3 D050 Bobby Aberdeen 12 EXAMPLE: List the names of drivers with addresses from either Aberdeen or Dundee SELECT name FROM Drivers WHERE (address LIKE D*') OR (address LIKE A*'); name Jimmy David Bobby SELECT name WHERE (address LIKE D*) OR (address LIKE A*) Combining Operators OR

Mathematical Operators supports the following –+, -, *, / (division), % (modulo) item# qtyprice Shoes220 Raft160 Skateboard1020 Life Vest15 SELECT item, qty*price AS TotalCost FROM Items_ordered; item# TotalCost Shoes40 Raft60 Skateboard200 Life Vest5 Items_ordered Use AS to specify new column name

Summary: Single Table Queries Queries may be created in a DBMS using SQL SELECT statement The basic ANSI syntax is: SELECT FROM [ WHERE ] ; Can pattern match within certain fields of a table - LIKE clause Can check if a field has a value from a set of values - IN operator Can perform calculations on values in a table - COLUMN FUNCTIONS Can make your queries have a choice or be more specific - OR and AND clauses Can sort output of a query into ascending/descending order - ORDER BY clause

Multi-Table Queries Commonly require data from more than one table Involves JOINING tables to form a SUPERTABLE Table JOINS –PRODUCT or CARTESIAN –INNER JOIN or EQUI JOIN –NATURAL JOIN –OUTER JOIN (LEFT and RIGHT)

Multi-Table Select Queries List data on all orders including customer names and addresses Customers cust# name address C100AllanAberdeen C101JohnDundee C102BettyStirling C200 Dean Dundee Orders order# cust# date 2000 C100 20/11/ C101 27/11/ C100 30/11/01

Product Join forms every possible combination of rows combining all columns E.g Customer PRODUCT Order C.cust# nameaddress order# O.cust# date C100AllanAberdeen 2000 C100 20/11/01 C101JohnDundee 2000 C100 20/11/01 C102BettyStirling 2000 C100 20/11/01 C200 Dean Dundee 2000 C100 20/11/01 C100AllanAberdeen 3000 C101 27/11/95 etc SELECT * FROM Customer, Order;

Inner Join (or Equi-Join) 1.Apply a product join 2.Retrieve rows with matching linked attribute values E.g Customer INNER JOIN Order C.cust# name address order# O.cust# date C100 AllanAberdeen 2000 C100 20/11/01 C101 John Dundee 3000 C101 27/11/01 C100 AllanAberdeen 4000 C100 30/11/01 SELECT * FROM Customer C, Order O WHERE C.cust# = O.cust#; Inner join is a more useful kind of join for data retrieval Use of alias. Can also use AS here. E.g. Order AS O

Natural Join C.cust# name address order# date C100 AllanAberdeen /11/01 C101 John Dundee /11/01 C100 AllanAberdeen /11/01 SELECT C.cust, name, address, order#, date FROM Customer C, Order O WHERE C.cust# = O.cust#; Similar to Inner join but with a single matching attribute e.g. no O.cust#

Queries on joined tables cust# name address order# date C101 John Dundee /11/01 C100 Allan Aberdeen /11/01 SELECT C.cust#, name, order#, date FROM Customer AS C, Order AS O WHERE Customer.cust# = Orders.cust# AND date > 25/11/01;

OUTER JOIN Use when we want to see the details from unmatched rows as well –columns of the output corresponding to unavailable data are set to null Right Outer JOIN –E.g. Not all customers have placed orders in the Orders table Left Outer Join

rows in the 1 st table with unmatched rows in the 2 nd table are still included with NULL values E.g Customer LEFT OUTER JOIN Order cust#nameaddress order# date C100AllanAberdeen /11/01 C101JohnDundee /11/01 C100 AllanAberdeen /11/01 C102BettyStirling NULL NULL C200Dean Dundee NULL NULL SELECT Customer.cust#, name, order#, date FROM Customer LEFT JOIN order ON Customer.cust# = Orders.cust#;

Summary Multi-Table Joins It is possible to join as many tables as you want –generally for n tables n-1 joins Inner Join (and Natural join) is most common –outer joins will display unmatched rows

Query Processor Extracts required information from database How? –Structured Query Language (SQL) –Query by Example (QBE) Querying without having to know SQL

QBE with MS Access E.g. Inner Join

MS Access SQL View Functionally Similar

SQL - Next Structured Query Language (SQL) Data Manipulation Language –SELECT Single table Multi table –MS Access (Query by Example) –GROUP BY with SELECT –INSERT, UPDATE, DELETE Data Definition Language –CREATE TABLE, DROP TABLE, ALTER TABLE

Grouping Results Useful to summarise results Closely integrated with SELECT –Specify column names –Aggregate functions e.g. count, avg, sum, max, min –WHERE conditions –Any combination of the above All columns names in the SELECT must appear in the GROUP BY –HAVING clause used to specify conditions on groups of rows

GROUP BY ANSI syntax is: All select columns Must appear here Specify conditions applicable to groups SELECT {* | [column1 [AS newName]] [,column2, …]} [ALL | DISTINCT] FROM table1 [alias] [, table2,…] [WHERE "conditions"] [GROUP BY "column-list"] [HAVING "conditions"] [ORDER BY "column-list" [ASC | DESC] ];

Group By Clause Example Given the following table: Employees NI_no name addresssalary NS Fred Aberdeen15,000 NS Bobby Dundee20,000 NS Dave Aberdeen12,000 NS Steve Stirling10,000 NS Betty Dundee25,000 Show, for each address, the number of employees that live there SELECT address, count(NI_no) FROM Employees GROUP BY address; Address count(NI_no) Aberdeen2 Dundee2 Stirling1

Group By Clause Example In order to do the previous query, an intermediate table is created that is group by (sorted on) address i.e.: Employees NI_no nameaddress salary NS FredAberdeen 15,000 NS DaveAberdeen 12,000 NS BobbyDundee 20,000 NS BettyDundee 25,000 NS SteveStirling 10,000 We perform count(NI_no) for each of the 3 groupings grouping 1 grouping 2 grouping 3

Given the following table: Employees NI_no name addresssalary NS Fred Aberdeen15,000 NS Bobby Dundee20,000 NS Dave Aberdeen12,000 NS Steve Stirling10,000 NS Betty Dundee25,000 Show the addresses whose employees average salary is greater than £21,000. Also show the average salary. SELECT address, avg(salary) FROM Employees GROUP BY address HAVING avg(salary) > 12000; address avg(salary) Aberdeen Dundee NOTE: compare with intermediate table from previous slide GROUP BY with Having