Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Systems - Introduction to Databases and Data Warehouses

Similar presentations


Presentation on theme: "Database Systems - Introduction to Databases and Data Warehouses"— Presentation transcript:

1 Database Systems - Introduction to Databases and Data Warehouses
CHAPTER 5 - SQL

2 INTRODUCTION SQL - Structured Query Language SQL is used for:
Creating databases Adding, modifying and deleting database structures Inserting, deleting, and modifying records in databases Querying databases (data retrieval) SQL functions as a standard relational database language It can be used (with minor dialectical variations) with the majority of relational DBMS software tools Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 2

3 INTRODUCTION SQL commands – categories: Data Definition Language (DDL)
Data Manipulation Language (DML) Data Control Language (DCL) Transaction Control Language (TCL) Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 3 3

4 INTRODUCTION Data Definition Language (DDL)
Used to create and modify the structure of the database Example commands: CREATE ALTER DROP Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 4 4

5 INTRODUCTION Data Manipulation Language (DML)
Used to insert, modify, delete and retrieve data Example commands: INSERT INTO UPDATE DELETE SELECT Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 5

6 INTRODUCTION Data Control Language (DCL)
Used for data access control Transaction Control Language (TCL) Used for managing database transactions Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 6 6

7 INTRODUCTION SQL data types
Each column of each SQL created relation has a specified data type Commonly used SQL data types: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 7 7

8 INTRODUCTION Brief SQL syntax notes
Semicolon “;” following the end of an SQL statement, indicates the end of the SQL command In a list of multiple SQL statements the semicolon indicates where each SQL statement ends SQL keywords, as well as the table and column names used in the SQL commands, are not case sensitive E.g. SELECT is the same as select or SeLeCt An SQL statement can be written as one long sentence in one line of text However, for legibility reasons SQL statements are usually broken down into multiple lines of text Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 8 8

9 CREATE TABLE CREATE TABLE
Used for creating and connecting relational tables DCL and TCL statements are covered in Chapter 10. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 9 9

10 ER diagram : ZAGI Retail Company Sales Department Database
Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 10 10

11 Relational schema: ZAGI Retail Company Sales Department Database
Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 11 11

12 CREATE TABLE statements for ZAGI Retail Company Sales Department Database
CREATE TABLE vendor ( vendorid CHAR(2) NOT NULL, vendorname VARCHAR(25) NOT NULL, PRIMARY KEY (vendorid) ); CREATE TABLE category ( categoryid CHAR(2) NOT NULL, categoryname VARCHAR(25) NOT NULL, PRIMARY KEY (categoryid) ); CREATE TABLE product ( productid CHAR(3) NOT NULL, productname VARCHAR(25) NOT NULL, productprice NUMERIC(7,2) NOT NULL, vendorid CHAR(2) NOT NULL, categoryid CHAR(2) NOT NULL, PRIMARY KEY (productid), FOREIGN KEY (vendorid) REFERENCES vendor(vendorid), FOREIGN KEY (categoryid) REFERENCES category(categoryid) ); CREATE TABLE region ( regionid CHAR(1) NOT NULL, regionname VARCHAR(25) NOT NULL, PRIMARY KEY (regionid) ); This example is discussed on Page 70. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 12 12

13 CREATE TABLE statements for ZAGI Retail Company Sales Department Database
CREATE TABLE store ( storeid VARCHAR(3) NOT NULL, storezip CHAR(5) NOT NULL, regionid CHAR(1) NOT NULL, PRIMARY KEY (storeid), FOREIGN KEY (regionid) REFERENCES region(regionid) ); CREATE TABLE customer ( customerid CHAR(7) NOT NULL, customername VARCHAR(15) NOT NULL, customerzip CHAR(5) NOT NULL, PRIMARY KEY (customerid) ); CREATE TABLE salestransaction ( tid VARCHAR(8) NOT NULL, customerid CHAR(7) NOT NULL, storeid VARCHAR(3) NOT NULL, tdate DATE NOT NULL, PRIMARY KEY (tid), FOREIGN KEY (customerid) REFERENCES customer(customerid), FOREIGN KEY (storeid) REFERENCES store(storeid) ); CREATE TABLE soldvia ( productid CHAR(3) NOT NULL, tid VARCHAR(8) NOT NULL, noofitems INT NOT NULL, PRIMARY KEY (productid, tid), FOREIGN KEY (productid) REFERENCES product(productid), FOREIGN KEY (tid) REFERENCES salestransaction(tid) ); This example is discussed on Page 70. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 13 13

