NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL.

Slides:



Advertisements
Similar presentations
SQL: The Query Language Part 2
Advertisements

Chapter 4 Joining Multiple Tables
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Joining Relations in SQL Objectives of the Lecture : To consider the Natural & Generalised Joins using the SQL1 standard; To consider the Natural & Generalised.
Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5 Modified by Donghui Zhang.
CSC271 Database Systems Lecture # 13. Summary: Previous Lecture  Grouping through GROUP BY clause  Restricted groupings  Subqueries  Multi-Table queries.
SQL Subqueries Objectives of the Lecture : To consider the general nature of subqueries. To consider simple versus correlated subqueries. To consider the.
CS 405G: Introduction to Database Systems
1 Lecture 12: Further relational algebra, further SQL
Structure Query Language (SQL) COMSATS INSTITUTE OF INFORMATION TECHNOLOGY, VEHARI.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
FALL 2004CENG 351 File Structures and Data Management1 SQL: Structured Query Language Chapter 5.
Nov 24, 2003Murali Mani SQL B term 2004: lecture 12.
1 Relational Model. 2 Relational Database: Definitions  Relational database: a set of relations  Relation: made up of 2 parts: – Instance : a table,
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 8 Advanced SQL.
CPSC-608 Database Systems Fall 2011 Instructor: Jianer Chen Office: HRBB 315C Phone: Notes #3.
Database Systems More SQL Database Design -- More SQL1.
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.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
Chapter 3 Single-Table Queries
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 8 Advanced SQL.
CSE314 Database Systems More SQL: Complex Queries, Triggers, Views, and Schema Modification Doç. Dr. Mehmet Göktürk src: Elmasri & Navanthe 6E Pearson.
HAP 709 – Healthcare Databases SQL Data Manipulation Language (DML) Updated Fall, 2009.
Advanced SQL Murat Kantarcioglu Adapted from Silberchatz et al. slides.
Chapter 9 Joining Data from Multiple Tables
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
SQL: Data Manipulation Presented by Mary Choi For CS157B Dr. Sin Min Lee.
The Data in a Relation To consider atomic data in relations; To consider data types in a relation; To consider missing data & NULLs in relations. Objectives.
Chapter 6 SQL: Data Manipulation (Advanced Commands) Pearson Education © 2009.
1 The Relational Database Model. 2 Learning Objectives Terminology of relational model. How tables are used to represent data. Connection between mathematical.
1 Single Table Queries. 2 Objectives  SELECT, WHERE  AND / OR / NOT conditions  Computed columns  LIKE, IN, BETWEEN operators  ORDER BY, GROUP BY,
Using Special Operators (LIKE and IN)
9/7/2012ISC329 Isabelle Bichindaritz1 The Relational Database Model.
6 1 Lecture 8: Introduction to Structured Query Language (SQL) J. S. Chou, P.E., Ph.D.
Set Operations Objectives of the Lecture : To consider the Set Operations Union, Difference and Intersect; To consider how to use the Set Operations in.
Further GroupBy & Extend Operations Objectives of the Lecture : To consider “whole relation” Grouping; To consider the SQL Grouping option Having; To consider.
Topics Related to Attribute Values Objectives of the Lecture : To consider sorting relations by attribute values. To consider Triggers and their use for.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
NULL VALUES CHAPTER 5 (6/E) CHAPTER 8 (5/E) 1. LECTURE OUTLINE  Dealing with null values Three-valued logic Effects in WHERE clauses IS NULL Effects.
Concepts of Database Management Seventh Edition Chapter 3 The Relational Model 2: SQL.
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Subqueries These slides are licensed under.
Views, Algebra Temporary Tables. Definition of a view A view is a virtual table which does not physically hold data but instead acts like a window into.
1 CS 430 Database Theory Winter 2005 Lecture 5: Relational Algebra.
SqlExam1Review.ppt EXAM - 1. SQL stands for -- Structured Query Language Putting a manual database on a computer ensures? Data is more current Data is.
Insert & Delete Objectives of the Lecture : To consider the insertion of tuples into a relation; To consider the deletion of tuples from a relation; To.
Web Programming MySql JDBC Web Programming.
Restrictions Objectives of the Lecture : To consider the algebraic Restrict operator; To consider the Restrict operator and its comparators in SQL.
1 SQL: Structured Query Language (‘Sequel’) Chapter 5.
More SQL (and Relational Algebra). More SQL Extended Relational Algebra Outerjoins, Grouping/Aggregation Insert/Delete/Update.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
1 SQL: The Query Language. 2 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 5: SQL I Rob Gleasure robgleasure.com.
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.
SQL: Structured Query Language Instructor: Mohamed Eltabakh 1 Part II.
Subqueries CIS 4301 Lecture Notes Lecture /23/2006.
More SQL: Complex Queries, Triggers, Views, and Schema Modification
More SQL: Complex Queries,
COP Introduction to Database Structures
Database Systems: Design, Implementation, and Management Tenth Edition
Quiz Questions Q.1 An entity set that does not have sufficient attributes to form a primary key is a (A) strong entity set. (B) weak entity set. (C) simple.
Lecture 2 The Relational Model
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL: Structured Query Language
SQL: Structured Query Language
Database Systems: Design, Implementation, and Management Tenth Edition
Manipulating Data Lesson 3.
Lecture 04: SQL Monday, October 6, 2003.
Presentation transcript:

