© Pearson Education Limited, 20041 Chapter 3 SQL and QBE Transparencies.

Slides:



Advertisements
Similar presentations
CSC271 Database Systems Lecture # 11.
Advertisements

Chapter 6 SQL: Data Manipulation Pearson Education © 2009.
CSC271 Database Systems Lecture # 13. Summary: Previous Lecture  Grouping through GROUP BY clause  Restricted groupings  Subqueries  Multi-Table queries.
Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Introduction to Structured Query Language (SQL)
Session 4 SQL Structured Query Language. SQL Modes of use –Interactive –Embedded Purpose –Create database –Create, Read, Update, Delete.
1 Minggu 4, Pertemuan 8 SQL: Data Manipulation (Cont.) Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Introduction to Structured Query Language (SQL)
Chapter 6 SQL: Data Manipulation. 2 Objectives of SQL u Database language should allow user to: –create database and relation structures –perform insertion,
Introduction to Structured Query Language (SQL)
Chapter 6 SQL: Data Manipulation Cont’d. 2 ANY and ALL u ANY and ALL used with subqueries that produce single column of numbers u ALL –Condition only.
1 Minggu 4, Pertemuan 7 SQL: Data Manipulation Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Microsoft Access 2010 Chapter 7 Using SQL.
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
Agenda TMA01 M876 Block 3 – Using SQL Structured Query Language - SQL A non-procedural language to –Create database and relation structures. –Perform.
Data Manipulation Using MySQL tMyn1 Data Manipulation Using MySQL Ideally, a database language should allow a user to: –Create the database and relation.
SQL: Overview SQL Overview © Pearson Education Limited 1995, 2005.
Database Systems: A Practical Approach to Design, Implementation and Management International Computer Science S. Carolyn Begg, Thomas Connolly Lecture.
10/15/2012ISC239 Isabelle Bichindaritz1 SQL Queries.
CSC271 Database Systems Lecture # 12. Summary: Previous Lecture  Row selection using WHERE clause  WHERE clause and search conditions  Sorting results.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
Chapter 7 Introduction to SQL(Wk11_12) © Pearson Education Limited 1995, 2005.
Chapter 5: Part 1: DDL STRUCTURED QUERY LANGUAGE (SQL)
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
Chapter 5 SQL: Data Manipulation © Pearson Education Limited 1995, 2005.
SQL: Data Manipulation I Chapter 5 CIS 458 Sungchul Hong.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
Chapter 5 SQL: Data Manipulation. 2 Chapter - Objectives u Purpose and importance of SQL. u How to retrieve data from database using SELECT and: –Use.
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.
Chapter 7 SQL: Data Manipulation Chapter #6 in the textbook Pearson Education © 2009.
Chapter 7 SQL: Data Definition Pearson Education © 2009.
Chapter Name SQL: Data Definition
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
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.
ITS232 Introduction To Database Management Systems Siti Nurbaya Ismail Faculty of Computer Science & Mathematics, Universiti Teknologi MARA (UiTM), Kedah.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
Chapter 6 SQL – Data Manipulation Pearson Education © 2014.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
SQL and QBE Transparencies. ©Pearson Education 2009 Chapter 3 - Objectives Purpose and importance of SQL, the main language for querying relational databases.
Chapter 2 The Relational Model. 2-2 In This Chapter You Will Learn   What a data model is and what its uses are   The terminology of the relational.
SQL: Data Manipulation. Objectives Describe the purpose and importance of SQL. Demonstrate how to retrieve data from database using SELECT and: ▫Use compound.
LM 5 Introduction to SQL MISM 4135 Instructor: Dr. Lei Li.
SQL: Additional Notes. 2 Example 5.3 Use of DISTINCT List the property numbers of all properties that have been viewed. SELECT propertyNo FROM Viewing;
Chapter 6 SQL: Data Manipulation Pearson Education © 2009.
Lecture 11 SQL. Agenda SQL Select statement WHERE clause BindingSource filtering.
Teacher Workshop Database Design Pearson Education © 2014.
Chapter 11 SQL: Data Manipulation
國立臺北科技大學 課程:資料庫系統 Chapter 7 SQL Data Definition.
REV 00 Chapter 4 SQL and QBE DDC 2483 – Database Systems.
Chapter Name SQL: Data Manipulation
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
Chapter Name SQL: Data Manipulation
SQL – Data Manipulation
Introduction to SQL Chapter 3.
Chapter Name SQL: Data Manipulation Chapter #6 in the textbook
© Pearson Education Limited, 2004
Chapter Name SQL: Data Manipulation Chapter #6 in the textbook
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation Transparencies
Chapter Name SQL: Data Manipulation Transparencies
Chapter Name SQL: Data Manipulation
Presentation transcript:

© Pearson Education Limited, Chapter 3 SQL and QBE Transparencies

© Pearson Education Limited, Chapter 3 - Objectives Purpose and importance of SQL. How to retrieve data using SELECT. How to insert data using INSERT. How to update data using UPDATE. How to delete data using DELETE. How to create new tables using CREATE TABLE. About an alternative language, QBE.

© Pearson Education Limited, SQL Main language for relational DBMSs. Main characteristics: relatively easy to learn; non-procedural - you specify what information you require, rather than how to get it; essentially free-format; consists of standard English words like SELECT, INSERT, and UPDATE; can be used by range of users.

© Pearson Education Limited, Importance of SQL First and, so far, only standard database language to gain widespread acceptance. Huge investment from both vendors and users. Federal Information Processing Standard (FIPS). Used as the basis for other standards.

© Pearson Education Limited, Objectives of SQL Ideally database language should let user: create database and table structures. perform basic tasks like insert, update, delete; perform both simple and complex queries. Must perform these tasks with minimal user effort. Must be easy to learn.

© Pearson Education Limited, Objectives of SQL SQL is a transform-oriented language with 2 major components: a DDL for defining database structure; a DML for retrieving and updating data. Until SQL3, SQL did not contain flow of control commands (not computationally complete). SQL can be used interactively or embedded in a high-level language (eg. C, C++).

© Pearson Education Limited, Writing SQL Commands SQL statement consists of reserved words and user-defined words. – Reserved words: fixed part of SQL and must be spelt exactly as required and cannot be split across lines. – User-defined words: made up by user and represent names of various database objects such as tables, columns, views.

© Pearson Education Limited, Writing SQL Commands Most components of an SQL statement are case insensitive, except for literal character data. Use extended form of BNF notation: - Upper-case letters represent reserved words. - Lower-case letters represent user-defined words. - | indicates a choice among alternatives. - Curly braces indicate a required element. - Square brackets indicate an optional element. - … indicates optional repetition (0 or more).

© Pearson Education Limited, Literals Literals are constants used in SQL statements. All non-numeric literals must be enclosed in single quotes (eg. ‘London’). All numeric literals must not be enclosed in quotes (eg ).

© Pearson Education Limited, SELECT Statement SELECT [DISTINCT | ALL] {* | [columnExprn [AS newName]] [,...] } FROM TableName [alias] [,...] [WHERE condition] [GROUP BY columnList] [HAVINGcondition] [ORDER BYcolumnList]

© Pearson Education Limited, SELECT Statement FROMSpecifies table(s) to be used. WHEREFilters rows. GROUP BYForms groups of rows with same column value. HAVINGFilters groups subject to some condition. SELECTSpecifies which columns are to appear in output. ORDER BY Specifies the order of the output.

© Pearson Education Limited, SELECT Statement Order of the clauses cannot be changed. Only SELECT and FROM are mandatory.

© Pearson Education Limited, All Columns, All Rows List full details of all videos. SELECT catalogNo, title, category, dailyRental, price, directorNo FROM Video; Can use * as an abbreviation for ‘all columns’: SELECT * FROM Video;

© Pearson Education Limited, All Columns, All Rows

© Pearson Education Limited, Specific Columns, All Rows List the catalog number, title and daily rental rate of all videos. SELECT catalogNo, title, dailyRental FROM Video;

© Pearson Education Limited, Specific Columns, All Rows

© Pearson Education Limited, Use of DISTINCT List all video categories. SELECT category FROM Video;