14 DROP TABLE DROP TABLE Used to remove a table from the database
This example is discussed on Page 70. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 14 14

15 Cannot delete a parent entity
DROP TABLE statements for ZAGI Retail Company Sales Department Database INVALID SEQUENCE DROP TABLE region; DROP TABLE store; DROP TABLE salestransaction; DROP TABLE product; DROP TABLE vendor; DROP TABLE category; DROP TABLE customer; DROP TABLE soldvia; Cannot delete a parent entity This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 15 15

16 DROP TABLE statements for ZAGI Retail Company Sales Department Database
INVALID SEQUENCE DROP TABLE region; DROP TABLE store; DROP TABLE salestransaction; DROP TABLE product; DROP TABLE vendor; DROP TABLE category; DROP TABLE customer; DROP TABLE soldvia; VALID SEQUENCE DROP TABLE soldvia; DROP TABLE product; DROP TABLE salestransaction; DROP TABLE customer; DROP TABLE category; DROP TABLE vendor; DROP TABLE store; DROP TABLE region; This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 16 16

17 INSERT INTO INSERT INTO
Used to populate the created relations with data This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 17 17

18 Data records: ZAGI Retail Company Sales Department Database
Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 18 18

19 INSERT INTO statements for ZAGI Retail Company Sales Department Database
INSERT INTO vendor VALUES ('PG','Pacifica Gear'); INSERT INTO vendor VALUES ('MK','Mountain King'); INSERT INTO category VALUES ('CP','Camping'); INSERT INTO category VALUES ('FW','Footwear'); INSERT INTO product VALUES ('1X1','Zzz Bag',100,'PG','CP'); INSERT INTO product VALUES ('2X2','Easy Boot',70,'MK','FW'); INSERT INTO product VALUES ('3X3','Cosy Sock',15,'MK','FW'); INSERT INTO product VALUES ('4X4','Dura Boot',90,'PG','FW'); INSERT INTO product VALUES ('5X5','Tiny Tent',150,'MK','CP'); INSERT INTO product VALUES ('6X6','Biggy Tent',250,'MK','CP'); INSERT INTO region VALUES ('C','Chicagoland'); INSERT INTO region VALUES ('T','Tristate'); INSERT INTO store VALUES ('S1','60600','C'); INSERT INTO store VALUES ('S2','60605','C'); INSERT INTO store VALUES ('S3','35400','T'); INSERT INTO customer VALUES (' ','Tina','60137'); INSERT INTO customer VALUES (' ','Tony','60611'); INSERT INTO customer VALUES (' ','Pam','35401'); This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 19 19

20 INSERT INTO statements for ZAGI Retail Company Sales Department Database
INSERT INTO salestransaction VALUES ('T111',' ','S1','01/Jan/2013'); INSERT INTO salestransaction VALUES ('T222',' ','S2','01/Jan/2013'); INSERT INTO salestransaction VALUES ('T333',' ','S3','02/Jan/2013'); INSERT INTO salestransaction VALUES ('T444',' ','S3','02/Jan/2013'); INSERT INTO salestransaction VALUES ('T555',' ','S3','02/Jan/2013'); INSERT INTO soldvia VALUES ('1X1','T111',1); INSERT INTO soldvia VALUES ('2X2','T222',1); INSERT INTO soldvia VALUES ('3X3','T333',5); INSERT INTO soldvia VALUES ('1X1','T333',1); INSERT INTO soldvia VALUES ('4X4','T444',1); INSERT INTO soldvia VALUES ('2X2','T444',2); INSERT INTO soldvia VALUES ('4X4','T555',4); INSERT INTO soldvia VALUES ('5X5','T555',2); INSERT INTO soldvia VALUES ('6X6','T555',1); Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 20 20

21 SELECT SELECT Used for the retrieval of data from the database relations Most commonly issued SQL statement Basic form: SELECT <columns> FROM <table> This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 21 21

22 SELECT Query 1 text: Retrieve the entire contents of the relation PRODUCT Query 1: SELECT productid, productname, productprice, vendorid, categoryid FROM product; Query 1 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 22 22

23 SELECT Query 1 text: Retrieve the entire contents of the relation PRODUCT Query 1a: SELECT * FROM product; Query 1a result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 23 23

24 SELECT Query 2 text: Retrieve the entire contents of the relation PRODUCT and show the columns in the following order: ProductName, ProductID, VendorID, CategoryID, ProductPrice Query 2: SELECT productname, productid, vendorid, categoryid, productprice FROM product; Query 2 result: This example is discussed on Page 134. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 24 24

