COMP102: Introduction to Databases, 5 & 6

Similar documents
Lecture 07. Spring 2018 Borough of Manhattan Community College

Chapter 6. SQL Data Manipulation

Standard Query Language. SQL: Data Definition Transparencies

3ISY402 DATABASE SYSTEMS

CMP-3440 Database Systems

Lecture 5 Data Definition Language (DDL)

COMP102: Introduction to Databases, 4

STRUCTURED QUERY LANGUAGE (SQL)

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

1) Introduction to SQL

Lecture 6 Structured Query Language (SQL)

SQL queries II. Set operations and joins

Database Management Systems,

RELATIONAL DATA MODEL

Lecture 06. Fall 2018 Borough of Manhattan Community College

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

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

DB Creation with SQL DDL

Database design process

COMP102: Introduction to Databases, 9.1

CS317 File and Database Systems

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Subquery: There are basically three types of subqueries are:

KORA. RDBMS Concepts II

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

Midterm Review. Winter Lecture 13

Intermediate SQL ( )

Database Technology. Topic 2: Relational Databases and SQL. Olaf Hartig.

Step 1: Create and Check ER Model

Cheltenham Courseware Microsoft Access 2003 Manual - Advanced Level SAMPLE

DATABASE TECHNOLOGY. Spring An introduction to database systems

Chapter 3: Introduction to SQL. Chapter 3: Introduction to SQL

The SQL database language Parts of the SQL language

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Basic SQL. Basic SQL. Basic SQL

COMP102: Introduction to Databases, 20

Database Technology. Topic 3: SQL. Olaf Hartig.

COMP102: Introduction to Databases, 14

DATABASE DESIGN I - 1DL300

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


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

CSC Web Programming. Introduction to SQL

Transforming ER to Relational Schema

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

Information Systems for Engineers. Exercise 10. ETH Zurich, Fall Semester Hand-out Due

Chapter 4. The Relational Model

DATABASE TECHNOLOGY - 1MB025

Joins, NULL, and Aggregation

A <column constraint> is a constraint that applies to a single column.

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

DATABASE TECHNOLOGY - 1MB025

Set Operations, Union

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Chapter 6. SQL: SubQueries

Database Modifications and Transactions

Chapter # 7 Introduction to Structured Query Language (SQL) Part II

Chapter 3: Introduction to SQL

SQL STRUCTURED QUERY LANGUAGE

SQL (Structured Query Language) Truong Tuan Anh CSE-HCMUT

Querying Data with Transact SQL

Intermediate SQL: Aggregated Data, Joins and Set Operators

Chapter 3: Introduction to SQL

An Introduction to Structured Query Language

An Introduction to Structured Query Language

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

An Introduction to Structured Query Language

An Introduction to Structured Query Language

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

Sql Server Syllabus. Overview

An Introduction to Structured Query Language

The SQL data-definition language (DDL) allows defining :

Full file at

Slides by: Ms. Shree Jaswal

Oracle Syllabus Course code-r10605 SQL

DATABASTEKNIK - 1DL116

SIT772 Database and Information Retrieval WEEK 6. RELATIONAL ALGEBRAS. The foundation of good database design

CS121 MIDTERM REVIEW. CS121: Relational Databases Fall 2017 Lecture 13

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

SQL (Structured Query Language)

SQL Data Manipulation Language. Lecture 5. Introduction to SQL language. Last updated: December 10, 2014

SQL - Subqueries and. Schema. Chapter 3.4 V4.0. Napier University

CMP-3440 Database Systems

Principles of Data Management

Introduction. Sample Database SQL-92. Sample Data. Sample Data. Chapter 6 Introduction to Structured Query Language (SQL)

SQL. Lecture 4 SQL. Basic Structure. The select Clause. The select Clause (Cont.) The select Clause (Cont.) Basic Structure.

Chapter 1 SQL and Data

UFCEKG 20 2 : Data, Schemas and Applications

Data about data is database Select correct option: True False Partially True None of the Above

CS317 File and Database Systems

Chapter 4: SQL. Basic Structure

1 Writing Basic SQL SELECT Statements 2 Restricting and Sorting Data

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Programming and Database Fundamentals for Data Scientists

Chapter 3. The Relational database design

Overview Relational data model

Relational Database Language

