lecture 8 – sql joins – assemble new views from existing tables inner join’s the cartesian...

29
Lecture 8 – SQL Lecture 8 – SQL Joins – assemble new views from Joins – assemble new views from existing tables existing tables INNER JOIN’s INNER JOIN’s The Cartesian Product The Cartesian Product Theta Joins and Equi-joins Theta Joins and Equi-joins Self Joins Self Joins Natural Join Natural Join

Upload: bartholomew-garrett

Post on 20-Jan-2016

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Lecture 8 – SQLLecture 8 – SQL

Joins – assemble new views from existing Joins – assemble new views from existing tablestables

INNER JOIN’sINNER JOIN’s

The Cartesian ProductThe Cartesian Product

Theta Joins and Equi-joinsTheta Joins and Equi-joins

Self JoinsSelf Joins

Natural JoinNatural Join

Page 2: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

INNER JOINSINNER JOINS

INNER JOIN – the regular join operationINNER JOIN – the regular join operationSELECT fieldsSELECT fields

FROM Table1 INNER JOIN Table2FROM Table1 INNER JOIN Table2

ON Table1.field1=Table2.field1ON Table1.field1=Table2.field1

Example:Example:SELECT *SELECT *

FROM COURSE c INNER JOIN Prereq pFROM COURSE c INNER JOIN Prereq p

ON c.course_number = p.course_numberON c.course_number = p.course_number

This query could be written without the table alias.This query could be written without the table alias.

Page 3: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

WHERE Clause and the Cartesian WHERE Clause and the Cartesian ProductProduct

A second way of joining tables – instead of using A second way of joining tables – instead of using the INNER JOIN command:the INNER JOIN command:

SELECT *SELECT *

FROM Course c, Prereq pFROM Course c, Prereq p

WHERE c.course_number = p.course_numberWHERE c.course_number = p.course_number

Cartesian product – a binary operation in which Cartesian product – a binary operation in which two objects are combined. It is usually not two objects are combined. It is usually not wanted. Why? How to prevent?wanted. Why? How to prevent?

SELECT *SELECT *

FROM Course c, Prereq p;FROM Course c, Prereq p;

Page 4: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Theta Joins and Equi-joinsTheta Joins and Equi-joins

Join with comparison operators (=,>,>=, <=. Join with comparison operators (=,>,>=, <=. and <>) on the WHERE or ON clauses are and <>) on the WHERE or ON clauses are called theta joins.called theta joins.

Join with an = operator are called equi-joins.Join with an = operator are called equi-joins.

Join with an operator other than an = sign Join with an operator other than an = sign are called nonequi-joins.are called nonequi-joins.

SELECT *SELECT *

FROM Course c INNER JOIN Prereq pFROM Course c INNER JOIN Prereq p

ON c.course_number = p.course_number;ON c.course_number = p.course_number;

Page 5: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

SELF JoinsSELF Joins

On rare situations, you will need to join a On rare situations, you will need to join a table with itself – called self join.table with itself – called self join.

Scenario – trying to find all students who are Scenario – trying to find all students who are more senior than other students:more senior than other students:

SELECT x.sname + ‘ is more senior than ‘ + y.snameSELECT x.sname + ‘ is more senior than ‘ + y.sname

FROM Student AS x, Student AS yFROM Student AS x, Student AS y

WHERE y.class = 3WHERE y.class = 3

AND x.class > y.classAND x.class > y.class

This produces the 70 rows of output.This produces the 70 rows of output.

Page 6: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Natural JoinsNatural Joins

Natural Join – a equi-join without the Natural Join – a equi-join without the duplicate column and with the obvious join duplicate column and with the obvious join condition. Example:condition. Example:

SELECT c.course_name, c.course_number, c.credit_hours, SELECT c.course_name, c.course_number, c.credit_hours, C.offering_dept, p.prereqC.offering_dept, p.prereq

FROM Course c INNER JOIN Prereq pFROM Course c INNER JOIN Prereq p

ON c.course_number = p.course_numberON c.course_number = p.course_number

The implied join condition is the equality of The implied join condition is the equality of course_number in the tables, so it is course_number in the tables, so it is displayed only once in the result set.displayed only once in the result set.

Page 7: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Using ORDER BY with a joinUsing ORDER BY with a join

The ORDER BY clause can be used in joins The ORDER BY clause can be used in joins to order the output. To order the output by to order the output. To order the output by course_number:course_number:

SELECT c.course_name, c.course_number, c.credit_hours, SELECT c.course_name, c.course_number, c.credit_hours, C.offering_dept, p.prereqC.offering_dept, p.prereq

FROM Course c INNER JOIN Prereq pFROM Course c INNER JOIN Prereq p

