CSC271 Database Systems Lecture # 11.

Slides:



Advertisements
Similar presentations
Chapter 6 SQL: Data Manipulation Pearson Education © 2009.
Advertisements

CSC271 Database Systems Lecture # 13. Summary: Previous Lecture  Grouping through GROUP BY clause  Restricted groupings  Subqueries  Multi-Table queries.
Chapter 6 SQL: Data Manipulation. 2 Objectives of SQL u Database language should allow user to: –create database and relation structures –perform insertion,
1 Minggu 4, Pertemuan 7 SQL: Data Manipulation Matakuliah: T0206-Sistem Basisdata Tahun: 2005 Versi: 1.0/0.0.
Relational Database Management System A type of database in which records are stored in relational form is called relational database management system.
Relational Model & Relational Algebra. 2 Relational Model u Terminology of relational model. u How tables are used to represent data. u Connection between.
CSC271 Database Systems Lecture # 10.
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.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
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 7 SQL: Data Manipulation Chapter#6 in the text book Pearson Education © 2009.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Chapter 7 Introduction to SQL(Wk11_12) © Pearson Education Limited 1995, 2005.
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
SQL Data Manipulation II Chapter 5 CIS 458 Sungchul Hong.
Chapter 5 SQL Data Manipulation Language Chapter 5 in Textbook.
Chapter 5 SQL: Data Manipulation © Pearson Education Limited 1995, 2005.
Bayu Adhi Tama, ST., MTI. Introduction Relational algebra and relational calculus are formal languages associated with the relational.
Advanced Database Systems
CS 3630 Database Design and Implementation. 2 DreamHome Branch (branchNo, street, city, state, zipcode, phone1, phone2, phone3) Staff (staffNo, firstName,
1 Pertemuan > > Matakuliah: >/ > Tahun: > Versi: >
Chapter 7 SQL: Data Manipulation Chapter #6 in the textbook Pearson Education © 2009.
Chapter 5 Relational Algebra and Relational Calculus Pearson Education © 2009.
IST 210 SQL Todd Bacastow IST 210: Organization of Data.
Queries SELECT [DISTINCT] FROM ( { }| ),... [WHERE ] [GROUP BY [HAVING ]] [ORDER BY [ ],...]
DATA RETRIEVAL WITH SQL Goal: To issue a database query using the SELECT command.
Chapter 8 Introduction to SQL
Chapter 5 Relational Algebra Pearson Education © 2014.
CSC271 Database Systems Lecture # 8. Summary: Previous Lecture  Relation algebra and operations  Selection (Restriction), projection  Union, set difference,
SQL : Data Manipulation Pertemuan 09 s/d 12 Matakuliah: M0564 /Pengantar Sistem Basis Data Tahun : 2008.
CSC271 Database Systems Lecture # 7. Summary: Previous Lecture  Relational keys  Integrity constraints  Views.
A Guide to SQL, Eighth Edition Chapter Four Single-Table Queries.
IST 210 More SQL Todd Bacastow IST 210: Organization of Data.
Chapter 6 SQL – Data Manipulation Pearson Education © 2014.
SQL and QBE Transparencies. ©Pearson Education 2009 Chapter 3 - Objectives Purpose and importance of SQL, the main language for querying relational databases.
SQL: Data Manipulation. Objectives Describe the purpose and importance of SQL. Demonstrate how to retrieve data from database using SELECT and: ▫Use compound.
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.
Retrieving Information Pertemuan 3 Matakuliah: T0413/Current Popular IT II Tahun: 2007.
Teacher Workshop Database Design Pearson Education © 2014.
Chapter 11 SQL: Data Manipulation
Tahun : <<2007>> Versi : <<2/1>>
CS 3630 Database Design and Implementation
Chapter Name SQL: Data Manipulation
Chapter Name SQL: Data Manipulation
Data Manipulation Language
CS311 Database Management system
SQL – Data Manipulation
Relational Algebra and Relational Calculus
Introduction to SQL Chapter 3.
The Relational Database Model
Chapter Name SQL: Data Manipulation Chapter #6 in the textbook
SQL-2 Week 9-11.
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
SQL – Data Manipulation
Chapter Name SQL: Data Manipulation
The Relational Algebra
Chapter Name SQL: Data Manipulation Transparencies
Chapter Name SQL: Data Manipulation Transparencies
Chapter Name SQL: Data Manipulation
Presentation transcript:

CSC271 Database Systems Lecture # 11

Summary: Previous Lecture Objectives of SQL History of SQL Importance of SQL Writing SQL statements DML (Data Manipulation Language) SELECT statement

DreamHome Case Study Consist of following tables: Branch (branchNo, street, city, postcode) Staff (staffNo, fName, lName, position, sex, DOB, salary, branchNo) PropertyForRent (propertyNo, street, city, postcode, type, rooms, rent, ownerNo, staffNo, branchNo) Client (clientNo, fName, lName, telNo, prefType, maxRent) PrivateOwner (ownerNo, fName, lName, address, telNo) Viewing (clientNo, propertyNo, viewDate, comment)

Instance of DreamHome

Instance of DreamHome

Instance of DreamHome

Row Selection (WHERE) To restrict rows that are to be retrieved, use WHERE clause Keyword WHERE is followed by a search condition There are five basic search conditions (or predicates using the ISO terminology) available The WHERE clause is equivalent to the relational algebra Selection operation

Search Conditions Comparison Range Set membership Compare the value of one expression to the value of another expression Range Test whether the value of an expression falls within a specified range of values Set membership Test whether the value of an expression equals one of a set of values

Search Conditions.. Pattern match Null Test whether a string matches a specified pattern. Null Test whether a column has a null (unknown) value

Example 5.5 Comparison search condition List all staff with a salary greater than 10,000 SELECT staffNo, fName, lName, position, salary FROM Staff WHERE salary > 10000;

Result: Example 5.5

SQL Comparison Operators In SQL, the following simple comparison operators are available: = , < > (ISO standard) / != (allowed in some dialects) < , <= , >, >= Complex predicate using logical operators AND, OR, NOT Parenthesis to show the order of evaluation

Expression Evaluation The rules for evaluating a conditional expression are: An expression is evaluated left to right Sub expressions in brackets are evaluated first NOTs are evaluated before ANDs and ORs ANDs are evaluated before ORs The use of parentheses is always recommended in order to remove any possible ambiguities

Example 5.6 Compound comparison search condition List addresses of all branch offices in London or Glasgow SELECT * FROM Branch WHERE city = ‘London’ OR city = ‘Glasgow’;

Result: Example 5.6

Example 5.7 Range search condition (BETWEEN/NOT BETWEEN) List all staff with a salary between 20,000 and 30,000 SELECT staffNo, fName, lName, position,salary FROM Staff WHERE salary BETWEEN 20000 AND 30000; BETWEEN test includes the endpoints of range

Result: Example 5.7

Range Search Condition Also a negated version, NOT BETWEEN BETWEEN does not add much to the expressive power of SQL, because SELECT staffNo, fName, lName, position, salary FROM Staff WHERE salary >= 20000 AND salary <= 30000; Useful and simple, though, for a range of values

Example 5.8 Set membership condition (IN/NOT IN) List all managers and supervisors SELECT staffNo, fName, lName, position FROM Staff WHERE position IN (‘Manager’, ‘Supervisor’);

Result: Example 5.8

Set Membership Search Condition There is a negated version (NOT IN) IN does not add much to the expressive power of SQL, because SELECT staffNo, fName, lName, position FROM Staff WHERE position=‘Manager’ OR position=‘Supervisor’; IN is more efficient particularly if the set contains many values

Example 5.9 Pattern match search condition (LIKE/NOT LIKE) Find all owners with the string ‘Glasgow’ in their address SELECT ownerNo, fName, lName, address, telNo FROM PrivateOwner WHERE address LIKE ‘%Glasgow%’;

Result: Example 5.9

Pattern Match Search Condition SQL has two special pattern matching symbols: % (percent): any sequence of zero or more characters _ (underscore): any single character Address LIKE ‘H%’ means the first character must be H, but the rest of the string can be anything Address LIKE ‘H_ _ _’ means that there must be exactly four characters in the string, the first of which must be an H LIKE ‘%Glasgow%’ means a sequence of characters of any length containing ‘Glasgow’

Pattern Match Search Condition.. If the search string can include the pattern-matching character itself, we can use an escape character to represent the pattern-matching character For example, to check for the string ‘15%’, we can use the predicate: LIKE ‘15#%’ ESCAPE ‘#’ Some RDBMSs, such as Microsoft Office Access, use the wildcard characters * and ? instead of % and _

Example 5.10 NULL search condition (IS NULL/IS NOT NULL) List the details of all viewings on property PG4 where a comment has not been supplied SELECT clientNo, viewDate FROM Viewing WHERE propertyNo= ‘PG4’ AND comment IS NULL; Negated version (IS NOT NULL) can test for non-null values

Result: Example 5.10

Sorting Results (ORDER BY Clause) In general, the rows of an SQL query result table are not arranged in any particular order Although some DBMSs may use a default ordering based, for example, on a primary key We can use ORDER BY clause to sort query results Sorting in ASC or DESC order on a column(s) Single column ordering or multiple column ordering ORDER BY clause must always be the last clause of the SELECT statement

Example 5.11 Single-column ordering List salaries for all staff, arranged in descending order of salary. SELECT staffNo, fName, lName, salary FROM Staff ORDER BY salary DESC;

Result: Example 5.11

Example 5.12 Multiple column ordering Minor/Major sort key (one sort key) Produce an abbreviated list of properties arranged in order of property type SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type;

Result: Example 5.12

Example 5.12 Multiple column ordering Minor/Major sort key (two sort keys) Produce an abbreviated list of properties arranged in order of property type SELECT propertyNo, type, rooms, rent FROM PropertyForRent ORDER BY type, rent DESC;

Result: Example 5.12

SQL Aggregate Functions The ISO standard defines five aggregate functions: COUNT: returns the number of values in a specified column SUM: returns the sum of the values in a specified column AVG: returns the average of the values in a specified column MIN: returns the smallest value in a specified column MAX: returns the largest value in a specified column

SQL Aggregate Functions.. These functions operate on a single column of a table and return a single value COUNT, MIN, and MAX apply to both numeric and non-numeric fields SUM and AVG may be used on numeric fields only Apart from COUNT(*), each function eliminates nulls first and operates only on the remaining non-null values

SQL Aggregate Functions.. COUNT(*) is a special use of COUNT, which counts all the rows of a table, regardless of whether nulls or duplicate values occur If we want to eliminate duplicates before the function is applied, we use the keyword DISTINCT before the column name in the function

SQL Aggregate Functions.. The ISO standard allows the keyword ALL to be specified if we do not want to eliminate duplicates, although ALL is assumed if nothing is specified DISTINCT has no effect with the MIN and MAX functions However, it may have an effect on the result of SUM or AVG DISTINCT can be specified only once in a query

SQL Aggregate Functions.. It is important to note that an aggregate function can be used only in the SELECT list HAVING clause It is incorrect to use it elsewhere

SQL Aggregate Functions.. If the SELECT list includes an aggregate function and no GROUP BY clause is being used to group data together, then no item in the SELECT list can include any reference to a column unless that column is the argument to an aggregate function For example, the following query is illegal: SELECT staffNo, COUNT(salary) FROM Staff;

Example 5.13 Use of COUNT(*) How many properties cost more than £350 per month to rent? SELECT COUNT(*) AS myCount FROM PropertyForRent WHERE rent > 350;

Example 5.14 Use of COUNT(DISTINCT) How many different properties were viewed in May 2004? SELECT COUNT(DISTINCT propertyNo) AS myCount FROM Viewing WHERE viewDate BETWEEN ‘1-May-04’ AND ‘31-May-04’;

Example 5.15 Use of COUNT and SUM Find the total number of Managers and the sum of their salaries SELECT COUNT(staffNo) AS myCount, SUM(salary) AS mySum FROM Staff WHERE position= ‘Manager’;

Example 5.16 Use of MIN, MAX, AVG Find the minimum, maximum, and average staff salary SELECT MIN(salary) AS myMin, MAX(salary) AS myMax, AVG(salary) AS myAvg FROM Staff;

Summary Row selection using WHERE clause WHERE clause and search conditions Sorting results using ORDER BY clause SQL aggregate functions

References All the material (slides, diagrams etc.) presented in this lecture is taken (with modifications) from the Pearson Education website : http://www.booksites.net/connbegg