Information Systems Engineering. SQL Structured Query Language DML Data Manipulation (sub)language

Transcription:

COMP102: Introduction to Databases, 5 & 6 Dr Muhammad Sulaiman Khan Department of Computer Science University of Liverpool U.K. 8/11 February, 2011

Introduction: SQL, part 2

Specific topics for today: Retrieving data using SELECT, cntd. Inserting data using INSERT. Updating data using UPDATE. Deleting data using DELETE. Creating new tables using CREATE TABLE.

SELECT Statement: Aggregates ISO SQL defines five aggregate functions: COUNT: returns number of values in specified column. SUM: returns sum of values in specified column. AVG: returns average of values in specified column. MIN: returns smallest value in specified column. MAX: returns largest value in specified column.

SELECT Statement: Aggregates, cntd. Each operates on a single column of a table and returns a single value. COUNT, MIN, MAX apply to numeric/non-numeric fields. SUM and AVG apply only to numeric fields. Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values. COUNT(*) counts all rows of a table, regardless of whether nulls or duplicate values occur. Can use DISTINCT before column name to eliminate duplicates. DISTINCT has no effect with MIN/MAX, but may have with SUM/AVG.

SELECT Statement: Aggregates, cntd. Aggregate functions can be used only in SELECT list and in HAVING clause. If SELECT list includes an aggregate function and there is no GROUP BY clause, SELECT list cannot reference a column unless that column is the argument to an aggregate function. For example, the following is illegal: SELECT staffno, COUNT(salary) FROM Staff;

Query 3.11: Use of COUNT and SUM List total number of staff with salary > $ 40,000 and the sum of their salaries: SELECT COUNT(staffNo) AS totalstaff, SUM(salary) AS totalsalary FROM Staff WHERE salary > 40000;

Query 3.12: Use of MIN, MAX and AVG List the minimum, maximum, and average staff salary: SELECT MIN(salary) AS minsalary, MAX(salary) AS maxsalary, AVG(salary) AS avgsalary FROM Staff;

SELECT Statement: Grouping. Use GROUP BY clause to get sub-totals. GROUP BY produces a single summary row for each group. SELECT and GROUP BY closely integrated: each item in SELECT list must be single-valued per group, and SELECT clause may only contain: column names aggregate functions constants expression with combination of above. All column names in SELECT list must appear in GROUP BY clause unless used only in an aggregate function. Note: Not all column names in GROUP BY clause must appear in SELECT list. If used, WHERE is applied first, then groups are formed from remaining rows satisfying predicate. ISO considers two nulls to be equal for purposes of GROUP BY.

Query 3.13: Use of GROUP BY Find number of staff in each branch and sum of their salaries: SELECT branchno, COUNT(staffNo) AS totalstaff, SUM(salary) AS totalsalary FROM Staff GROUP BY branchno ORDER BY branchno;

Restricted Groupings: HAVING clause HAVING clause designed for use with GROUP BY to restrict groups that appear in final result table. Similar to WHERE, but WHERE filters individual rows whereas HAVING filters groups. Note: Aggregate functions cannot be used in the WHERE clause. Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function.

Query 3.14: Use of HAVING For each branch with more than 1 member of staff, find number of staff in each branch and sum of their salaries: SELECT branchno, COUNT(staffNo) AS totalstaff, SUM(salary) AS totalsalary FROM Staff GROUP BY branchno HAVING COUNT(staffNo) > 1 ORDER BY branchno;

Subqueries Some SQL statements can have a SELECT embedded within them. A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a subquery or nested query. Subselects may also appear in INSERT, UPDATE, and DELETE statements.

Query 3.15: Subquery with Equality Find staff who work in branch at Jefferson Way : SELECT staffno, name, position FROM Staff WHERE branchno = (SELECT branchno FROM Branch WHERE street = Jefferson Way ); Inner SELECT finds branch number for branch at 8 Jefferson Way ( B001 ). Outer SELECT then retrieves details of all staff who work at this branch. Outer SELECT then becomes: SELECT staffno, name, position FROM Staff WHERE branchno = B001 ;

Query 3.15: Result of the query

Query 3.16: Subquery with Aggregate List all staff whose salary is greater than the average salary: SELECT staffno, name, position FROM Staff WHERE salary > (SELECT AVG(salary) FROM Staff); Cannot write WHERE salary > AVG(salary) Instead, use subquery to find average salary (41166.67), and then use outer SELECT to find those staff with salary greater than this: SELECT staffno, name, position FROM Staff WHERE salary > 41166.67;