ON c.course_number = p.course_numberON c.course_number = p.course_number

ORDER BY c.course_number;ORDER BY c.course_number;

Or change the last line to –Or change the last line to –

ORDER BY 2;ORDER BY 2;

Page 8: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Joining More than two tables Joining More than two tables

1.1. Using a nested INNER JOINUsing a nested INNER JOIN2.2. Using a WHERE clauseUsing a WHERE clauseSELECT fieldsSELECT fieldsFROM table1 INNER JOINFROM table1 INNER JOIN(table2 INNER JOIN table3(table2 INNER JOIN table3ON table3.field3 = table2.field2)ON table3.field3 = table2.field2)ON table1.field1=table2.field2;ON table1.field1=table2.field2;

For example, if we want to see the courses that For example, if we want to see the courses that have prerequisites and the departments have prerequisites and the departments offering those courses, we have to first join the offering those courses, we have to first join the Course table with the prereq table, and then Course table with the prereq table, and then join that result to the Department_to_major join that result to the Department_to_major table.table.

Page 9: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Joining Multiple tables with Joining Multiple tables with WHERE ClauseWHERE Clause

SELECT c.course_name, c.course_number, d.dnameSELECT c.course_name, c.course_number, d.dname

FROM Course c, Prereq p, Department_to_major dFROM Course c, Prereq p, Department_to_major d

WHERE c.course_number = p.course_numberWHERE c.course_number = p.course_number

AND c.offering_dept = d.dcode;AND c.offering_dept = d.dcode;

Joining order depends on the database Joining order depends on the database engine – thought result would be same, engine – thought result would be same, performance might be different. In Access, performance might be different. In Access, the order of joins is most easily controlled the order of joins is most easily controlled using the INNER JOIN syntax.using the INNER JOIN syntax.

Page 10: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Outer JOINs Outer JOINs

If you want to include unmatched records in If you want to include unmatched records in an equi-join, you will need to use OUTER an equi-join, you will need to use OUTER JOINs.JOINs.

LEFT JOINLEFT JOIN

RIGHT JOINRIGHT JOIN

FULL OUTER JOIN – union of the LEFT FULL OUTER JOIN – union of the LEFT and RIGHT OUTER JOINsand RIGHT OUTER JOINs

Page 11: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The LEFT JOINThe LEFT JOIN

SELECT fieldsSELECT fields

FROM table1 LEFT JOIN table2FROM table1 LEFT JOIN table2

ON table1.field1 = table2.field1;ON table1.field1 = table2.field1;

LEFT OUTER JOINS includes all the LEFT OUTER JOINS includes all the records from the first (left) of the two records from the first (left) of the two tables, even if there are no matching tables, even if there are no matching values for the records in the second (right) values for the records in the second (right) table.table.

Page 12: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The RIGHT JOINThe RIGHT JOIN

RIGHT OUTER JOINs includes all the RIGHT OUTER JOINs includes all the records from the second (right) of the two records from the second (right) of the two tables, even if there are no matching tables, even if there are no matching values for the records in the first (left) values for the records in the first (left) table.table.

Access SQL does not explicitly support the Access SQL does not explicitly support the FULL OUTER JOIN. Word “OUTER” is FULL OUTER JOIN. Word “OUTER” is optional in Access.optional in Access.

Page 13: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

FunctionsFunctions

Aggregate Functions – COUNT, SUM, Aggregate Functions – COUNT, SUM, AVG, MIN, MAX, FIRST and LASTAVG, MIN, MAX, FIRST and LAST

Row-level Functions – Adding a number Row-level Functions – Adding a number to a field, ROUND, NZ functions, etc.to a field, ROUND, NZ functions, etc.

Other Functions – TOP, BOTTOM, etc.Other Functions – TOP, BOTTOM, etc.

StringString

DateDate

Page 14: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Aggregate FunctionsAggregate Functions

Numeric aggregate functions that are Numeric aggregate functions that are used in calculations on a group of used in calculations on a group of numbers, such as SUM, AVG.numbers, such as SUM, AVG.

The second type of aggregate functions The second type of aggregate functions can be used for other manipulations of can be used for other manipulations of multiple rows, for example, TOP or multiple rows, for example, TOP or DISTINCT, in which we try to obtain a DISTINCT, in which we try to obtain a smaller set from multiple rows.smaller set from multiple rows.

Page 15: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The COUNT FunctionThe COUNT Function

COUNT is a function that will generate a value of how COUNT is a function that will generate a value of how many of something there are.many of something there are.

SELECT COUNT(*)SELECT COUNT(*)FROM table-name(s)FROM table-name(s)Example:Example:SELECT COUNT(grade) AS [Count of Grade]SELECT COUNT(grade) AS [Count of Grade]FROM Grade_reportFROM Grade_report

