Chapter 4 Structured Query Language

107
CHAPTER 4 STRUCTURED QUERY LANGUAGE (SQL) DFC2033 DATABASE SYSTEM

Transcript of Chapter 4 Structured Query Language

Page 1: Chapter 4 Structured Query Language

CHAPTER 4 STRUCTURED QUERY LANGUAGE (SQL)

DFC2033 DATABASE SYSTEM

Page 2: Chapter 4 Structured Query Language

Course Learning Outcome � CLO1 : Explain the fundamentals

concepts of database management and relational data model to create a database based on an organization’s requirements.

� CLO3 : Solve an organization’s requirements by selecting the correct database query formulation using an appropriate commercial Database Management System (DBMS).

Page 3: Chapter 4 Structured Query Language

At the end of this class you should know. �  Use SQL commands to database. �  State the use of Structured Query Language (SQL). �  Define the two main sublanguages in SQL

commands: a. Data Definition Language (DDL) b. Data manipulation Language (DML)

�  Describe the functions of the four basic DDL commands: a. CREATE b. USE c. ALTER d. DROP

Page 4: Chapter 4 Structured Query Language

Introduction to SQL §  Structured Query Language. §  Standard Relational database language. §  Originally SQL was called SEQUEL (Structured

English QUEry Language) §  Was design an implemented at IBM research. §  Now become standard for commercial

relational DBMS §  Divided into two types of language:

§  Data Definition Language (DDL) §  Data Manipulation Language (DML)

4

Page 5: Chapter 4 Structured Query Language

Use of SQL ¡  Allow user to create database

and relation structure ¡  Perform basic data

management tasks, such as the insertion, modification, and deletion of data from the relations

¡  Perform both simple and complex queries

5

Page 6: Chapter 4 Structured Query Language

What SQL can do? §  SQL can execute queries against a database §  SQL can retrieve data from a database §  SQL can insert records in a database §  SQL can update records in a database §  SQL can delete records from a database §  SQL can create new databases §  SQL can create new tables in a database §  SQL can create stored procedures in a database §  SQL can create views in a database §  SQL can set permissions on tables, procedures,

and views

6

Page 7: Chapter 4 Structured Query Language

DDL �  Create database and tables �  Modify the structure of the existing tables and

other objects in the database. �  Some DDL commands

� CREATE DATABASE - creates a new database � USE DATABASE – select database to work with � ALTER DATABASE - modifies a database � CREATE TABLE - creates a new table � ALTER TABLE - modifies a table � DROP TABLE - deletes a table

7

Page 8: Chapter 4 Structured Query Language

DML � A language for manipulation of data

inside the database. � The statement used to work with data

inside the tables. � Some DML commands:

� SELECT - extracts data from a database � UPDATE - updates data in a database � DELETE - deletes data from a database �  INSERT INTO - inserts new data into a

database

8

Page 9: Chapter 4 Structured Query Language

SQL DATA TYPE (TEXT)

9

Data type Description CHAR(size) Holds a fixed length string (can contain letters,

numbers, and special characters). The fixed size is specified in parenthesis. Can store up to 255 characters

VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greater value than 255 it will be converted to a TEXT type

TINYTEXT Holds a string with a maximum length of 255 characters TEXT Holds a string with a maximum length of 65,535

characters BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535

bytes of data

Page 10: Chapter 4 Structured Query Language

SQL DATA TYPE (TEXT) MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes

of data LONGTEXT Holds a string with a maximum length of 4,294,967,295

characters LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295

bytes of data ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535

values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. Note:  The  values  are  sorted  in  the  order  you  enter  them.  You  enter  the  possible  values  in  this  format:  ENUM('X','Y','Z')  

SET Similar to ENUM except that SET may contain up to 64 list items and can store more than one choice

10

Page 11: Chapter 4 Structured Query Language

SQL DATA TYPE (NUMBER)

11

Data type Description TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum

number of digits may be specified in parenthesis SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The

maximum number of digits may be specified in parenthesis MEDIUMINT(size) -8388608 to 8388607 normal. 0 to 16777215 UNSIGNED*.

The maximum number of digits may be specified in parenthesis

INT(size) -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis

BIGINT(size) -9223372036854775808 to 9223372036854775807 normal. 0 to 18446744073709551615 UNSIGNED*. The maximum number of digits may be specified in parenthesis

Page 12: Chapter 4 Structured Query Language

SQL DATA TYPE (NUMBER) FLOAT(size,d) A small number with a floating decimal point. The maximum

number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter

12

Page 13: Chapter 4 Structured Query Language

SQL DATA TYPE (DATE)

13

Data type Description DATE() A date. Format: YYYY-MM-DD

Note: The supported range is from '1000-01-01' to '9999-12-31' DATETIME() *A date and time combination. Format: YYYY-MM-DD

HH:MM:SS Note: The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'

TIMESTAMP() *A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD HH:MM:SS Note: The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC

TIME() A time. Format: HH:MM:SS Note: The supported range is from '-838:59:59' to '838:59:59'

YEAR() A year in two-digit or four-digit format. Note: Values allowed in four-digit format: 1901 to 2155. Values allowed in two-digit format: 70 to 69, representing years from 1970 to 2069

Page 14: Chapter 4 Structured Query Language

CREATE 1.  Create database CREATE DATABASE databasename; CREATE DATABASE pbu; 2.  Select Database to work with USE pbu;

14

Page 15: Chapter 4 Structured Query Language

CREATE 3.  Create table CREATE TABLE tablename ( attribute1 datatype (n), attribute2 datatype (n), attributen datatype (n) ); ** A constraint can be applied on the attribute.

15

Page 16: Chapter 4 Structured Query Language

CREATE CREATE TABLE student ( f_name VARCHAR(25) NOT NULL, l_name VARCHAR(25), AGE DATE );

16

Page 17: Chapter 4 Structured Query Language

CREATE TABLE WITH PRIMARY KEY CREATE TABLE product ( prod_id CHAR(10) PRIMARY KEY NOT NULL, prod_name VARCHAR(10) NOT NULL, prod_quantity INT(10) );

17

Page 18: Chapter 4 Structured Query Language

CREATE TABLE WITH PRIMARY KEY AND FOREIGN KEY CREATE TABLE customer ( cust_id CHAR(10) PRIMARY KEY NOT NULL, f_name VARCHAR(10) NOT NULL, l_name INT(10), product_id CHAR(10), FOREIGN KEY (product_id) REFERENCES product (prod_id); );

18

Page 19: Chapter 4 Structured Query Language

ALTER Add column to the table: ALTER TABLE tablename ADD attributename datatype(n); ALTER TABLE student ADD addresss VARCHAR(20) NOT NULL, ADD phone_num VARCHAR(20), ADD PRIMARY KEY (stud_id) ;

19

Page 20: Chapter 4 Structured Query Language

ALTER ALTER TABLE product DROP prod_name, DROP primary key;

20

Page 21: Chapter 4 Structured Query Language

DROP 1.  Remove database DROP DATABASE databasename; DROP database pbu; ** all database including tables are deleted. 2.  Remove table DROP TABLE tablename; ** all data and table structure will be deleted.

21

Page 22: Chapter 4 Structured Query Language

To be continued…

Page 23: Chapter 4 Structured Query Language
Page 24: Chapter 4 Structured Query Language

At the end of this class you should know.

� Describe the functions of the following DML commands: a. INSERT b. SELECT c. UPDATE d. DELETE

Page 25: Chapter 4 Structured Query Language

INSERT � Add one or more tuples to a relation � Attribute values should be listed in the

same order as in the CREATE TABLE command.

INSERT tablename VALUE (value1, value2, valuen);

25

Page 26: Chapter 4 Structured Query Language

INSERT EXAMPLE: INSERT INTO EMPLOYEE VALUES ('Richard','K','Marini', '653298653', '30-DEC 52‘ '98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 )

26

Page 27: Chapter 4 Structured Query Language

INSERT � An alternate form of INSERT specifies

explicitly the attribute names that correspond to the values in the new tuple.

� Attributes with NULL values can be left out � Example: Insert a tuple for a new

EMPLOYEE for whom we only know the FNAME, LNAME, and SSN attributes.