NULLs & Outer Joins Objectives of the Lecture : To consider the use of NULLs in SQL. To consider Outer Join Operations, and their implementation in SQL.

Missing Values : Possible Strategies l Use a special value to represent missing data. E.g. ‘N/A’, ‘T.B.A.’ The special value must have the same data type as the data that is missing, so it can be stored with the data that is known. Requires no special facility from the DBMS. l Use NULL to represent missing data. NULL is the absence of a value. NULL  0NULL  ‘ ’ NULL is not part of any data type. Requires special support from the DBMS. SQL DBMSs provide this support. So most DBs use NULLs to represent missing data. space character

Display of SQL NULLs Blank space in Oracle. Keyword NULL in other SQL DBMSs. Other possibilities in other DBMSs.

Dealing with NULLs in SQL Tables Three situations arise : l Comparisons of column values. This occurs in the SQL equivalents of the Restrict and the various Join operations, plus Deletions and Updates. l Calculations involving column values. This occurs in the SQL equivalents of the GroupBy and Extend operations. l Comparisons of row values. This occurs in the SQL equivalents of the Project, GroupBy, Union, Intersect, and Difference operations.

Comparison of Column Values (1) SQL provides special comparators to check for NULL :- X IS NULL X IS NOT NULL Let X be a numeric column. If X has a value, the comparison X = 3 makes sense. It should yield true or false. Suppose X is NULL. An error should arise. In fact SQL treats the NULL as representing an existing but unknown value. Comparison returns maybe. Rationale : We don’t know if X = 3 because X is NULL (= not available). Note : X may represent some other case of missing data (e.g. not applicable, does not exist). The result is still maybe even though this is then illogical.

Comparisons of Column Values (2) l Let X and Y be a numeric columns. Consider the comparison X = Y Suppose X and Y are both NULL. The result is maybe not true. l NULL is not the same as maybe. Absence of a value. A truth value. l SQL uses NULL to mean maybe !

Restricts, Joins, Updates and Deletions RestrictSELECT * FROM TableName WHERE condition ; JoinSELECT * FROM Table1 NATURAL JOIN Table2 ; DeleteDELETE FROM TableName WHERE condition ; UpdateUPDATE TableName SET column(s) = new value(s) WHERE condition ; l Restrict / Join / Delete / Update action taken only where condition evaluates to true, not where it evaluates to maybe or false. Column comparison used as a condition Similarly for other kinds of Join.

Unexpected Results (1) They arise when forgetting that the condition can evaluate to maybe. Example :- SELECT* FROMEMP WHERESal >= UNION SELECT* FROMEMP WHERESal < ;  the 2 Restrictions will not necessarily contain all the rows of EMP between them. If column ‘Sal’ contains any NULLs, the result will not re-create table EMP.

Unexpected Results (2) To ensure the table is re-created, re-write the query as follows :- SELECT* FROMEMP WHERESal >= UNION SELECT* FROMEMP WHERESal < UNION SELECT* FROMEMP WHERESal IS NULL ; In general, adjust statements to reflect the NULL possibility.

Join involving NULLs : Example This row does not appear in the result. SELECT * FROM R Natural Join S ; R S

Oracle’s “NVL” Function NVL supplies a value to use whenever a NULL is encountered. It can be used in SELECT and WHERE phrases. Example :NVL( Sal, 0 ) This yields the value of the ‘Sal’ column, except that if ‘Sal’ is NULL, then a value of zero is returned. NVL can be used to ensure a comparison always yields true or false, and never maybe. Example : ……... WHERE NVL( M-S, ‘S’ ) <> ‘M’ Put a column name in the first position. Put a value in the second position. Value ‘S’ is used in the comparison when ‘M-S’ is NULL. Comparison can never return maybe.

Calculations Involving Column Values These arise in two situations : Scalar calculations along rows Extend Aggregate calculations along columns GroupBy