25 SELECT Query 3 text: For the relation PRODUCT, show the columns ProductID and ProductPrice Query 3: SELECT productid, productprice FROM product; Query 3 result: This example is discussed on Page 135. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 25 25

26 SELECT SELECT In addition to displaying columns, the SELECT clause can be used to display derived attributes (calculated columns) represented as expressions SELECT statement can be structured as follows: SELECT <columns, expressions> FROM <table> This example is discussed on Page 135. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 26 26

27 SELECT Query 3a text: For the relation PRODUCT, show the columns ProductID and ProductPrice Query 3a: SELECT productid, productprice, productprice * FROM product; Query 3a result: This example is discussed on Page 135. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 27 27

28 SELECT SELECT The SELECT FROM statement can contain other optional keywords, such as WHERE, GROUP BY, HAVING, and ORDER BY, appearing in this order: : SELECT <columns, expressions> FROM <tables> WHERE <row selection condition> GROUP BY <grouping columns> HAVING <group selection condition> ORDER BY <sorting columns, expressions> Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 28 28

29 WHERE WHERE WHERE condition determines which rows should be retrieved and consequently which rows should not be retrieved The logical condition determining which records to retrieve can use one of the following logical comparison operators: = Equal to < Less than > Greater than <= Less than or equal to >= Greater than or equal to != Not equal to <> Not equal to (alternative notation | uncommon) This example is discussed on Page 136. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 29 29

30 WHERE Query 4 text: Retrieve the product id, product name, vendor id, and product price for each product whose price is above $100 Query 4: SELECT productid, productname, vendorid, productprice FROM product WHERE productprice > 100; Query 4 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 30 30

31 WHERE Query 5 text: Retrieve the product id, product name, vendor id, and product price for each product in the FW category whose price is equal to or below $110 Query 5: SELECT productid, productname, vendorid, productprice FROM product WHERE productprice <= 110 AND categoryid = 'FW'; Query 5 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 31 31

32 DISTINCT DISTINCT Can be used in conjunction with the SELECT statement
Eliminates duplicate values from a query result This example is discussed on Page 136. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 32 32

33 DISTINCT Query 6 text: Retrieve the VendorID value for each record in the relation PRODUCT Query 6: SELECT vendorid FROM product; Query 6 result: This example is discussed on Page 137. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 33 33

34 DISTINCT Query 7 text: Show one instance of all the different VendorID values in the relation PRODUCT Query 7: SELECT DISTINCT vendorid FROM product; Query 7 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 34 34

35 ORDER BY ORDER BY Used to sort the results of the query by one or more columns (or expressions) This example is discussed on Page 137. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 35 35

36 ORDER BY Query 8 text: Retrieve the product id, product name, category id, and product price for each product in the FW product category, sorted by product price Query 8: SELECT productid, productname, categoryid, productprice FROM product WHERE categoryid = 'FW' ORDER BY productprice; Query 8 result: This example is discussed on Page 137. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 36 36

37 ORDER BY Query 9 text: Retrieve the product id, product name, category id, and product price for each product in the FW product category, sorted by product price in descending order Query 9: SELECT productid, productname, categoryid, productprice FROM product WHERE categoryid = 'FW' ORDER BY productprice DESC; Query 9 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 37 37

38 ORDER BY Query 10 text: Retrieve the product id, product name, category id, and product price for each product, sorted by category id and, within the same category id, by product price Query 10 : SELECT productid, productname, categoryid, productprice FROM product ORDER BY categoryid, productprice; Query 10 result: This example is discussed on Page 138. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 38 38

39 LIKE LIKE Used for retrieval of records whose values partially match a certain criteria This example is discussed on Page 138. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 39 39

40 LIKE Query 11 text: Retrieve the record for each product whose product name contains the phrase ’Boot’ Query 11 : SELECT * FROM product WHERE productname LIKE '%Boot%'; Query 11 result: This example is discussed on Page 138. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 40 40

41 Like Operator - Patterns
DESCRIPTION WHERE CustomerName LIKE 'a%' Finds any values that start with "a" WHERE CustomerName LIKE '%a' Finds any values that end with "a" WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position WHERE CustomerName LIKE 'a_%_%' Finds any values that start with "a" and are at least 3 characters in length WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and ends with "o" Tip: You can also combine any number of conditions using AND or OR operators Reference:

42 AGGREGATE FUNCTIONS Aggregate functions
For calculating and summarizing values in queries, SQL provides the following aggregate functions: COUNT SUM AVG MIN MAX Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 42 42