INSERT INTO EMPLOYEE (FNAME,LNAME, SSN) VALUES ('Richard', 'Marini', '653298653');

27

Page 28: Chapter 4 Structured Query Language

UPDATE �  Used to modify attribute values of one or more

selected tuples �  A WHERE-clause selects the tuples to be modified �  An additional SET-clause specifies the attributes to

be modified and their new values �  Each command modifies tuples in the same

relation UPDATE tablename SET attributename=newvalue WHERE codition;

28

Page 29: Chapter 4 Structured Query Language

UPDATE �  Change the location and controlling

department number of project number 10 to 'Bellaire' and 5, respectively.

UPDATE PROJECT SET PLOCATION = 'Bellaire', DNUM = 5 WHERE PNUMBER=10 ** You have to specify the where condition. If not all tuples will be change to Bellaire and 5 in attribute PLOCATION and DNUM

29

Page 30: Chapter 4 Structured Query Language

EXAMPLE UPDATE EMPLOYEE SET SALARY = SALARY *1.1 WHERE PNUMBER = 10;

30

Page 31: Chapter 4 Structured Query Language

DELETE �  Removes tuples from a relation �  Includes a WHERE-clause to select the tuples

to be deleted �  Tuples are deleted from only one table at a

time �  A missing WHERE-clause specifies that all

tuples in the relation are to be deleted; the table then becomes an empty table

�  The number of tuples deleted depends on the number of tuples in the relation that satisfy the WHERE-clause

31

Page 32: Chapter 4 Structured Query Language

DELETE DELETE FROM EMPLOYEE WHERE LNAME='Brown’;

32

Page 33: Chapter 4 Structured Query Language

TRUNCATE � The SQL TRUNCATE command is used to

delete all the rows from the table and free the space containing the table.

TRUNCATE TABLE table_name; TRUNCATE TABLE employee;

33

Page 34: Chapter 4 Structured Query Language

DELETE VS TRUNCATE �  TRUNCATE is a DDL whereas DELETE is a DML �  You can use WHERE clause(conditions) with

DELETE but you can't use WHERE clause with TRUNCATE .

�  You can't rollback data in TRUNCATE but in DELETE you can rollback data. TRUNCATE removes(delete) the record permanently.

�  TRUNCATE is faster than DELETE.

34

Page 35: Chapter 4 Structured Query Language
Page 36: Chapter 4 Structured Query Language

SELECT � Used to retrieve data in the table � Basic queries : SELECT-FROM-WHERE

structure.

SELECT attribute1, attribute2,... attribute-n FROM table_name; SELECT stud_id, f_name FROM student;

36

Page 37: Chapter 4 Structured Query Language

HOW TO SELECT ALL ATTRIBUTES IN THE TABLE?

� Using asterisk ( * ) to select all attributes in the table.

SELECT * FROM student ;

37

Page 38: Chapter 4 Structured Query Language

SELECT � Can be used with logical operator to

select data with certain condition.

38

= Equal > Greater than < Less than

>= Greater than or equal <= Less than or equal <> != Not equal to

Page 39: Chapter 4 Structured Query Language

SELECT

39

• People • First_Name • Last_Name • Gender • Age • Phone

• John • Smith • M • 27 • 2-4315

• Sally • Jones • F • 27 • 3-1542

• John • White • M • 32 • 2-4315

• Mary • Smith • F • 42 • 5-4321

• First_Name • Last_Name

John White Mary Smith

Result:

Let’s retrieve first name and last name for people who age is greater than 30.

Page 40: Chapter 4 Structured Query Language
Page 41: Chapter 4 Structured Query Language

SELECT

Retrieve the birthdate and address of the employee whose name is 'John B. Smith'.

41

SELECT BDATE, ADDRESS FROM EMPLOYEE WHERE FNAME='John' AND MINIT='B’ AND LNAME='Smith’;

Page 42: Chapter 4 Structured Query Language

Retrieve the name and address of all employees who work for the 'Research' department.

42

SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO;

Page 43: Chapter 4 Structured Query Language

SELECT � Similar to a SELECT-PROJECT-JOIN

sequence of relational algebra operations

