<<

Introduction to SQL Part 3 – Manipulation Language - Joining tables - (Olav Dæhli – 2018)

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 1 Creating a and two tables

• Create a database named CarDatabaseLecture3

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 2 Creating the Car-

CREATE TABLE CAR ( RegNumber varchar (7), --Primærnøkkel blir per definisjon --NOT NULL og UNIQUE CarMake varchar(30) NULL, -- Nullmerker tillates Color varchar(20) NULL DEFAULT 'Unknown', --'Unknown' når -- verdi ikke angis RegDate date NULL, Price money NULL, OwnerId int NULL, CONSTRAINT PK_CAR (RegNumber), --RegNumber som ) --primærnøkkel

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 3 Creating the Owner-table

CREATE TABLE OWNER ( OwnerId int NOT NULL, FName varchar(30) NULL, LName varchar(30) NULL, PostalCode int NULL, CONSTRAINT PK_OWNER PRIMARY KEY (OwnerId) )

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 4 Adding foreign key: Three alternative methods 1: Drag and drop in Diagram View (after the Table Creation)

Primary Key

Foreign Key 25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 5 Adding foreign key: Three alternative methods 2: With SQL: Implement it when creating the table (CREATE TABLE)

CREATE TABLE CAR ( RegNumber varchar (7), CarMake varchar(30) NULL, Color varchar(20) NULL DEFAULT 'Unknown', RegDate date NULL, Price money NULL, OwnerId int NULL, CONSTRAINT PK_CAR PRIMARY KEY (RegNumber), CONSTRAINT FK_CAR_OWNER FOREIGN KEY (OwnerId) REFERENCES OWNER (OwnerId) )

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 6 Adding foreign key: Three alternative methods 3: With SQL: Implement it with after table creation (ALTER TABLE)

ALTER TABLE CAR ADD CONSTRAINT FK_CAR_OWNER FOREIGN KEY (OwnerId) REFERENCES OWNER (OwnerId)

If you want to the foreign key, use the identificator FK_CAR_OWNER:

ALTER TABLE CAR DROP CONSTRAINT FK_CAR_OWNER

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 7 Reference integrity

• After adding the foreign key, try to: • delete the OWNER-table before deleting the CAR-table • delete the CAR-table before deleting the OWNER-table

• Try to insert a value into the CAR-tables OwnerId-, where it does not exist a corresponing value in the OWNER-table.

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 8 Reference integrity

• When refering to a table (with a foreign key), the table must exist.

• When refering to a value (with a foreign key), the value must exist.

• A foreign key field is allowed to be left empty (NULL-value/NULL-values).

• A foreign key field can not be left partly empty. A combined foreign key have to have only NULL-values or no NULL-values at all in each . OWNER • A foreign key column, and it’s corresponing primary key column, have to CAR be of the same datatype.

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 9 Adding a third table (POSTALADDRESS)

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 10 Creating the POSTALADDRESS-table CREATE TABLE POSTALADDRESS ( Notice that the datatype PostalCode char(4), is not a number City char(35) CONSTRAINT PKPOSTALADDRESS PRIMARY KEY (PostalCode) )

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 11 Adding a foreign key (To the OWNER-table)

Adding a foreign key from OWNER to POSTALADDRESS

ALTER TABLE OWNER ADD CONSTRAINT FK_OWNER_POSTALADDRESS FOREIGN KEY (PostalCode) REFERENCES POSTALADDRESS (PostalCode)

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 12 Insert some data into the tables

• Import date from scripts • In what order should they be imported, and why?

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 13 Cartesian Product (Cross Product)

SELECT * This is normally not what we want! FROM OWNER, POSTALADDRESS

Result (total number of columns and rows): • Number of columns = columns in OWNER + columns in POSTALADDRESS

• Number of rows = rows in OWNER * rows in POSTALADDRESS

Rows for each person connected to each Postal Code

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 14 Aliases introduced in the FROM-part, have to be used Use of aliases already in the SELECT-part (when refering to tables) SELECT OwnerId, Lname, POSTALADDRESS.PostalCode FROM OWNER, POSTALADDRESS Here we have to use it Here we can use it, (because more than one table but don’t have to has the same column name)

SELECT O.OwnerId, LName, P.PostalCode FROM OWNER AS O, POSTALADDRESS AS P

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 15 «EQUI JOIN» (based on equality) (with WHERE)

SELECT * FROM OWNER AS O, POSTALADDRESS AS P WHERE O.PostalCode = P.PostalCode O.PostalCode = P.PostalCode Result:

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 16 INNER JOIN (alternative equi -notation)

SELECT * FROM OWNER AS O INNER JOIN POSTALADDRESS AS P ON O.PostalCode = P.PostalCode Result (the same as with WHERE on the previous slide):

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 17 JOIN: Get data from multiple tables (here two)

• We want the following data: OwnerID, LName, PostalCode and City for all persons with PostalCode that starts with the number 3, ordered ascending on postaladdress.