SELECT COUNT(*) AS CountSELECT COUNT(*) AS CountFROM Student, Section, Grade_Report;FROM Student, Section, Grade_Report;

Result - 321024Result - 321024

Page 16: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

SUM, AVG, MIN and Max FunctionSUM, AVG, MIN and Max Function

SELECT SUM(Hours) AS [Total hours]SELECT SUM(Hours) AS [Total hours]FROM Employee;FROM Employee;

SELECT AVG(hours) AS [Average hours]SELECT AVG(hours) AS [Average hours]FROM Employee;FROM Employee;

SELECT MIN(wage) As [Minimum Wage]SELECT MIN(wage) As [Minimum Wage]FROM Employee;FROM Employee;

First and Last Functions will return corresponding row First and Last Functions will return corresponding row attributes.attributes.

Page 17: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Row-Level FunctionsRow-Level Functions

Row functions operate on single rows at a time.Row functions operate on single rows at a time.

(1) Adding a Number to a Field(1) Adding a Number to a FieldSELECT wage, (wage +5) AS [wage+5]SELECT wage, (wage +5) AS [wage+5]

(2) The ROUND Function(2) The ROUND FunctionSELECT name, wage, ROUND))wage/3), 2) AS [wage/3]SELECT name, wage, ROUND))wage/3), 2) AS [wage/3]