� (DNAME='Research') is a selection condition (corresponds to a SELECT operation in relational algebra)

�  (DNUMBER=DNO) is a join condition (corresponds to a JOIN operation in relational algebra)

43

Page 44: Chapter 4 Structured Query Language

44

Page 45: Chapter 4 Structured Query Language

SELECT For every project located in 'Stafford', list the project number, the controlling department number, and the department manager's last name, address, and birthdate.

45

Attribute to select ? PNUMBER DNUM LNAME BDATE ADDRESS

Table? PROJECT DEPARTMENT EMPLOYEE

Join condition? PLOCATION= ‘Stafford’ DNUM = DNUMBER (JOIN PROJECT AND DEPARTMENT) MGRSSN = SSN (JOIN DEPARTMENT AND EMPLOYEE)

Page 46: Chapter 4 Structured Query Language

SELECT SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford‘;

46

Page 47: Chapter 4 Structured Query Language

SELECT � There are two join conditions � The join condition

DNUM=DNUMBER relates a project to its controlling department

� The join condition MGRSSN=SSN relates the controlling department to the employee who manages that department

47

Page 48: Chapter 4 Structured Query Language

Group discussion Create SQL command for each of the followings: � Q1 : Select project name located at

Houston � Q2 : Select employee first name, last

name for those who works more than 20 hours.

� Q3 : Select manager’s first name, last name, address, department’s name and dependent’s name for manager who has male dependent.

48

Page 49: Chapter 4 Structured Query Language

Answer q1

49

Page 50: Chapter 4 Structured Query Language

Answer q2

50

Page 51: Chapter 4 Structured Query Language

Answer q1

51

Page 52: Chapter 4 Structured Query Language

To be continued…

Page 53: Chapter 4 Structured Query Language

At the end of this class you should know. Create new table with CREATE command. � Remove tables with DROP command. � Delete data with the DELETE and

TRUNCATE commands. � Add data with the INSERT command. � Use data manipulation statements of SQL

on a given database: a. Retrieve data with the SELECT command b. Retrieve data from multiple tables with SQL JOINs (outer join, and inner joins) c. Use SQL CASE statements

Page 54: Chapter 4 Structured Query Language

IN

• People • First_Name • Last_Name • Gender • Age • Phone

• John • Smith • M • 27 • 2-4315

• John • White • M • 32 • 2-4315

• Mary • Smith • F • 42 • 5-4321

• Mama Mia • Steventh • F • 38 • 5-4321

SELECT First_Name,LastName,Age FROM People WHERE Age IN (27,32,42);

Result: • John • Smith • M • 27 • 2-4315

• John • White • M • 32 • 2-4315

• Mary • Smith • F • 42 • 5-4321

Page 55: Chapter 4 Structured Query Language

SUBSTRING COMPARISON � The LIKE comparison operator is used to

compare partial strings � Two reserved characters are used: '%' (or

'*' in some implementations).

55

Page 56: Chapter 4 Structured Query Language

LIKE

Employee First_Name Last_Name Gender Age Phone

John Smith M 27 2-4315

John White M 32 2-4315

Mary Smith F 42 5-4321

Mama Mia Steventh F 38 5-4321

John Smith M 27 2-4315

Mary Smith F 42 5-4321

Sury Steventh F 38 5-4321

SELECT * FROM Employee WHERE Last_Name LIKE ‘%th';

This SQL statement will match any first names that end with ‘th’

Result:

Page 57: Chapter 4 Structured Query Language

LIKE

Employee First_Name Last_Name Gender Age Phone

John Smith M 27 2-4315

John White M 32 2-4315

Mary Smith F 42 5-4321

Mama Mia Steventh F 38 5-4321

SELECT * FROM Employee WHERE First_Name LIKE ‘Ma%';

This SQL statement will match any first names that START with ‘Ma’

Mary Smith F 42 5-4321

Mama Mia Steventh F 38 5-4321

Result:

Page 58: Chapter 4 Structured Query Language

ORDER BY � The ORDER BY clause is used to sort the

tuples in a query result based on the values of some attribute(s).

� The default order is in ascending order of values

� We can specify the keyword DESC if we want a descending order; the keyword ASC can be used to explicitly specify ascending order, even though it is the default