43 AGGREGATE FUNCTIONS Query 12 text: Retrieve the average price of all products Query 12 : SELECT AVG(productprice) FROM product; Query 12 result: This example is discussed on Page 139. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 43 43

44 AGGREGATE FUNCTIONS Query 13 text: Show how many products we offer for sale Query 13 : SELECT COUNT(*) FROM product; Query 13 result: Functions SUM and AVG operate on numeric values only. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 44 44

45 AGGREGATE FUNCTIONS Query 14 text: Retrieve the number of vendors that supply our products Query 14 : SELECT COUNT(DISTINCT vendorid) FROM product; Query 14 result: This example is discussed on Page 139. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 45 45

46 AGGREGATE FUNCTIONS Query 15 text: Retrieve the number of products, average product price, lowest product price, and highest product price in the CP product category Query 15 : SELECT COUNT(*), AVG(productprice), MIN(productprice), MAX(productprice) FROM product WHERE categoryid = 'CP'; Query 15 result: This example is discussed on Page 139. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 46 46

47 GROUP BY GROUP BY Enables summarizations across the groups of related data within tables The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the result-set by one or more columns This example is discussed on Page 140. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 47 47

48 Out source – Group By Examples
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country; This example is discussed on Page 140. Reference: 48

49 Out source – Group By Examples
This example is discussed on Page 140. Reference: Chapter 5 – Slide 49 49

50 Out source – Group By Examples
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country ORDER BY COUNT(CustomerID) DESC; This example is discussed on Page 140. Reference: Chapter 5 – Slide 50 50

51 Out source – Group By Examples
This example is discussed on Page 140. Reference: Chapter 5 – Slide 51 51

52 Out source – Group By Examples
SELECT COUNT(CustomerID) as counter, Country FROM Customers GROUP BY Country ORDER BY counter DESC; This example is discussed on Page 140. Reference: Chapter 5 – Slide 52 52

53 GROUP BY Query 16 text: For each vendor, retrieve the vendor id, number of products supplied by the vendor, and average price of the products supplied by the vendor Query 16 : SELECT vendorid, COUNT(*), AVG(productprice) FROM product GROUP BY vendorid; Query 16 result: This example is discussed on Page 140. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 53 53

54 Query 16 illustration 54 Jukić, Vrbsky, Nestorov – Database Systems
Chapter 5 – Slide 54 54

55 GROUP BY Query 16 text: For each vendor, retrieve the vendor id, number of products supplied by the vendor, and average price of the products supplied by the vendor Query 16 : SELECT vendorid, COUNT(*), AVG(productprice) INVALID FROM product; ERROR MESSAGE RETURNED This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 55 55

56 GROUP BY Query 17 text: For each vendor, retrieve the number of products supplied by the vendor and the average price of the products supplied by the vendor Query 17 : SELECT COUNT(*), AVG(productprice) FROM product GROUP BY vendorid; Query 17 result (vs. Query 16): This example is discussed on Pages Query 17 result Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 56 56

57 GROUP BY Query 18 text: For each vendor, retrieve the vendor id and the number of products with a product price of $100 or higher supplied by the vendor Query 18 : SELECT vendorid, COUNT(*) FROM product WHERE productprice >= GROUP BY vendorid; Query 18 result: This example is discussed on Page 142. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 57 57

58 GROUP BY Query 19 text: Consider the groups of products where each group contains the products that are from the same category supplied by the same vendor. For each such group, retrieve the vendor id, product category id, number of products in the group, and average price of the products in the group. Query 19 : SELECT vendorid, categoryid, COUNT(*), AVG(productprice) FROM product GROUP BY vendorid, categoryid; Query 19 result: This example is discussed on Pages 142. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 58 58

59 GROUP BY Query 20 text: For each product, retrieve the ProductID value and the total number of product items sold within all sales transactions. Query 20 : SELECT productid, SUM(noofitems) FROM soldvia GROUP BY productid; Query 20 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 59 59

60 GROUP BY Query 21 text: For each product, retrieve the ProductID value and the number of sales transactions in which the product was sold Query 21: SELECT productid, COUNT(*) FROM soldvia GROUP BY productid; Query 21 result: This example is discussed on Page 143. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 60 60

61 SELECT TOP, LIMIT, or ROWNUM Clause
SQL Select Top Is used to specify the number of records to return Useful on large tables with thousands of records Returning a large number of records can impact on performance Note Not all database systems support the SELECT TOP clause MYSQL supports the LIMIT clause to select a limited number of records Oracle uses ROWNUM This example is discussed on Page 143. 61

