SQL - Subqueries and Schema Chapter 3.4 V3.0 Napier University Dr Gordon Russell.

Slides:



Advertisements
Similar presentations
Data Definition and Integrity Constraints
Advertisements

Dr. Alexandra I. Cristea CS 252: Fundamentals of Relational Databases: SQL5.
SQL: The Query Language Part 1 R &G - Chapter 5 Life is just a bowl of queries. -Anon (not Forrest Gump)
Creating Tables. 2 home back first prev next last What Will I Learn? List and provide an example of each of the number, character, and date data types.
Fundamentals of Database Systems Fourth Edition El Masri & Navathe
SQL – Simple Queries Chapter 3.1 V3.0 Napier University Dr Gordon Russell.
SQL – JOINs and VIEWs Chapter 3.3 V3.0 Napier University Dr Gordon Russell.
Relational Database. Relational database: a set of relations Relation: made up of 2 parts: − Schema : specifies the name of relations, plus name and type.
Database Management Systems, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)MySQL Recap.
1 Lecture 11: Basic SQL, Integrity constraints
Relational Algebra 1 Chapter 5.1 V3.0 Napier University Dr Gordon Russell.
Triggers The different types of integrity constraints discussed so far provide a declarative mechanism to associate “simple” conditions with a table such.
A Guide to SQL, Seventh Edition. Objectives Create a new table from an existing table Change data using the UPDATE command Add new data using the INSERT.
Fundamentals, Design, and Implementation, 9/e COS 346 Day 11.
Introduction to Structured Query Language (SQL)
Introduction to Oracle9i: SQL1 Basic SQL SELECT Statements.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
ASP.NET Database Connectivity I. 2 © UW Business School, University of Washington 2004 Outline Database Concepts SQL ASP.NET Database Connectivity.
Fundamentals, Design, and Implementation, 9/e Chapter 6 Introduction to Structured Query Language (SQL)
Introduction to Structured Query Language (SQL)
Structured Query Language Chapter Three DAVID M. KROENKE’S DATABASE CONCEPTS, 2 nd Edition.
SQL – Logical Operators and aggregation Chapter 3.2 V3.0 Napier University Dr Gordon Russell.
Structured Query Language (SQL) A2 Teacher Up skilling LECTURE 2.
Relational DBs and SQL Designing Your Web Database (Ch. 8) → Creating and Working with a MySQL Database (Ch. 9, 10) 1.
1 IT420: Database Management and Organization SQL - Data Manipulation Language 27 January 2006 Adina Crăiniceanu
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor Ms. Arwa.
Introduction to Databases Chapter 7: Data Access and Manipulation.
ITBIS373 Database Development
Lecture6:Data Manipulation in SQL, Simple SQL queries Prepared by L. Nouf Almujally Ref. Chapter5 Lecture6 1.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
Dr Gordon Russell, Napier University Unit SQL 2 - V2.0 1 SQL 2 Unit 1.3.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
FALL 2004CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
7 1 Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Advanced SQL: Triggers & Assertions
1 SQL - II Data Constraints –Applying data constraints Types of data constraints –I/O constraints The PRIMARY KEY constraints The FOREIGN KEY constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
7 1 Constraints & Triggers Chapter Constraints and triggers? Constraints: Certain properties that the DBMS is required to enforce –E.g. primary.
Constraints and Triggers. What’s IC? Integrity Constraints define the valid states of SQL-data by constraining the values in the base tables. –Restrictions.
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.
Database UpdatestMyn1 Database Updates SQL is a complete data manipulation language that can be used for modifying the data in the database as well as.
CMPT 258 Database Systems The Relationship Model (Chapter 3)
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Database Management Systems Chapter 5 SQL.
© 2002 by Prentice Hall 1 Structured Query Language David M. Kroenke Database Concepts 1e Chapter 3 3.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Dr Gordon Russell, Napier University Unit SQL 3 - V2.0 1 SQL 3 Unit 1.4.
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
Chapter 3 The Relational Model. Why Study the Relational Model? Most widely used model. Vendors: IBM, Informix, Microsoft, Oracle, Sybase, etc. “Legacy.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 The Relational Model Chapter 3.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
CENG 351 File Structures and Data Management1 Relational Model Chapter 3.
Fundamentals of DBMS Notes-1.
SQL: Schema Definition and Constraints Chapter 6 week 6
Prepared by : Moshira M. Ali CS490 Coordinator Arab Open University
SQL Creating and Managing Tables
SQL Creating and Managing Tables
SQL Creating and Managing Tables
Creating Tables & Inserting Values Using SQL
Unit Relational Algebra 1
Presentation transcript:

SQL - Subqueries and Schema Chapter 3.4 V3.0 Napier University Dr Gordon Russell

Subqueries Subquery – one select statement inside another Used in the WHERE clause Subqueries can return many rows. Subqueries can only return 1 column. Used as a replacement for view or selfjoin. Some programmers see them as easier to understand than other options. The main drawback is that they can be much slower than selfjoin or view.

Simple Example Who in the database is older than Jim Smith? SELECT dob FROM driver WHERE name = Jim Smith ; SELECT name FROM driver WHERE dob > 11 Jan 1980 ; Dob 11 Jan 1980 name Bob Smith Bob Jones

Combined together: SELECT name FROM driver WHERE dob > (SELECT dob FROM driver WHERE name = Jim Smith ) ; This query will only work if there is only 1 Jim Smith.

ANY and ALL To support subqueries which return more than 1 row we need some additional operators … ANY and ALL. ANY – changes the rule so that it must be true for at least one of the rows returned from the subquery. ALL – changes the rule so that it must be true for each and every row returned from the subquery. The ANY or ALL operator goes immediately before the open bracket of the subquery.

Example 1 What cars are the same solour as a car owned by Jim Smith? Jim owns 2 cars, one is RED and the other BLUE. We are looking for cars which are either RED or BLUE. SELECT regno FROM car WHERE colour = ANY (SELECT colour FROM car WHERE owner = Jim Smith )

Example 2 List the drivers younger than all the people who own a blue car. We are looking for the age of drivers who own a BLUE car, and listing drivers who are younger than all of those ages. SELECT name,dob FROM driver WHERE dob < ALL ( SELECT dob FROM car JOIN driver ON (owner=name) WHERE colour = BLUE ) ;

IN and NOT IN We earlier saw IN working for sets like ( A, B ). A subquery itself returns its result as a set. Therefore we can use IN and NOT IN on subqueries. Question: Which cars are the same colour as one of Jim Smith s cars? SELECT regno FROM car WHERE colour IN (SELECT colour FROM car WHERE owner = Jim Smith ) ;

Example of NOT IN Question: Which cars DO NOT have the same colour as one of Jim Smith s cars? SELECT regno FROM car WHERE colour NOT IN (SELECT colour FROM car WHERE owner = Jim Smith ) ;

EXISTS If a question involves discovering uniqueness, then it can probably be easily solved using the operator EXISTS or NOT EXISTS. The EXISTS operator tests the result of running a subquery, and if any rows are returned it is TRUE, else it is FALSE. NOT EXISTS does the opposite of EXISTS. Note that subqueries can actually refer to tables defined outside the brackets which define the subquery. This is exceptionally useful, but can be slow to execute and confusing to look at.

Question: List the colours which are only used once in the database. SELECT colour FROM car a WHERE exists ( SELECT colour-- The row does not matter FROM car b-- unique name from a WHERE a.colour = b.colour-- Same colour as a AND a.regno != b.regno-- Different car from a );

UNION Sometimes you might write two or more queries which produce the same types of answer, and you want to combine the rows of these answers into a single result. UNION does this, and basically allows you to join different SELECT statement together. UNION automatically removes duplicate rows. For the next example, assume a row has been added to the DRIVER table for David Davis, but that he owns no cars. Question: List all drivers in the DRIVER table, together with how many cars they own.

SELECT name,count(*) FROM driver JOIN car on (name = owner) David Davis is missing, as he did not satisfy the JOIN condition. NAMECount(*) Jim Smith2 Bob Smith1 Bob Jones1

Write a query just for David Davis … SELECT name,0 FROM driver WHERE name NOT IN (select owner from car) NAME David Davis0

Link the two queries together: SELECT name,count(*) FROM driver JOIN car on (name = owner) UNION SELECT name,0 FROM driver WHERE name NOT IN (select owner from car) NAMECount(*) Jim Smith2 Bob Smith1 Bob Jones1 David Davis0