58

Page 59: Chapter 4 Structured Query Language

ORDER BY

Employee First_Name Last_Name Gender Age Phone

John Smith M 27 2-4315

John White M 32 2-4315

Mary Smith F 42 5-4321

Mama Mia Steventh F 38 5-4321

SELECT First_Name,Last_Name,Age FROM Employee WHERE Gender=“M” ORDER BY Age;

By default : Sort in ascending order

Result: John Smith 27

John White 32

Page 60: Chapter 4 Structured Query Language

ORDER BY

Employee First_Name Last_Name Gender Age Phone

John Smith M 27 2-4315

John White M 32 2-4315

Mary Smith F 42 5-4321

Mama Mia Steventh F 38 5-4321

SELECT First_Name,LastName,Age FROM Employee WHERE Gender=“M” ORDER BY Age DESC;

Sort in descending order: add DESC

Result: John White 32

John Smith 27

Page 61: Chapter 4 Structured Query Language

DISTINCT � SQL does not treat a relation as a set, so

redundant data or tuples can appear. � To eliminate redundant tuples in a query

result, the keyword DISTINCT is used

SELECT DISTINCT SALARY FROM EMPLOYEE;

61

Page 62: Chapter 4 Structured Query Language

UNSPECIFIED WHERE CLAUSE � A missing WHERE-clause indicates no

condition; hence, all tuples of the relation in the FROM-clause are selected

� This is equivalent to the condition WHERE TRUE is in one relation.

�  If more than one relation is specified in the

FROM-clause and there is no join condition, then the CARTESIAN PRODUCT of tuples is selected

62

Page 63: Chapter 4 Structured Query Language

UNSPECIFIED WHERE CLAUSE SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT

63

Page 64: Chapter 4 Structured Query Language

OUTPUT

64

8 ROWS FROM EMPLOYEE X 3 ROWS FROM DEPARTMENT = 24 ROWS

Page 65: Chapter 4 Structured Query Language

UNSPECIFIED WHERE CLAUSE � The SQL before produced a large

relation which concatenate with every tuples from both relations

� It is extremely important not to overlook specifying any selection and join conditions in the WHERE-clause; otherwise, incorrect and very large relations may result

65

Page 66: Chapter 4 Structured Query Language

Aliases �  In SQL, we can use the same name for

two (or more) attributes as long as the attributes are in different relations.

� A query that refers to two or more attributes with the same name must qualify the attribute name with the relation name by prefixing the relation name to the attribute name

Example: � EMPLOYEE.LNAME, DEPARTMENT.DNAME

66

Page 67: Chapter 4 Structured Query Language

Aliases � Some queries need to refer to the same

relation twice. �  In this case, aliases are given to the

relation name � Example:

For each employee, retrieve the employee's name, and the name of his or her immediate supervisor.

67

Page 68: Chapter 4 Structured Query Language

SELECT E.FNAME, S.FNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN=S.SSN;

68

Page 69: Chapter 4 Structured Query Language

Aliases

69

Page 70: Chapter 4 Structured Query Language

Aliases � The alternate relation names E and S are

called aliases or tuple variables for the EMPLOYEE relation.

� We can think of E and S as two different copies of EMPLOYEE; �  E represents employees in role of

supervisees �  S represents employees in role of supervisors

70

Page 71: Chapter 4 Structured Query Language

SQL JOINS � Permit users to specify a table resulting

from a join operation in the from clause of a query.

�  It is easier to do than mixing together all the select and join conditions in where clause.

� The default join is inner join. � For example to join a table of the

EMPLOYEE and DEPARTMENT.

71

Page 72: Chapter 4 Structured Query Language

SQL JOINS � Without join SQL command will be: SELECT FNAME, DNAME FROM EMPLOYEE, DEPARTMENT WHERE DNO = DNUMBER;

� With JOIN the SQL command will be : SELECT FNAME, DNAME FROM ( EMPLOYEE JOIN DEPARTMENT ON DNO = DNUMBER );

72

Page 73: Chapter 4 Structured Query Language

73

Page 74: Chapter 4 Structured Query Language