62 SELECT LIMIT - MYSQL MySQL Syntax SELECT column_name(s) FROM
table_name WHERE condition LIMIT number; SELECT * FROM Customers LIMIT 3; This example is discussed on Page 143. 62

63 LIMIT 3 This example is discussed on Page 143. 63

64 SQL BETWEEN Between Operator Syntax
It selects values within a given range Values can be numbers, text, or dates Syntax SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2; This example is discussed on Page 143. 64

65 BETWEEN Example SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20 LIMIT 3; This example is discussed on Page 143. 65

66 NOT BETWEEN Example SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20 LIMIT 3; This example is discussed on Page 143. 66

67 BETWEEN w\ IN Example SELECT * FROM Products
WHERE (Price BETWEEN 10 AND 20) AND NOT CategoryID IN (1, 2, 3) LIMIT 3; This example is discussed on Page 143. 67

68 BETWEEN Dates Example SELECT * FROM Orders WHERE OrderDate
BETWEEN ' ' AND ' ’ limit 3; This example is discussed on Page 143. 68

69 CONCAT - Concatenate SELECT
CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address FROM Customers; MySQL SELECT  CustomerName, CONCAT(Address,', ',PostalCode, ', ',City,', ',Country) AS Address FROM Customers; This example is discussed on Page 143. 69

70 HAVING HAVING Enables summarizations across groups of related data within tables Determines which groups will be displayed in the result of a query and, consequently, which groups will not be displayed in the result of the query A query that contains a HAVING clause must also contain a GROUP BY clause Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 70

71 HAVING vs. Where WHERE clause is used for filtering rows and it applies on each and every row, while HAVING clause is used to filter groups in SQL Where clause introduces a condition on individual rows Having clause introduces a condition on aggregations i.e. results of selection where a single result, such as count, average, min, max, or sum, has been produced from multiple rows As a rule of thumb, use WHERE before GROUP BY and HAVING after GROUP BY. It is a rather primitive rule but it is useful in more than 90% of the cases. This example is discussed on Page 145. 71

72 HAVING Query 22 text: Consider the groups of products where each group contains the products that are from the same category and supplied by the same vendor. For each such group that has more than one product, retrieve the vendor id, product category id, number of products in the group, and average price of the products in the group. Query 22: SELECT vendorid, categoryid, COUNT(*), AVG(productprice) FROM product GROUP BY vendorid, categoryid HAVING COUNT(*) > 1; Query 22 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 72 72

73 HAVING Query 23 text: Consider the groups of products where each group contains the products that are from the same category, supplied by the same vendor, and whose product price is $50 or higher. For each such group that has more than one product, retrieve the vendor id, product category id, number of products in the group, and average price of the products. Query 23: SELECT vendorid, categoryid, COUNT(*), AVG(productprice) FROM product WHERE productprice >= GROUP BY vendorid, categoryid HAVING COUNT(*) > 1; Query 23 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 73 73

74 HAVING Query 24 text: For each product that has more than three items sold within all sales transactions, retrieve the ProductID value and the total number of product items sold within all sales transactions Query 24: SELECT productid, SUM(noofitems) FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3; Query 24 result: This example is discussed on Page 144. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 74 74

75 HAVING Query 25 text: For each product that was sold in more than one sales transaction, retrieve the ProductID value and the number of sales transactions in which the product was sold Query 25: SELECT productid, COUNT(*) FROM soldvia GROUP BY productid HAVING COUNT(*) > 1; Query 25 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 75 75

76 HAVING Query 26 text: For each product that has more than three items sold within all sales transactions, retrieve the ProductID value Query 26: SELECT productid FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3; Query 26 result: This example is discussed on Page 145. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 76 76

77 HAVING Query 27 text: For each product that was sold in more than one sales transaction, retrieve the ProductID value Query 27: SELECT productid FROM soldvia GROUP BY productid HAVING COUNT(*) > 1; Query 27 result: This example is discussed on Page 145. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 77 77

78 NESTED QUERIES Nested Query A query that is used within another query
A nested query is also referred to as an inner query, The query that uses the nested query is referred to as an outer query This example is discussed on Page 146. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 78 78

79 NESTED QUERIES Query 28 text: For each product whose product price is below the average price of all products, retrieve the product id, product name, and product price Query 28: SELECT productid, productname, productprice FROM product WHERE productprice < ( SELECT AVG(productprice) FROM product); Query 28 result: This example is discussed on Page 146. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 79 79

80 NESTED QUERIES Query 28 text: For each product whose product price is below the average price of all products, retrieve the product id, product name, and product price Query 28: SELECT productid, productname, productprice INVALID FROM product WHERE productprice < AVG(productprice); A query may contain another query (or queries). Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 80 80