Scalar Calculations Any calculation involving a NULL results in a NULL. Examples : let n be NULL. Then :- l n + 1  NULL l n concatenate “ABCD”  NULL l n - n  NULL (not zero) Example :- SELECT Sal AS NewSal FROM EMP ; So “NewSal” will be NULL whenever “Sal” is NULL.

Aggregate Calculations If the columns being aggregated contain one or more NULLs, then the answer from : l Sum l Avg l Minignores the NULLs. l Max l Count( Distinct ) l Count(*) includes the NULLs.

Example : Aggregation in GroupBy SELECT Sum(Sal) AS Total, M-S FROM EMP GROUP BY M-S ;

Comparisons of Rows l In SQL, two rows are identical if : they have the same number of attributes; corresponding attributes are of the same data type; corresponding attributes have the same value. l In an SQL row comparison, a NULL compared to a NULL  true l In an SQL column comparison (e.g. for a Join operation) a NULL compared to a NULL  maybe Different !!

Example : Row Comparison Comparison of M-S column values : l Row Comparison : 2 NULLs are defined to be identical. A comparison yields true !!  these 2 rows are identical. l Column Comparison : 2 NULLs are not assumed identical. A comparison yields maybe !!  these rows are rejected.

Project, GroupBy, & Set Operators ProjectSELECT DISTINCT ColumnName(s) FROM TableName ; GroupBySELECT “Aggregation(s)”, GroupingCol(s) FROM TableName GROUP BY GroupingCol(s) ; Set OpsSELECT * FROM TableName1 UNION SELECT * FROM TableName2 ; l Project / GroupBy (grouping rows) / Union / Intersect / Except action taken on the basis that all NULLs are identical. Similarly for the other Set Ops, Intersect & Except/Minus.

Example : Projection SELECT DISTINCT M-S FROM EMP ;

Example : Grouping in ‘GroupBy’ SELECT “Aggregation”, M-S FROM EMP GROUP BY M-S ;

Example : Union Operation Union

Joins - Inner versus Outer l All joins considered so far are Inner Joins. Only a subset of each operand’s tuples appear in the result. These are the tuples that match each other in the 2 operands. (Match  the comparison (of whatever kind) is true). The unmatched tuples don’t appear in the result. l Sometimes it is useful to have unmatched tuples in the result as well.  Outer Join Three kinds of Outer Join, to retain in the result all the unmatched tuples from : ‘Left’ operand, ‘Right’ operand, ‘Left’ and ‘Right’ operands.

Inner Joins (Natural) Unmatched tuples are not in the result. unmatched

Outer Join : Left ? ? (Natural) Some unmatched tuples are in the result. unmatched ‘padding’ unmatched

Outer Join : Right ? ? ? ? ? ? ? ? (Natural) Some unmatched tuples are in the result. unmatched ‘padding’ unmatched

Outer Join : Full ? ? ? ? ? ? ? ? ? ? (Natural) All unmatched tuples are in the result. unmatched ‘padding’ unmatched

Outer Joins in SQL l What “padding” attribute values are used with the unmatched columns ? l What syntax is used for outer joins ? l Natural Join, l Join Using( ColNames ), l Join On( condition ). Each of these can be used for Left, Right and Full outer joins.  9 possibilities. SQL uses NULLs. An extension of the FROM phrase inner join syntax.

SQL2 Outer Natural Joins SELECT * FROM R Natural Join S ; Left Right Full Outer optionally inserted Examples :- SELECT * FROM SUPP Natural Left Outer Join SHIP ; Result retains all the unmatched rows of LHS table, i.e. SUPP. SELECT * FROM SUPP Natural Right Join SHIP ; Result retains all the unmatched rows of RHS table, i.e. SHIP.

The Other Two SQL2 Outer Joins l SELECT * FROM R Join S Using ( attribute(s) ) ; l SELECT * FROM R Join S On ( condition ) ; Example :- SELECT * FROM SUPP Left Outer Join SHIP Using( S# ) ; Left and right refer to the tables written to left and right of the join operator. Logically only left or right is required, but it is convenient to have both. Left Right Full Outer optionally inserted Left Right Full

Oracle : Outer Joins Original Oracle syntax is completely non-standard. The idea is to add a (+) suffix to the name of the column that is in the table whose columns will receive the NULLs as ‘padding’. Regarding ‘left’ and ‘right’, this is the exact opposite of the SQL standard. Example :- SELECT AttributeNames FROM SUPP, SHIP WHERE SUPP.S# = SHIP.S#(+) ; l Old fashioned SQL1 join syntax is required. l ‘Left’ & ‘right’ refer to columns in the WHERE phrase, not tables in the FROM phrase. l Full join ≡ Union of left and right outer joins. Do NOT use unless desparate !