SQL JOINS The example before : Retrieve the name and address of all employees who work for the 'Research' department.

74

SELECT FNAME, SSN, SALARY FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO; How it will be done using SQL join ?

Page 75: Chapter 4 Structured Query Language

SQL JOINS SELECT FNAME, SSN, SALARY FROM ( EMPLOYEE JOIN DEPARTMENT ON DNO = DNUMBER ) WHERE DNAME = ‘Research’;

75

Page 76: Chapter 4 Structured Query Language

SQL JOINS SELECT PNUMBER, PNAME, DNUM, FNAME, SSN, SALARY FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND PLOCATION='Stafford‘; How it will be done with SQL Join ?

76

Page 77: Chapter 4 Structured Query Language

SQL JOINS SELECT PNUMBER, PNAME, DNUM, FNAME, SSN, SALARY FROM ( PROJECT JOIN DEPARTMENT ON DNO = DNUMBER JOIN EMPLOYEE ON MNGR_SSN=SSN ) WHERE PLOCATION='Stafford‘;

77

Page 78: Chapter 4 Structured Query Language

OUTPUT

78

Page 79: Chapter 4 Structured Query Language

SQL JOINS �  In inner join, tuple is included in the result

only if a matching tuple exists in the other relations.

� For outer join, either the all the tables from the right or left (based on what you specify) will be included in the relations together with its matching value.

� When is to used outer join ?

79

Page 80: Chapter 4 Structured Query Language

SQL Joins � Retrieve only employee name and

supervisor name for those who has supervisor. �  Inner Join

SELECT E.FNAME AS Employee_Name, S.LNAME AS Supervisor_Name FROM (EMPLOYEE AS E JOIN EMPLOYEE AS S ON E.SUPERSSN=S.SSN)

80

Page 81: Chapter 4 Structured Query Language

INNER JOIN

81

Page 82: Chapter 4 Structured Query Language

SQL LEFT OUTER Joins �  Retrieve all the employee name and its

supervisor name. �  That’s mean all employee tuple must be

included. �  We have to use outer join

SELECT E.FNAME AS Employee_Name, S.LNAME AS Supervisor_Name FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S ON E.SUPERSSN=S.SSN)

82

Page 83: Chapter 4 Structured Query Language

LEFT OUTER JOIN

83

Page 84: Chapter 4 Structured Query Language

Aggregate function � There are 5 aggregate function in SQL.

�  COUNT (Return the number of tuples in rlation)

�  SUM (Return Summation of value ) �  MAX (Return Maximum value in a relation) �  MIN (Return Minimum value in a relation) �  AVG (Return Average )

84

Page 85: Chapter 4 Structured Query Language

COUNT

Product

PRO_ID NAME V_CODE

1 FAN 21

2 DESK 22

3 PENCIL 22

4 ERASER 21

Result:

SELECT COUNT(*) AS no_of_product;

no_of_product

4

Page 86: Chapter 4 Structured Query Language

SUM � SELECT SUM(PRICE) AS Total � FROM product;

Result:

Total

850

Product

PRO_ID NAME PRICE

1 FAN 200

2 DESK 220

3 PENCIL 220

4 ERASER 210

Page 87: Chapter 4 Structured Query Language

AVG � SELECT AVG(PRICE) AS total � FROM product;

Result:

total

212.5

Product

PRO_ID NAME PRICE

1 FAN 200

2 DESK 220

3 PENCIL 220

4 ERASER 210

Page 88: Chapter 4 Structured Query Language

MAX � SELECT MAX(PRICE) AS max_price � FROM product;

Result:

max_price

220

Product

PRO_ID NAME PRICE

1 FAN 200

2 DESK 220

3 PENCIL 220

4 ERASER 210

Page 89: Chapter 4 Structured Query Language

Aggregate function � Find the maximum salary, the minimum

salary, and the average salary among all employees.

� SELECT MAX(SALARY), MIN(SALARY), AVG(SALARY) FROM EMPLOYEE;

89

Page 90: Chapter 4 Structured Query Language

GROUP DISCUSSION QUESTION1 Find the maximum salary, the minimum salary, and the average salary among employees who work for the 'Research' department. QUESTION2 Retrieve the number of employees in the ‘Administration Department' department