Changing Data We have looked so far at just SELECT There are some other useful operators too: –INSERT –DELETE –UPDATE

INSERT INSERT INTO table_name [(column_list)] VALUES (value_list) The column_list can be omitted if every column is to be assigned a value, otherwise it must list columns to be assigned values. The value_list is a set of literal values giving the value of each column in the same order as the column_list, if specified, or as the columns are defined in the original CREATE TABLE. insert into driver values ( Jessie James, 31 Nov 1892 ); insert into driver (name,dob) values ( John Johnstone, 1 Aug 1996 );

DELETE DELETE FROM table_name [WHERE condition]; the rows of table_name which satify the condition are deleted. Delete Examples: DELETE FROM car;-- Delete all rows from CAR ; DELETE FROM car WHERE owner is null-- Delete rows for cars without owners;

UPDATE UPDATE table_name SET column_name = expression,{column_name=expression} [WHERE condition] Set all BLUE cars to GREEN UPDATE car SET colour = GREEN WHERE colour = BLUE Add VAT/Purchase Tax at 17.5% to all prices UPDATE car SET price = price * 1.175

View Manipulation When is a view materialised or populated with rows of data? When it is defined or when it is accessed If it is the former then subsequent inserts, deletes and updates would not be visible. If the latter then changes will be seen. Some systems allow you to chose when views are materialised, most do not and views are materialised whenever they are accessed thus all changes can be seen.

VIEW update, insert and delete Can we change views? Yes, provided the primary key of all the base tables which make up the view are present in the view.

VIEW cont... This view cannot be changed because we have no means of knowing which row of B to modify

Controlling Schema All the commands so far have allowed data to be looked at, changes, added to, or removed. We also need commands to build, change, and remove table definitions. We call this schema changes. The useful commands to do this include: –CREATE TABLE –DROP TABLE –ALTER TABLE

CREATE TABLE Column types are needed to tell the DBMS what is allowed to be stored in each attribute column. A selection of types include: –INTEGER –REAL –DECIMAL : Including DECIMAL(5) and DECIMAL(4,2) –VARCHAR –CHAR : Pads out strings with spaces –DATE

SYNTAX CREATE TABLE tablename ( colname typeoptionalinfo,colname typeoptionalinfo,other optional info ); Optionalinfo could be things like –a INTEGER REFERENCES b(c) –PRIMARY KEY –NOT NULL

The other optional info at the end of the definition tend to be rules which impact on more than one attribute: –PRIMARY KEY (col1,col2, … ) –FOREIGN KEY (col1,col2, … ) REFERENCES othertable

CAR + DRIVER CREATE table driver ( namevarchar(30) PRIMARY KEY,dobdateNOT NULL ); CREATE TABLE car ( regnovarchar(8)PRIMARY KEY,makevarchar(20),colourvarchar(30),pricedecimal(8,2),ownervarchar(30)references driver(name) );

CAR + DRIVER Using Additional Info CREATE table driver ( namevarchar(30),dobdateNOT NULL,PRIMARY KEY (name) );

CAR + DRIVER Using Additional Info CREATE TABLE car ( regnovarchar(8),makevarchar(20),colourvarchar(30),pricedecimal(8,2),ownervarchar(30),FOREIGN KEY(owner)references driver(name),PRIMARY KEY(regno) );

DROP TABLE If you want to delete a table you use DROP TABLE. –DROP TABLE tablename The main difficulty with dropping a table is referential integrity. As CAR refers to DRIVER, you must delete CAR first then DRIVER. If you try to delete DRIVER first, the system would report an error. DROP TABLE car; DROP TABLE driver;

MODIFY TABLE To change a table which already exists you could use MODIFY TABLE. It is a complex command with many different options. A simple example of it would be adding an address field to the DRIVER table. ALTER TABLE driver ADD address varchar(50)

SELECT - Order of Evaluation SELECT [DISTINCT] column_name 5,6 eliminate unwanted data FROM label_list 1 Cartesian Product [WHERE condition ] 2 eliminate unwanted rows [GROUP BY column_list 3 group rows [HAVING condition ]] 4 eliminate unwanted groups [ORDER BY column_list[DESC]] 7 sort rows The last four components are optional.