Query 3.16: Result of the query

Subquery Rules ORDER BY clause may not be used in a subquery (although it may be used in outermost SELECT). Subquery SELECT list must consist of a single column name or expression, except for subqueries that use EXISTS. By default, column names refer to table name in FROM clause of subquery. Can refer to a table in FROM using an alias. When subquery is an operand in a comparison, subquery must appear on right-hand side. A subquery may not be used as an operand in an expression.

More about Subqueries Some SQL statements can have a SELECT embedded within them. A subselect can be used in WHERE and HAVING clauses of an outer SELECT, where it is called a subquery or nested query. Subselect may also appear in the FROM clause, where it is paranthesized and given an alias. Subselects may also appear in INSERT, UPDATE, and DELETE statements.

Example: Subselect in FROM clause Consider the following schema: Movie(title, year, producercertno) StarsIn(movieTitle, movieyear, starname) MovieExec(name, address, certno) Find producers of Harrison Ford s movies: Method no. 1: SELECT name FROM MovieExec, Movie, StarsIn WHERE certno = producercertno AND title=movietitle AND year = movieyear AND starname = Harisson Ford ; Method no. 2 (subselect in FROM clause): SELECT name FROM MovieExec, ( SELECT producercertno FROM Movie, StarsIn WHERE title = movietitle AND year = movieyear AND starname = Harisson Ford ) Prod WHERE certno = Prod.producerCertNo;

Example: Correlated subquery Consider the same schema: Movie(title, year, producercertno) StarsIn(movieTitle, movieyear, starname) MovieExec(name, address, certno) Find movie title that appear more than once: SELECT title FROM Movie m WHERE year < ANY ( SELECT year FROM Movie WHERE title = m.title );

Multi-Table Queries Can use subqueries provided result columns come from same table. If result columns come from more than one table must use a join. To perform join, include more than one table in FROM clause. Use comma as separator with typically a WHERE to specify join column(s). Also possible to use an alias for a table named in FROM clause. Alias is separated from table name with a space. Alias can be used to qualify column names when there is ambiguity.

Query 3.17: Simple Join List all videos along with the name of the director: SELECT catalogno, title, category, v.directorno, directorname FROM Video v, Director d WHERE v.directorno = d.directorno; Only those rows from both tables with identical values in the directorno columns (v.directorno = d.directorno) included in result.

Alternative JOIN Constructs Note: In Query 3.17 we compared the foreign key, v.directorno, in table Video with the primary key, d.directorno, in table Director. Alternative ways to specify such join operation: FROM Video v JOIN Director d ON v.directorno = d.directorno FROM Video JOIN Director USING directorno FROM Video NATURAL JOIN Director Note: FROM replaces original FROM and WHERE. However, first produces table with two identical directorno columns.

Query 3.18: Four Table Join List all videos along with name of director and names of actors and their associated roles: SELECT v.catalogno, title, category, directorname, actorname, character FROM Video v, Director d, Actor a, Role r WHERE d.directorno = v.directorno AND v.catalogno = r.catalogno AND r.actorno = a.actorno;

INSERT, UPDATE and DELETE commands

INSERT INSERT INTO TableName [ ( columnlist ) ] VALUES ( datavaluelist ); columnlist is optional; if omitted, SQL assumes a list of all columns in their original CREATE TABLE order. Any columns omitted must have been declared as NULL or a DEFAULT was specified when table was created. datavaluelist must match columnlist as follows: Number of items in each list must be same. There must be direct correspondence in position of items in two lists. Data type of each item in datavaluelist must be compatible with data type of corresponding column.

Query 3.19: INSERT Insert a row into the Video table: INSERT INTO Video VALUES ( 207132, Die Another Day, Action, 5.00, 21.99, D1001 );

UPDATE UPDATE tablename SET columnname1=datavalue1 [,columnname2=datavalue2...] [WHERE searchcondition] tablename can be name of a base table or an updatable view. SET clause specifies names of one or more columns that are to be updated. WHERE clause is optional: If omitted, named columns are updated for all rows in table. If specified, only those rows that satisfy searchcondition are updated. New datavalue(s) must be compatible with data type for corresponding column.