90

Page 91: Chapter 4 Structured Query Language

ANSWER Q1

91

Page 92: Chapter 4 Structured Query Language

ANSWER Q2

92

Page 93: Chapter 4 Structured Query Language

GROUPING �  In many cases, we want to apply the

aggregate functions to subgroups of tuples in a relation

� Each subgroup of tuples consists of the set of tuples that have the same value for the grouping attribute(s)

� The function is applied to each subgroup independently

� SQL has a GROUP BY-clause for specifying the grouping attributes, which must also appear in the SELECT-clause

93

Page 94: Chapter 4 Structured Query Language

GROUPING For each department, retrieve the department number, the number of employees in the department, and their average salary. SELECT DNO, COUNT (*), AVG(SALARY) FROM EMPLOYEE GROUP BY DNO;

94

Page 95: Chapter 4 Structured Query Language

OUTPUT

95

Page 96: Chapter 4 Structured Query Language

GROUPING � The EMPLOYEE tuples are divided into

groups--each group having the same value for the grouping attribute DNO

� The COUNT and AVG functions are applied to each such group of tuples separately

� The SELECT-clause includes only the grouping attribute and the functions to be applied on each group of tuples �  A join condition can be used in conjunction with

grouping

96

Page 97: Chapter 4 Structured Query Language

GROUPING � For each project, retrieve the project

number, project name, and the number of employees who work on that project.

SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER;

�  In this case, the grouping and functions are

applied after the joining of the two relations

97

Page 98: Chapter 4 Structured Query Language

OUTPUT

98

Page 99: Chapter 4 Structured Query Language

THE HAVING-CLAUSE � Sometimes we want to retrieve the values

of these functions for only those groups that satisfy certain conditions.

� The HAVING-clause is used for specifying a selection condition on groups (rather than on individual tuples)

99

Page 100: Chapter 4 Structured Query Language

THE HAVING-CLAUSE � For each project on which more than two

employees work , retrieve the project number, project name, and the number of employees who work on that project. SELECT PNUMBER, PNAME, COUNT (*) FROM PROJECT, WORKS_ON WHERE PNUMBER=PNO GROUP BY PNUMBER HAVING COUNT (*) > 2;

100

Page 101: Chapter 4 Structured Query Language

OUTPUT

101

Page 102: Chapter 4 Structured Query Language

Summary of SQL Queries � A query in SQL can consist of up to six

clauses, but only the first two, SELECT and FROM, are mandatory. The clauses are specified in the following order: SELECT <attribute list> FROM <table list> [WHERE <condition>] [GROUP BY <grouping attribute(s)>] [HAVING <group condition>] [ORDER BY <attribute list>]

102

Page 103: Chapter 4 Structured Query Language

Summary of SQL Queries � The SELECT-clause lists the attributes or

functions to be retrieved � The FROM-clause specifies all relations (or

aliases) needed in the query but not those needed in nested queries

� The WHERE-clause specifies the conditions for selection and join of tuples from the relations specified in the FROM-clause

103

Page 104: Chapter 4 Structured Query Language

Summary of SQL Queries � GROUP BY specifies grouping attributes � HAVING specifies a condition for selection

of groups � ORDER BY specifies an order for displaying

the result of a query � A query is evaluated by first applying the

WHERE-clause, then GROUP BY and HAVING, and finally the SELECT-clause

104

Page 105: Chapter 4 Structured Query Language

SQL CASE � SQL CASE is a very unique conditional

statement providing if/then/else logic for any ordinary SQL command, such as SELECT or UPDATE.

�  It then provides when-then-else functionality (WHEN this condition is met THEN do_this).

� This functionality provides the developer the ability to manipulate the presentation of the data without actually updating or changing the data as it exists inside the SQL table.

105

Page 106: Chapter 4 Structured Query Language

SQL CASE � SYNTAX CASE WHEN ‘VALUE’ THEN ‘STATEMENT’ ELSE ‘STATEMENT’ END AS ‘NEW ATTRIBUTENAME’ FROM TABLENAME;

106

Page 107: Chapter 4 Structured Query Language

EXAMPLE

107