81 SQL IN Operator IN Operator Syntax
Used for comparison of a value with a set of values It allows you to specify multiple values in a WHERE clause Is a shorthand for multiple or conditions Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1, value2, …, valueN); SELECT column_name(s) FROM table_name WHERE column_name IN (SELECT STATEMENT); This example is discussed on Page 143. 81

82 IN Operator SELECT * FROM Customers WHERE Country
IN (‘Germany’, ‘France’, ‘UK’); This example is discussed on Page 143. 82

83 IN Operator – query result
SELECT * FROM Customers WHERE Country IN (‘Germany’, ‘France’, ‘UK’) LIMIT 3; This example is discussed on Page 143. 83

84 NOT IN Operator SELECT * FROM Customers WHERE Country
NOT IN (‘Germany’, ‘France’, ‘UK’); This example is discussed on Page 143. 84

85 IN Operator – query result
SELECT * FROM Customers WHERE Country NOT IN (‘Germany’, ‘France’, ‘UK’) LIMIT 3; This example is discussed on Page 143. 85

86 IN Operator – inner query
SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers); This example is discussed on Page 143. 86

87 IN – Additional Samples
Query 29 text: For each product that has more than three items sold within all sales transactions, retrieve the product id, product name, and product price Query 29: SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3); Query 29 result: This example is discussed on Page 146. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 87 87

88 IN – Additional Samples
Query 30 text: For each product whose items were sold in more than one sales transaction, retrieve the product id, product name and product price Query 30 : SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING COUNT(*) > 1); Query 30 result: This example is discussed on Page Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 88 88

89 Exercises/Demo Write a query that returns all regions that have no stores Write a query that returns all customers who have not bought anything Write a query that returns all customers who have made purchases This example is discussed on Page 89

90 JOIN A join clause is used to combine rows from two or more tables
Based on a related column between them (PK/FK) This example is discussed on Page 147. 90

91 Types of JOIN Inner Join (default): returns records that have matching values in both tables Left (Outer) Join: Return all records from the left table, and the matched records from the right table Right (Outer) Join: Return all records from the right table, and the matched records from the left table Full (Outer) Join:  Return all records when there is a match in either left or right table This example is discussed on Page 147. 91

92 Types of JOIN This example is discussed on Page 147. 92

93 Inner Join Syntas The INNER JOIN keyword selects records that have matching values in both tables. select regionname from store inner join region on region.regionid = store.regionid; This example is discussed on Page 93

94 Inner Join Syntax w/ Group By
select regionname, count(*) as number_of_stores from store inner join region on region.regionid = store.regionid group by regionname; This example is discussed on Page 94

95 Inner Join Syntax w/ Group By
select regionname, count(*) as number_of_stores from store inner join region on region.regionid = store.regionid group by regionname; having number_of_stores > 1 This example is discussed on Page 95

96 LEFT JOIN The left join keyword returns all records from the left table (table1), and the matched records from the right table (table2). The result is NULL from the right side, if there is no match SELECT column_name(s) FROM table1 LEFT JOIN table2 ON table1.column_name = table2.column_name; This example is discussed on Page 96

97 RIGHT JOIN The RIGHT JOIN keyword returns all records from the right table (table2), and the matched records from the left table (table1). The result is NULL from the left side, when there is no match. SELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name; This example is discussed on Page 97

98 FULL OUTTER JOIN The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right (table2) table records. Note: FULL OUTER JOIN can potentially return very large result-sets! SELECT column_name(s) FROM table1 FULL OUTER JOIN table2 ON table1.column_name = table2.column_name; This example is discussed on Page 98

99 DEMO

100 DEMO DEMO

101 DEMO Customer City

102 DEMO - INNER JOIN Customer City

103 DEMO - LEFT OUTER JOIN Customer City

104 DEMO - RIGHT OUTER JOIN Customer City

105 DEMO – FULL OUTER JOIN Customer City

106 ENTITY/Relation ALIAS
An alternative and usually shorter name that can be used anywhere within a query instead of the full relation name This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 106 106

107 ALIAS Query 31 text: For each product, retrieve the product id, name of the product, name of the vendor of the product, and price of the product Query 31: SELECT productid, productname, vendorname, productprice FROM product, vendor WHERE product.vendorid = vendor.vendorid; Query 31 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 107 107