• We need to retrieve data from two tables

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 18 SOLUTION (with WHERE-syntax) SELECT OwnerID, LName, POSTALADDRESS.PostalCode, City FROM OWNER, POSTALADDRESS WHERE OWNER.PostalCode = POSTALADDRESS.PostalCode AND POSTALADDRESS.PostalCode LIKE '3%' ORDER BY POSTALADDRESS.PostalCode ASC

The result:

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 19 SOLUTION (with INNER JOIN-syntax) SELECT OwnerID, LName, POSTALADDRESS.PostalCode, City FROM OWNER INNER JOIN POSTALADDRESS ON OWNER.PostalCode = POSTALADDRESS.PostalCode WHERE POSTALADDRESS.PostalCode LIKE '3%' ORDER BY POSTALADDRESS.PostalCode ASC

The result:

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 20 JOIN: Get data from three tables

• We want the following data: OwnerId, Lname, City, RegNumber, CarMake, with one row for each car.

• We need to retrieve data from three tables.

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 21 SOLUTION (with WHERE-syntax) (3 tables) SELECT OWNER.OwnerID, LName, City, RegNumber, CarMake FROM CAR, OWNER, POSTALADDRESS WHERE OWNER.PostalCode = POSTALADDRESS.PostalCode AND OWNER.OwnerId = CAR.OwnerId ORDER BY OWNER.OwnerId ASC

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 22 SOLUTION (with INNER JOIN-syntax) (3 tables)

SELECT OWNER.OwnerID, LName, City, RegNumber, CarMake FROM CAR INNER JOIN OWNER ON CAR.OwnerId = OWNER.OwnerId INNER JOIN POSTALADDRESS ON OWNER.PostalCode = POSTALADDRESS.PostalCode ORDER BY OWNER.OwnerId ASC

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 23 Teller forekomster GROUP BY (when joining tables) (biler) i hver gruppe SELECT OWNER.OwnerID, LName, City , COUNT(*) AS [Num cars] FROM CAR, OWNER, POSTALADDRESS WHERE OWNER.PostalCode = POSTALADDRESS.PostalCode AND OWNER.OwnerId = CAR.OwnerId GROUP BY OWNER.OwnerID, LName, City

NB! Kolonner som tas med i SELECT-delen, må også tas med i GROUP BY-delen!

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 24 GROUP BY (when joining tables) SELECT OWNER.OwnerID, LName, City , COUNT(*) AS [Num cars] FROM CAR, OWNER, POSTALADDRESS WHERE OWNER.PostalCode = POSTALADDRESS.PostalCode AND OWNER.OwnerId = CAR.OwnerId GROUP BY OWNER.OwnerID, LName, City

HAVING COUNT(*) >= 3 Only owners with three or more cars

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 25 Queries with additional constraints SELECT OWNER.OwnerID, LName, City, RegNumber, CarMake FROM CAR, OWNER, POSTALADDRESS WHERE OWNER.PostalCode = POSTALADDRESS.PostalCode AND OWNER.OwnerId = CAR.OwnerId AND RegNumber LIKE 'AA%' AND (Price >= 300000) Additional constraints AND CarMake IN ('Volvo','Nissan','Audi')

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 26 OUTER JOIN LEFT TABLE RIGHT TABLE CAR

OWNER

No match

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 27 LEFT OUTER JOIN

SELECT *

FROM CAR LEFT OUTER JOIN OWNER /* Include all the values from the CAR-table */

ON CAR.OwnerId = OWNER.OwnerId

ORDER BY OWNER.OwnerId

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 28 The result of «LEFT OUTER JOIN»

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 29 RIGHT OUTER JOIN

SELECT *

FROM CAR RIGHT OUTER JOIN OWNER /* Include all the values from the OWNER-table */

ON CAR.OwnerId = OWNER.OwnerId

ORDER BY OWNER.OwnerId

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 30 The result of «RIGHT OUTER JOIN»

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 31 FULL OUTER JOIN

SELECT OWNER.OwnerId, LName, RegNumber

FROM CAR FULL OUTER JOIN OWNER /* Include all the values from both tables */

ON CAR.OwnerId = OWNER.OwnerId

ORDER BY OWNER.OwnerId

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 32 The result of «FULL OUTER JOIN»

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 33 A simple subquery

SELECT OWNER.OwnerId, LName, RegDate, CarMake, Price FROM OWNER, CAR WHERE OWNER.OwnerId = CAR.OwnerId AND Price >= (SELECT AVG(Price) FROM CAR)

This subquery only needs to be evaluated once. The result is then used by the main query

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 34 Making an INSERT-script, part 1

1 • Right click over the Database name

• Select Tasks -> Generate Scripts 2

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 40 Making an INSERT-script, part 2

3 Finish the wizard 7

Choose how to save the script 4

6

Select a table 5

25.09.2018 OD: SQL Part 3 - Data Manipulation Language (DML) - Joining tables 41