(3) The NZ Function – returns a value if a table value (or (3) The NZ Function – returns a value if a table value (or attribute is null. attribute is null.

NZ(expression, ValueIfNull)NZ(expression, ValueIfNull)

Example:Example:

SELECT name, NZ(wage, 0)*NZ(hours,0) AS [wage*hours]SELECT name, NZ(wage, 0)*NZ(hours,0) AS [wage*hours]

(4) Other row-level functions – ABS, SIN, COS, TAN, LOG, (4) Other row-level functions – ABS, SIN, COS, TAN, LOG, ETC.ETC.

Page 18: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Other FunctionsOther FunctionsThe TOP FunctionThe TOP FunctionSELECT TOP 2 name, wageSELECT TOP 2 name, wage

FROM EmployeeFROM Employee

ORDER BY wage ASC;ORDER BY wage ASC;

If you do not include the order by clause, the query will return rows If you do not include the order by clause, the query will return rows based on the order in which they appear in the table. To get based on the order in which they appear in the table. To get bottom rows:bottom rows:

……

ORDER BY Wage DESC;ORDER BY Wage DESC;

TOP can be used with PRECENT:TOP can be used with PRECENT:

SELECT TOP 10 PERCENT snameSELECT TOP 10 PERCENT sname

……

Page 19: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The DISTINCT FunctionThe DISTINCT Function

The distinct function omits records that contain The distinct function omits records that contain duplicate data in the selected fields.duplicate data in the selected fields.

SELECT DISTINCT gradeSELECT DISTINCT grade

FROM Grade_report;FROM Grade_report;

To count the number of distinct grades, two steps are required. First, To count the number of distinct grades, two steps are required. First, create a temporary table that has the distinct grades, and then count create a temporary table that has the distinct grades, and then count the distinct grades from it.the distinct grades from it.

SELECT DISTINCT grade INTO temp1SELECT DISTINCT grade INTO temp1

FROM Grade_report;FROM Grade_report;

SELECT COUNT(grade) AS [Count of distinct grade]SELECT COUNT(grade) AS [Count of distinct grade]

Page 20: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The DISTINCTROW FunctionThe DISTINCTROW Function

The DISTINCTROW function omits rows based on The DISTINCTROW function omits rows based on entire duplicate records, not just duplicate fields.entire duplicate records, not just duplicate fields.

SELECT DISTINCTROW prereq, course_numberSELECT DISTINCTROW prereq, course_number

FROM PrereqFROM Prereq

DISTINCTROW has an effect only when you select DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used fields from some, but not all, of the tables used in the query.in the query.

Page 21: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

String FunctionsString Functions

String functions are all row-level functions.String functions are all row-level functions.

(1)(1) String ConcatenationString ConcatenationSELECT name& ‘, Esq. ‘ AS [Employee Names]SELECT name& ‘, Esq. ‘ AS [Employee Names]

FROM Employee;FROM Employee;

SELECT (‘…..’ +name) AS [Employee Names]SELECT (‘…..’ +name) AS [Employee Names]

FROM Employee;FROM Employee;

(2) String Extractors(2) String ExtractorsMID, INSTR, LEFT/RIGHT, LTRIM/RTRIM, UCASE/LCASE, and LENMID, INSTR, LEFT/RIGHT, LTRIM/RTRIM, UCASE/LCASE, and LEN

Page 22: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

MID, INSTR and LEFT/RIGHTMID, INSTR and LEFT/RIGHT

MID(Stringexpression, start, length)MID(Stringexpression, start, length)

Start tells Access where in the string expression to start Start tells Access where in the string expression to start retrieving from, and length tells Access how many retrieving from, and length tells Access how many characters to extract.characters to extract.

INSTR(start, source_string, search_string)INSTR(start, source_string, search_string)

INSTR finds the occurrence of some search-string pattern INSTR finds the occurrence of some search-string pattern in the string listed in the second argument.in the string listed in the second argument.

SELECT name, INSTR(1, name, ‘ ‘) AS [position of blank in name]SELECT name, INSTR(1, name, ‘ ‘) AS [position of blank in name]

FROM Employee;FROM Employee;

LEFT(stringexpression, n)LEFT(stringexpression, n)

RIGHT(stringexpression,n)RIGHT(stringexpression,n)

Page 23: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

LTRIM/RTRIM and LTRIM/RTRIM and UCLASE/LCASE FunctionUCLASE/LCASE Function

LTRIM removes blanks from the beginning (left) of LTRIM removes blanks from the beginning (left) of as string. RTRIM removes blanks from the end as string. RTRIM removes blanks from the end of a string.of a string.

SELECT LTRIM(‘ Ranu’) AS name;SELECT LTRIM(‘ Ranu’) AS name;

UCASE converts a string to uppercase, while UCASE converts a string to uppercase, while LCASE will do the opposite.LCASE will do the opposite.

SELECT UCASE(name) AS [NAMES IN CAPS]SELECT UCASE(name) AS [NAMES IN CAPS]

FROM Employee;FROM Employee;

Page 24: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

The LEN/LIKE FunctionThe LEN/LIKE Function

The LEN function returns the length of a desired The LEN function returns the length of a desired string.string.

SELECT name, LEN(name) AS [Length of Name]SELECT name, LEN(name) AS [Length of Name]

FROM Employee;FROM Employee;

Matching Substring Using LIKE.Matching Substring Using LIKE.

Using LIKE as an “existence” match entails finding Using LIKE as an “existence” match entails finding whether a character string exists in an attribute – whether a character string exists in an attribute – if the string existed, the row is selected for if the string existed, the row is selected for inclusion in the result set.inclusion in the result set.

WHERE sname LIKE ‘*Smith’;WHERE sname LIKE ‘*Smith’;

Page 25: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

DATE FunctionsDATE Functions

The Year(number) function will extract the year The Year(number) function will extract the year from a date.from a date.

SELECT YEAR(k5date) AS [Kindergarten Year], nameSELECT YEAR(k5date) AS [Kindergarten Year], name

The MONTH function will extract the month from The MONTH function will extract the month from a date. a date.

The DAY function extracts the day of the month The DAY function extracts the day of the month from a date.from a date.

The WEEKDAY function extracts the day of the The WEEKDAY function extracts the day of the week from a date. Sunday is regarded as day 1week from a date. Sunday is regarded as day 1

The Function DATE() gives the current date.The Function DATE() gives the current date.

Page 26: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Query Development and Derived Query Development and Derived StructuresStructures

Query DevelopmentQuery Development

Parentheses in SQL ExpressionsParentheses in SQL Expressions

Derived StructureDerived Structure

Query Development with Derived Query Development with Derived StructuresStructures

Page 27: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Query DevelopmentQuery Development

ExperimentationExperimentation Modifying previous stored queriesModifying previous stored queries

Best way to understand how query building Best way to understand how query building process works is to look at an example.process works is to look at an example.

Suppose we want to find the names of all Suppose we want to find the names of all students in the standard student.mdb students in the standard student.mdb database who major in computer science database who major in computer science (COSC) and have earned a grade of B in (COSC) and have earned a grade of B in some course.some course.

Page 28: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Derived StructuresDerived Structures

Derived structures help us to build queries Derived structures help us to build queries on top of other queries.on top of other queries.

ViewsViews

Temporary tablesTemporary tables

A view (virtual table, a saved query.):A view (virtual table, a saved query.):

- Save spaceSave space

- Permission controlPermission control

Page 29: Lecture 8 – SQL Joins – assemble new views from existing tables INNER JOIN’s The Cartesian Product Theta Joins and Equi-joins Self Joins Natural Join

Using ViewsUsing Views

View can be used just like a tableView can be used just like a table A view has no data of its ownA view has no data of its own Views depend on the underlying tablesViews depend on the underlying tables If a record were added or deleted from the If a record were added or deleted from the view, the same change would also appear view, the same change would also appear in the original tablein the original table If data is changed in the original table, the If data is changed in the original table, the same data in all the views related to that same data in all the views related to that table also gets changed.table also gets changed.