108 ALIAS Query 31a text: For each product, retrieve the product id, name of the product, (same query) name of the vendor of the product, and price of the product Query 31a: SELECT p.productid, p.productname, v.vendorname, p.productprice FROM product p, vendor v WHERE p.vendorid = v.vendorid; Query 31a result: (same result) Columns can also have aliases but their use is more restricted within a query. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 108 108

109 ALIAS Query 31b text: For each product, retrieve the product id, name of the product, (same query) name of the vendor of the product, and price of the product Query 31b: SELECT p.productid pid, p.productname pname, v.vendorname vname, p.productprice pprice FROM product p, vendor v WHERE p.vendorid = v.vendorid; Query 31b result: (same result, different column names in the result) This example is discussed on Page 151. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 109 109

110 ALIAS Query 31c text: For each product, retrieve the product id, name of the product, (same query) name of the vendor of the product, and price of the product Query 31c: SELECT p.productid AS pid, p.productname AS pname, v.vendorname AS vname, p.productprice AS pprice FROM product p, vendor v WHERE p.vendorid = v.vendorid; Query 31c result: (same result, as Query 31b) This example is discussed on Page 151. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 110 110

111 ALTER TABLE (DML) ALTER TABLE
Used to change the structure of the relation, once the relation is already created This example is discussed on Page 152. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 111 111

112 ALTER TABLE Alter Statement 1: ALTER TABLE vendor ADD ( vendorphonenumber CHAR(11)); Alter Statement 2: ALTER TABLE vendor DROP ( vendorphonenumber); This example is discussed on Page 151. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 112 112

113 UPDATE UPDATE Used to modify the data stored in database relations 113
Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 113 113

114 UPDATE Insert Statement 1: INSERT INTO product VALUES ('7×7','Airy Sock',1000,'MK','CP'); Update Statement 1: UPDATE product SET productprice = WHERE productid = '7×7'; Alter Statement 3: ALTER TABLE product ADD (discount NUMERIC(3,2) ); Update Statement 2: UPDATE product SET discount = 0.2; Update Statement 3: UPDATE product SET discount = WHERE vendorid = 'MK'; Alter Statement 4: ALTER TABLE product DROP (discount); This example is discussed on Page 153. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 114 114

115 DELETE DELETE Used to delete the data stored in database relations
This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 115 115

116 DELETE Delete Statement 1: DELETE FROM product WHERE productid = '7×7'; This example is discussed on Page 154. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 116 116

117 VIEW VIEW Mechanism in SQL that allows the structure of a query to be saved in the RDBMS Also known as a virtual table View is not an actual table and does not have any data physically saved Every time a view is invoked, it executes a query that retrieves the data from the actual tables A view can be used in SELECT statements just like any other table from a database Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 117 117

118 VIEW Create View Statement 1:
CREATE VIEW products_more_than_3_sold AS SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid AVING SUM(noofitems) > 3); Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 118 118

119 VIEW Query 29 text: For each product that has more than three items sold within all sales transactions, retrieve the product id, product name, and product price Query 29: SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3); Query 29 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 119 119

120 VIEW Query 29a text: For each product that has more than three items sold within all (same query) sales transactions, retrieve the product id, product name, and product price Query 29a: SELECT * FROM products_more_than_3_sold; Query 29a result: (same result) This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 120 120

121 VIEW Create View Statement 2:
CREATE VIEW products_in_multiple_trnsc AS SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING COUNT(*) > 1); This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 121 121

122 VIEW Query 30 text: For each product whose items were sold in more than one sales transaction, retrieve the product name and product price Query 30 : SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING COUNT(*) > 1); Query 30 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 122 122

123 VIEW Query 30a text: For each product whose items were sold in more than one sales (same query) transaction, retrieve the product name and product price Query 30a : SELECT * FROM products_in_multiple_trnsc; Query 30a result: (same result) This example is discussed on Page 155. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 123 123

124 VIEW Views will remain stored in the database such as tables
list all views in the database using the following: SHOW FULL TABLES IN databse_name WHERE TABLE_TYPE LIKE 'VIEW’; Update a View: CREATE OR REPLACE VIEW view_name AS SELECT column1, column2, ... FROM table_name WHERE condition; Delete/Drop a view: DROP VIEW view_name; This example is discussed on Page 155. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 124 124

125 SET OPERATORS Set operators
Standard set operators: union, intersection, and difference Used to combine the results of two or more SELECT statements that are union compatible Two sets of columns are union compatible if they contain the same number of columns, and if the data types of the columns in one set match the data types of the columns in the other set The first column in one set has a compatible data type with the data type of the first column in the other set, the second column in one set has a compatible data type with the data type of the second column in the other set, and so on. The set operators can combine results from SELECT statements querying relations, views, or other SELECT queries. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 125