© Pearson Education Limited, Use of DISTINCT Use DISTINCT to eliminate duplicates: SELECT DISTINCT category FROM Video;

© Pearson Education Limited, Calculated Fields List rate for renting videos for 3 days. SELECT catalogNo, title, dailyRental*3 FROM Video;

© Pearson Education Limited, Calculated Fields To name column, use AS clause: SELECT catalogNo, title, dailyRental*3 AS threeDayRate FROM Video;

© Pearson Education Limited, Comparison Search Condition List all staff with a salary greater than $10,000. SELECT staffNo, name, position, salary FROM Staff WHERE salary > 10000;

© Pearson Education Limited, Range Search Condition List all staff with a salary between $45,000 and $50,000. SELECT staffNo, name, position, salary FROM Staff WHERE salary BETWEEN AND 50000; BETWEEN test includes the endpoints of range.

© Pearson Education Limited, Range Search Condition

© Pearson Education Limited, Range Search Condition Also a negated version NOT BETWEEN. BETWEEN does not add much to SQL’s expressive power. Could also write: SELECT staffNo, name, position, salary FROM Staff WHERE salary >= AND salary <= 50000; Useful, though, for a range of values.

© Pearson Education Limited, Set Membership List all videos in the Action and Children categories. SELECT catalogNo, title, category FROM Video WHERE category IN (‘Action’, ‘Children’);

© Pearson Education Limited, Set Membership There is a negated version (NOT IN). IN does not add much to SQL’s expressive power. Could have expressed this as: SELECT catalogNo, title, category FROM Video WHERE category =‘Action’ OR category =‘Children’ IN is more efficient when set contains many values.

© Pearson Education Limited, Pattern Matching List all staff whose first name is Sally. SELECT staffNo, name, position, salary FROM Staff WHERE name LIKE ‘Sally%’;

© Pearson Education Limited, Pattern Matching SQL has two special pattern matching symbols: %: sequence of zero or more characters; _ (underscore): any single character. LIKE ‘Sally%’ means the first 5 characters must be Sally followed by anything.

© Pearson Education Limited, NULL Search Condition List the video rentals that have not yet been returned. Have to test for null explicitly using special keyword IS NULL: SELECT dateOut, memberNo, videoNo FROM RentalAgreement WHERE dateReturn IS NULL;

© Pearson Education Limited, NULL Search Condition Negated version (IS NOT NULL) can test for non-null values.

© Pearson Education Limited, Single Column Ordering List all videos in descending order of price. SELECT * FROM Video ORDER BY price DESC;

© Pearson Education Limited, Single Column Ordering

© Pearson Education Limited, SELECT Statement - Aggregates ISO SQL defines five aggregate functions: COUNT returns number of values in specified column. SUMreturns sum of values in specified column. AVGreturns average of values in specified column. MINreturns smallest value in specified column. MAXreturns largest value in specified column.

© Pearson Education Limited, SELECT Statement - Aggregates Each operates on a single column of a table and returns a single value. COUNT, MIN, and MAX apply to numeric and non-numeric fields, but SUM and AVG only for numeric fields. Apart from COUNT(*), each function eliminates nulls first and operates only on remaining non-null values.

© Pearson Education Limited, SELECT Statement - Aggregates 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.

© Pearson Education Limited, SELECT Statement - Aggregates 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 out with an aggregate function. For example, following is illegal: SELECT staffNo, COUNT(salary) FROM Staff;

© Pearson Education Limited, Use of COUNT and SUM List total number of staff with salary greater than $40,000 and the sum of their salaries. SELECT COUNT(staffNo) AS totalStaff, SUM(salary) as totalSalary FROM Staff WHERE salary > 40000;

© Pearson Education Limited, Use of COUNT and SUM

© Pearson Education Limited, 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;

© Pearson Education Limited, SELECT Statement - Grouping Use GROUP BY clause to get sub-totals. 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.

© Pearson Education Limited, SELECT Statement - Grouping All column names in SELECT list must appear in GROUP BY clause unless used only in an aggregate function. 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.

© Pearson Education Limited, 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;

© Pearson Education Limited, Use of GROUP BY