Query 3.20: UPDATE Rows in a Table Modify the daily rental rate of videos in the Thriller category by 10%: UPDATE Video SET dailyrental = dailyrental * 1.1 WHERE category = Thriller ;

DELETE DELETE FROM tablename [WHERE searchcondition] tablename can be name of a base table or an updatable view. searchcondition is optional: If omitted, all rows are deleted from table. This does not delete table. If searchcondition specified, only those rows that satisfy condition are deleted.

Query 3.21: DELETE Specific Rows Delete rental videos for catalog number 634817: DELETE FROM VideoForRent WHERE catalogno = 634817 ;

Data Definition Language (DDL)

Two main SQL DDL statements: CREATE TABLE - to create a new table. CREATE VIEW - to create a new view.

CREATE TABLE Statement CREATE TABLE tablename ({columnname datatype [NOT NULL] [UNIQUE] [DEFAULT defaultoption] [,...] } [[CONSTRAINT constrname]primary KEY (listofcolumns),] {[UNIQUE (listofcolumns),] [...,]} {[[CONSTRAINT constrname]foreign KEY (listofforeignkeycolumns) REFERENCES ParentTableName [(listofcandkeycolumns)], [ON UPDATE referentialaction] [ON DELETE referentialaction]] [,...]});

Defining a column columnname datatype [NOT NULL] [UNIQUE] [DEFAULT defaultvalue] NOT NULL means the column cannot accept nulls; UNIQUE means that each value within this column will be unique (i.e., the column is a candidate key); DAFAULT specifies the default value for the column to be used if the value of the column is not specified. Supported data types of SQL are:

PRIMARY KEY and entity integrity Entity integrity supported by PRIMARY KEY clause. Example: We can define the primary keys for the tables Video and Role, respectively, as follows: CONSTRAINT pk PRIMARY KEY (catalogno) CONSTRAINT pk1 PRIMARY KEY (catalogno, actorno) CONSTRAINT constrname is optional, but allows the constraint to be dropped by the SQL statement ALTER TABLE: ALTER TABLE Video DROP CONSTRAINT pk

FOREIGN KEY and referential integrity FOREIGN KEY: defines any foreign keys in the table. SQL rejects any INSERT or UPDATE that attempts to create a FK value in child table without matching CK value in parent table. The action SQL takes for any UPDATE or DELETE that attempts to update or delete a CK value in the parent table with some matching rows in child table is dependent upon specified referential action. Referential actions with ON UPDATE and ON DELETE subclauses. Possible values are: CASCADE: Update/delete row from parent and automatically update/delete matching rows in child table, and so on in cascading manner. SET NULL: Update/delete row from parent and set FK values in child table to NULL. SET DEFAULT: Update/delete row from parent and set FK values in child table to specified default value. NO ACTION: Reject the update/delete.

About some data types CHARACTER(l) or CHAR(l): defines a string of fixed length l; entering shorter one causes padding the blanks on the right to make up the required length. CHARACTER VARYING(l) or VARCHAR(l): analogous to above, but strings can have length smaller than l (up to l). DECIMAL(a, b): number in specific format, i.e., a is the total number of decimal digits, and decimal point is b positions from the left. Example: 0324.56 is in DECIMAL(6,2). INTEGER, SMALLINT: defines integers; Typically SMALLINT is used to store integers with a maximum absolute value 32767. DATE: date stored a as a combination of YEAR (4 digits), MONTH (2 digits) and DAY (2 digits).

EXAMPLE: Creating table Branch CREATE TABLE Branch (branchno CHAR(4) NOT NULL, street VARCHAR(30) NOT NULL, city VARCHAR(20) NOT NULL, state VAR(2) NOT NULL, zipcode CHAR(5) NOT NULL UNIQUE, mgrstaffno CHAR(5) NOT NULL, CONSTRAINT pk1 PRIMARY KEY (branchno) CONSTRAINT fk1 FOREIGN KEY (mgrstaffno) REFERENCES Staff (staffno) ON UPDATE CASCADE ON DELETE NO ACTION);

CREATE VIEW Statement CREATE VIEW ViewName [(newcolumnname [,...])] AS Subselect Example: CREATE VIEW StaffBranch1 AS SELECT staffno, name, position FROM Staff WHERE branchno = B001 ;