126 SET OPERATORS UNION Used to combine the union compatible results of two SELECT statements by listing all rows from the result of the first SELECT statement and all rows from the result of the other SELECT statement If two or more rows are identical only one of them is shown (duplicates are eliminated from the result) Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 126

127 SET OPERATORS Query 36 text: Retrieve the product id, product name, and product price for each product that has more than three items sold within all sales transactions or whose items were sold in more than one sales transaction Query 36: SELECT * FROM products_more_than_3_sold UNION SELECT * FROM products_in_multiple_trnsc; Query 36 result: This example is discussed on Page 155. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 127 127

128 SET OPERATORS INTERSECT
Used to combine the results of two SELECT statements that are union compatible by listing every row that appears in the result of both of the SELECT statements This example is discussed on Page 155. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 128 128

129 SET OPERATORS Query 37 text: Retrieve the product id, product name, and product price for each product that has more than three items sold within all sales transactions and whose items were sold in more than one sales transaction Query 37: SELECT * FROM products_more_than_3_sold INTERSECT SELECT * FROM products_in_multiple_trnsc; Query 37 result: Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 129 129

130 SET OPERATORS MINUS (EXCEPT)
Used to combine the results of two SELECT statements that are union compatible by listing every row from the result of the first SELECT statement that does not appear in the result of the other SELECT statement Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 130 130

131 SET OPERATORS Query 38 text: Retrieve the product id, product name, and product price for each product that has more than three items sold within all sales transactions but whose items were not sold in more than one sales transaction Query 38: SELECT * FROM products_more_than_3_sold MINUS SELECT * FROM products_in_multiple_trnsc; Query 38 result: This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 131 131

132 IS NULL IS NULL Used in queries that contain comparisons with an empty value in a column of a record This example is discussed on Pages Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 132 132

133 IS NULL Query 45 text: Retrieve records for all managers who do not have a bonus Query 45: SELECT * FROM manager WHERE mbonus IS NULL; Query 45 result: Regular JOIN is also sometimes referred to as an INNER JOIN, to differentiate it from the OUTER JOIN. Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 133 133

134 INSERTING FROM A QUERY Inserting from a query
A query retrieving the data from one relation can be used to populate another relation Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 134 134

135 INSERTING FROM A QUERY Create Table Statement 1: CREATE TABLE cleaningdenormalized ( buildingid CHAR(3) NOT NULL, aptno CHAR(5) NOT NULL, smemberid CHAR(4) NOT NULL, smembername VARCHAR(15) NOT NULL, PRIMARY KEY (buildingid, aptno, smemberid)); Insert Statement 2: INSERT INTO cleaningdenormalized SELECT c.buildingid, c.aptno, s.smemberid, s.smembername FROM cleaning c, staffmember s WHERE c.smemberid = s.smemberid; Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 135 135

136 CASE The CASE statement goes through conditions and return a value when the first condition is met (like an IF-THEN-ELSE statement) So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause If there is no ELSE part and no conditions are true, it returns NULL CASE     WHEN condition1 THEN result1     WHEN condition2 THEN result2     WHEN conditionN THEN resultN     ELSE result END; Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 136 136

137 CASE SELECT OrderID, Quantity, CASE     WHEN Quantity > 30 THEN "The quantity is greater than 30"     WHEN Quantity = 30 THEN "The quantity is 30"     ELSE "The quantity is under 30" END AS QuantityText FROM OrderDetails; Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 137 137

138 CASE SELECT OrderID, Quantity, CASE     WHEN Quantity > 30 THEN "The quantity is greater than 30"     WHEN Quantity = 30 THEN "The quantity is 30"     ELSE "The quantity is under 30" END AS QuantityText FROM OrderDetails; Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 138 138

139 CASE The following SQL will order the customers by City. However, if City is NULL, then order by Country: SELECT CustomerName, City, Country FROM Customers ORDER BY (CASE WHEN City IS NULL THEN Country ELSE City END); Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 139 139

140 COMMENTS Single line comments start with -- Multi-line Comments
--Select all: SELECT * FROM Customers; Multi-line Comments /*Select all the columns of all the records in the Customers table:*/ SELECT * FROM Customers; SELECT /* city, */ quantity from Customer; Jukić, Vrbsky, Nestorov – Database Systems Chapter 5 – Slide 140 140

141 REFERENCE W3Schools Can be accessed via: [ 141


Download ppt "Database Systems - Introduction to Databases and Data Warehouses"

Similar presentations


Ads by Google