© Pearson Education Limited, 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. Column names in HAVING clause must also appear in the GROUP BY list or be contained within an aggregate function.

© Pearson Education Limited, 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;

© Pearson Education Limited, Use of HAVING

© Pearson Education Limited, 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.

© Pearson Education Limited, Subquery with Equality Find staff who work in branch at ‘8 Jefferson Way’. SELECT staffNo, name, position FROM Staff WHERE branchNo = (SELECT branchNo FROM Branch WHERE street=‘8 Jefferson Way’);

© Pearson Education Limited, Subquery with Equality 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’;

© Pearson Education Limited, Subquery with Equality

© Pearson Education Limited, 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);

© Pearson Education Limited, Subquery with Aggregate Cannot write ‘WHERE salary > AVG(salary)’ Instead, use subquery to find average salary ( ), and then use outer SELECT to find those staff with salary greater than this: SELECT staffNo, name, position FROM Staff WHERE salary > ;

© Pearson Education Limited, Subquery with Aggregate

© Pearson Education Limited, 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.

© Pearson Education Limited, Subquery Rules 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.

© Pearson Education Limited, 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).

© Pearson Education Limited, Multi-Table Queries 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.

© Pearson Education Limited, 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;

© Pearson Education Limited, Simple Join Only those rows from both tables with identical values in the directorNo columns (v.directorNo = d.directorNo) included in result.

© Pearson Education Limited, Alternative JOIN Constructs Alternative ways to specify joins: FROM Video v JOIN Director d ON v.directorNo = d.directorNo FROM Video JOIN Director USING directorNo FROM Video NATURAL JOIN Director FROM replaces original FROM and WHERE. However, first produces table with two identical directorNo columns.

© Pearson Education Limited, 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;

© Pearson Education Limited, Four Table Join

© Pearson Education Limited, 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.

© Pearson Education Limited, INSERT dataValueList must match columnList as follows: number of items in each list must be same; 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.

© Pearson Education Limited, INSERT Insert a row into the Video table. INSERT INTO Video VALUES (‘207132’, ‘Die Another Day’, ‘Action’ 5.00, 21.99, ‘D1001’ );

© Pearson Education Limited, 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.

© Pearson Education Limited, UPDATE 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.

© Pearson Education Limited, 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’;

© Pearson Education Limited, 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.

© Pearson Education Limited, DELETE Specific Rows Delete rental videos for catalog number DELETE FROM VideoForRent WHERE catalogNo = ‘634817’;

© Pearson Education Limited, Data Definition Two main SQL DDL statements: CREATE TABLE – to create a new table. CREATE VIEW – to create a new view.

© Pearson Education Limited, CREATE TABLE Statement CREATE TABLE TableName {(columnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption][,...]} [PRIMARY KEY (listOfColumns),] {[UNIQUE (listOfColumns),] […,]} {[FOREIGN KEY (listOfFKColumns) REFERENCES ParentTableName [(listOfCKColumns)], [ON UPDATE referentialAction] [ON DELETE referentialAction ]] [,…]}

© Pearson Education Limited, Defining a column columnName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption] Supported data types of SQL are:

© Pearson Education Limited, PRIMARY KEY and entity integrity Entity integrity supported by PRIMARY KEY clause. For example: CONSTRAINT pk PRIMARY KEY (catalogNo) CONSTRAINT pk1 PRIMARY KEY (catalogNo, actorNo)

© Pearson Education Limited, FOREIGN KEY and ref. integrity Use FOREIGN KEY clause to define 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.

© Pearson Education Limited, FOREIGN KEY and ref. integrity Referential actions with ON UPDATE and ON DELETE subclauses. Possible values are: CASCADE – Update/delete row from parent and automatically update/ 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.

© Pearson Education Limited, CREATE VIEW Statement CREATE VIEW ViewName [(newColumnName [,...]] AS Subselect CREATE VIEW StaffBranch1 AS SELECT staffNo, name, position FROM Staff WHERE branchNo = ‘B001’;

© Pearson Education Limited, Query-By-Example (QBE) QBE alternative graphical-based “point-and- click” way of querying database. One of easiest ways for non-technical users to query database. Query database by illustrating query to be answered using a template.