Module - 2
Module - 2
Module - 2
Catalog:
Named collection of schemas.
Data Definition, Constraints, and Schema Changes
• Used to CREATE, DROP, and ALTER the descriptions of the tables (relations) of a database
Creating a Database
• Syntax:
CREATE DATABASE database_name;
Creating a Table
• Syntax
CREATE TABLE table_name
(Column_name datatype[(size)],
Column_name datatype[(size)],
);
Slide 8- 3
CREATE TABLE
• Specifies a new base relation by giving it a name, and specifying each of its attributes and
their data types (INTEGER, FLOAT, DECIMAL(i,j), CHAR(n), VARCHAR(n))
• A constraint NOT NULL may be specified on an attribute
CREATE TABLE DEPARTMENT (
DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9) );
Slide 8- 4
CREATE TABLE
• In SQL, can use the CREATE TABLE command for specifying the primary key attributes,
secondary keys, and referential integrity constraints (foreign keys).
• Key attributes can be specified via the PRIMARY KEY and UNIQUE phrases
CREATE TABLE DEPT (
DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9),
MGRSTARTDATE CHAR(9),
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY (MGRSSN) REFERENCES EMP );
Slide 8- 5
Create tables for Company Database
COMPANY ER Schema Diagram
Chapter 3-7
DROP TABLE
• Used to remove a relation (base table) and its definition
• The relation can no longer be used in queries, updates, or any other
commands since its description no longer exists
• Example:
Slide 8- 8
ALTER TABLE
• The database users must still enter a value for the new attribute JOB for each EMPLOYEE
tuple.
• This can be done using the UPDATE command.
Slide 8- 9
Attribute Data Types and Domains in SQL
Following broad categories of data types exist in most databases:
• String Data
• Numeric Data
• Temporal Data
• Bit String
• Boolean
DDL - String Data
• Fixed Length:
• Occupies the same length of space in memory no matter
how much data is stored in them.
• Syntax:
char(n) where n is the length of the String
e.g. name char(50)
• If the variable stored for name is ‘Presidency’ the extra
40 fields are padded with blanks
11
DDL - Numeric Data Types
• Store all the data related to purely numeric data.
• Some numeric data may also be stored as a character
field e.g. zip codes
• Common Numeric Types:
• Decimal Floating point number
• Float Floating point number
• Integer(size) Integer of specified
length
• Money A number which contains
exactly two digits after the decimal point
• Number A standard number field that
can hold a floating point data
12
• These represent the dates and time:
DDL
• - Temporal
Three Data
basic types are Types
supported:
• Dates
• Times
• Date-Time Combinations
• MySQL comes with the following data types for storing a
date or a date/time value in the database:
• DATE - format YYYY-MM-DD
• DATETIME - format: YYYY-MM-DD HH:MI:SS
• TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
• YEAR - format YYYY or YY
13
Bit String:
• BIT(n)- Fixed Length(n)
• BIT varying(n) -Varying length string
Boolean:
• Takes value true or false.
• Because of the presence of NULL values Boolean also take the value
unknown.
Constraints in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
• FOREIGN KEY - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific
condition
• DEFAULT - Sets a default value for a column when no value is
specified
15
DDL - Specifying Keys- Introduction
• Unique keyword is used to specify keys.
• This ensures that duplicate rows are not created in the database.
• Both Primary keys and Candidate Keys can be specified in the database.
• Once a set of columns has been declared unique any data entered that
duplicates the data in these columns is rejected.
• Specifying a single column as unique:
16
Example:
CREATE TABLE Student
(snum Number,
sname varchar(20),
major varchar(10),
level char(2),
UNIQUE (sname));
17
DDL - Specifying Keys- Multiple Columns
• Specifying multiple columns as unique:
• Example:
CREATE TABLE Student
(snum Number,
sname varchar(20),
major varchar(10),
level varchar(10),
UNIQUE(snum, sname));
• Here both name and snum combination are declared as
candidate keys.
18
DDL - Specifying Keys- Primary Key
• Specifying multiple columns as unique:
• To specify the Primary Key the Primary Key clause is
used
• Example:
CREATE TABLE Student
( snum Number,
sname varchar(20),
major varchar(10),
level varchar(10),
DOB DATE,
PRIMARY KEY (snum),
UNIQUE (sname),
);
19
DDL - Specifying Keys- Single and MultiColumn Keys
• Single column keys can be defined at the column level
instead of at the table level at the end of the field
descriptions.
• MultiColumn keys still need to be defined separately at
the table level
CREATE TABLE Student
( snum int PRIMARY KEY,
Sname varchar(20) UNIQUE,
major varchar(10),
level varchar(10),
DOB date,
Unique(DOB,MAJOR));
20
DDL - Specifying Keys- Foreign Keys
• References clause is used to create a relationship
between a set of columns in one table and a candidate
key(primary key) in the table that is being referenced.
• Example:
21
The Mgr_ssn Example
22
Referential Integrity Options
• Causes of referential integrity violation for a foreign key FK (consider the
Mgr_ssn of DEPARTMENT).
• On Delete: when deleting the foreign tuple
• What to do when deleting the manager tuple in EMPLOYEE ?
• On Update: when updating the foreign tuple
• What to do when updating/changing the SSN of the manager tuple in
EMPLOYEE is changed ?
• Actions when the above two causes occur.
• Set Null: the Mgr_ssn is set to null.
• Set Default: the Mgr_ssn is set to the default value.
• Cascade: the Mgr_ssn is updated accordingly
• If the manager is deleted, the department is also deleted.
23
Referential Integrity Options
An Example:
Create table EMP(
…
ESSN CHAR(9),
DNO INTEGER DEFAULT 1,
SUPERSSN CHAR(9),
PRIMARY KEY (ESSN),
FOREIGN KEY (DNO) REFERENCES DEPT
ON DELETE SET DEFAULT
ON UPDATE CASCADE,
FOREIGN KEY (SUPERSSN) REFERENCES EMP ON
DELETE SET NULL ON UPDATE CASCADE);
24
DDL - Constraints- Disallowing Null
Values
Disallowing Null Values:
• Null values entered into a column means that the data in not known.
• These can cause problems in Querying the database.
• Specifying Primary Key automatically prevents null being entered in
columns which specify the primary key
• Not Null clause is used in preventing null values from being entered in a
column.
25
• Example:
CREATE TABLE Student
( snum number PRIMARY KEY,
sname varchar(20) NOT NULL,
major varchar(10) NOT NULL,
level varchar(10) NOT NULL
DOB date);
• Null clause can be used to explicitly allow null values in a
column also
26
DDL - Constraints- Value Constraints
Value Constraints:
• Allows value inserted in the column to be checked condition in the column
constraint.
• Check clause is used to create a constraint in SQL
• Example:
CREATE TABLE STUDENT
(snum Number PRIMARY KEY,
sname varchar(20),
Age Number check (Age > = 50));
• Table level constraints can also be defined using the Constraint keyword
27
Example:
28
DDL - Constraints- Default Value
Default Value:
• A default value can be inserted in any column by
using the Default keyword.
Example:
29
DDL -Constraints- AUTO INCREMENT
• Auto-increment allows a unique number to be generated
automatically when a new record is inserted into a table.
• Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.
• The following SQL statement defines the “SNUM" column to be an
auto-increment primary key field in the "Persons" table:
• CREATE TABLE STUDENT(
SNUM int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (SNUM));
30
continued..
• MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment
feature.
• By default, the starting value for AUTO_INCREMENT is 1, and it will
increment by 1 for each new record.
• To let the AUTO_INCREMENT sequence start with another value, use the
following SQL statement:
• ALTER TABLE STUDENT AUTO_INCREMENT=100;
• To insert a new record into the “STUDENT" table, we will NOT have to
specify a value for the “SNUM" column (a unique value will be added
automatically):
• INSERT INTO STUDENT (Sname,Major, Level,DOB)
VALUES ('Lakshman', ‘IS‘, ’JR’, ‘2001-05-01’);
31
Retrieval Queries in SQL
• SQL has one basic statement for retrieving information from a database; the
SELECT statement
• This is not the same as the SELECT operation of the relational algebra
• Important distinction between SQL and the formal relational model:
• SQL allows a table (relation) to have two or more tuples that are identical in all
their attribute values
• Hence, an SQL relation (table) is a multi-set (sometimes called a bag) of tuples;
it is not a set of tuples
• SQL relations can be constrained to be sets by specifying PRIMARY KEY or
UNIQUE attributes, or by using the DISTINCT option in a query
Slide 8- 33
Retrieval Queries in SQL (contd.)
• A bag or multi-set is like a set, but an element may appear more
than once.
• Example: {A, B, C, A} is a bag. {A, B, C} is also a bag that also is a set.
• Bags also resemble lists, but the order is irrelevant in a bag.
• Example:
• {A, B, A} = {B, A, A} as bags
• However, [A, B, A] is not equal to [B, A, A] as lists
Slide 8- 34
Retrieval Queries in SQL (contd.)
• Basic form of the SQL SELECT statement is called a mapping or a SELECT-
FROM-WHERE block
Slide 8- 35
Relational Database Schema
Slide 8- 36
Populated Database
Slide 8- 37
Simple SQL Queries
• Basic SQL queries correspond to using the following operations of
the relational algebra:
• SELECT
• PROJECT
• JOIN
• All subsequent examples use the COMPANY database
Slide 8- 38
Simple SQL Queries (contd.)
• Example of a simple query on one relation
• Query 0: Retrieve the birthdate and address of the employee whose name is 'John B.
Smith'.
Slide 8- 39
Simple SQL Queries (contd.)
• Query 1: Retrieve the name and address of all employees who work for the
'Research' department.
Slide 8- 40
Simple SQL Queries (contd.)
• Query 2: For every project located in 'Stafford', list the project number, the
controlling department number, and the department manager's last name,
address, and birthdate.
Q2: SELECT PNUMBER, DNUM, LNAME, BDATE, ADDRESS
FROM PROJECT, DEPARTMENT, EMPLOYEE
WHERE DNUM=DNUMBER AND MGRSSN=SSN
AND PLOCATION='Stafford‘;
Slide 8- 41
Aliases, * and DISTINCT, Empty WHERE-clause
• 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,
Slide 8- 42
ALIASES
• Some queries need to refer to the same relation twice
• In this case, aliases are given to the relation name
• Query 8: For each employee, retrieve the employee's name, and the name of
his or her immediate supervisor.
• In Q8, 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 and S represents employees in role of
supervisors
Slide 8- 43
ALIASES (contd.)
• Aliasing can also be used in any SQL query for convenience
• Can also use the AS keyword to specify aliases
Slide 8- 44
UNSPECIFIED WHERE-clause
• A missing WHERE-clause indicates no condition; hence, all tuples of the
relations in the FROM-clause are selected
• This is equivalent to the condition WHERE TRUE
• Query 9: Retrieve the SSN values for all employees.
• 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
Slide 8- 45
UNSPECIFIED WHERE-clause (contd.)
• Example:
Slide 8- 46
USE OF *
• To retrieve all the attribute values of the selected tuples, a * is used, which
stands for all the attributes
Examples:
Q1C: SELECT *
FROM EMPLOYEE
WHERE DNO=5;
Q1D: SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND
DNO=DNUMBER;
Slide 8- 47
USE OF DISTINCT
• SQL does not treat a relation as a set; duplicate tuples can appear
• To eliminate duplicate tuples in a query result, the keyword DISTINCT is used
• For example, the result of Q11 may have duplicate SALARY values whereas
Q11A does not have any duplicate values
Slide 8- 48
SET OPERATIONS
• SQL has directly incorporated some set operations
• There is a union operation (UNION), and in some versions of SQL there are set
difference (MINUS) and intersection (INTERSECT) operations
• The resulting relations of these set operations are sets of tuples; duplicate
tuples are eliminated from the result
• The set operations apply only to union compatible relations; the two relations
must have the same attributes and the attributes must appear in the same
order
Slide 8- 49
SET OPERATIONS (contd.)
• Query 4: Make a list of all project numbers for projects that involve an employee whose last
name is 'Smith' as a worker or as a manager of the department that controls the project.
Slide 8- 50
SUBSTRING PATTERN MATCHING AND ARITHMATIC
OPERATORS
In SQL, the LIKE comparison operator is used for string pattern matching.
• Partial strings are specified used two reserved characters:
- % replaces an arbitrary number of zero or more characters.
- Underscore(_) replaces a single character.
Q12: Retreive all employees whose address is in Houston, Texas.
SELECT Fname, Lname
FROM Employee
WHERE Address LIKE ‘%Houston,Tex%’;
Q12A: Find all the employees who were born during the 1950s.
SELECT Fname, Lname
FROM Employee
WHERE Bdate LIKE ‘_ _ 5_ _ _ _ _ _ _’;
Q13: Show the resulting salaries if every employee working on the ‘ProductX’
project is given a 10% rise.
SELECT E.Fname, E.Lname, 1.1*E.Salary AS Increased_Salary
FROM Employee AS E, Works_On AS W, Project AS P
WHERE E.SSN = W.ESSN and W.Pno = P.Pno and P.Pname = ‘ProductX’;
Q14: Retrieve all employees in dept. No 5 whose salary is between $30000 and
$40000.
SELECT * FROM Employee WHERE (Salary BETWEEN 30000 AND
40000) AND Dno = 5;
ORDER BY
• The ORDER BY clause is used to sort the tuples in a query result based on the
values of some attribute(s)
• Query 28: Retrieve a list of employees and the projects each works in, ordered
by the employee's department, and within each department ordered
alphabetically by employee last name.
Q28: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE,
WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME;
Slide 8- 53
ORDER BY (contd.)
• 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
Slide 8- 54
INSERT
• In its simplest form, it is used to add one or more tuples to a
relation
• Attribute values should be listed in the same order as the
attributes were specified in the CREATE TABLE command
Slide 8- 55
INSERT (contd.)
• Example:
U1: INSERT INTO EMPLOYEE
VALUES ('Richard','K','Marini', '653298653', '30-DEC-52',
'98 Oak Forest,Katy,TX', 'M', 37000,'987654321', 4 );
Slide 8- 56
INSERT (contd.)
• Important Note: Only the constraints specified in the DDL
commands are automatically enforced by the DBMS when updates
are applied to the database
• Another variation of INSERT allows insertion of multiple tuples resulting
from a query into a relation
Slide 8- 57
INSERT (contd.)
• Example: Suppose we want to create a temporary table that has the name, number of
employees, and total salaries for each department.
• A table DEPTS_INFO is created by U3A, and is loaded with the summary information
retrieved from the database by the query in U3B.
Slide 8- 58
INSERT (contd.)
• Note: The DEPTS_INFO table may not be up-to-date if we change
the tuples in either the DEPARTMENT or the EMPLOYEE relations
after issuing U3B. We have to create a view (see later) to keep
such a table up to date.
Slide 8- 59
DELETE
• Removes tuples from a relation
• Includes a WHERE-clause to select the tuples to be deleted
• Referential integrity should be enforced
• Tuples are deleted from only one table at a time (unless CASCADE is specified on
a referential integrity constraint)
• 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
Slide 8- 60
DELETE (contd.)
• Examples:
U4A: DELETE FROM EMPLOYEE
WHERE LNAME='Brown’;
Slide 8- 61
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
• Referential integrity should be enforced
Slide 8- 62
UPDATE (contd.)
• Example: Change the location and controlling department number
of project number 10 to 'Bellaire' and 5, respectively.
U5:UPDATE PROJECT
SET PLOCATION = 'Bellaire',
DNUM = 5
WHERE PNUMBER=10;
Slide 8- 63
UPDATE (contd.)
• Example: Give all employees in the 'Research' department a 10% raise in
salary.
U6: UPDATE EMPLOYEE
SET SALARY = SALARY *0.1
WHERE DNO IN (SELECT DNUMBER
FROM DEPARTMENT
WHERE DNAME='Research');
• In this request, the modified SALARY value depends on the original SALARY
value in each tuple
• The reference to the SALARY attribute on the right of = refers to the old SALARY
value before modification
• The reference to the SALARY attribute on the left of = refers to the new SALARY
value after modification
Slide 8- 64
MORE COMPLEX SQL RETRIEVAL
QUERIES
COMPARISON INVOLVING NULL AND 3 VALUED LOGIC
SQL has various rules for dealing with NULL values. The NULL is used to represent a missing
values but that is usually has one of the 3 different interpretations
Populated Database
Slide 8- 68
NESTING OF QUERIES
• A complete SELECT query, called a nested query, can be specified within the WHERE-clause of
another query, called the outer query
• Many of the previous queries can be specified in an alternative form using nesting
• Query 1: Retrieve the name and address of all employees who work for the 'Research'
department.
Slide 8- 69
NESTING OF QUERIES (contd.)
• The nested query selects the number of the 'Research' department
• The outer query select an EMPLOYEE tuple if its DNO value is in the result of
either nested query
• The comparison operator IN compares a value v with a set (or multi-set) of
values V, and evaluates to TRUE if v is one of the elements in V
• In general, we can have several levels of nested queries
• A reference to an unqualified attribute refers to the relation declared in the
innermost nested query
• In this example, the nested query is not correlated with the outer query
Slide 8- 70
CORRELATED NESTED QUERIES
• If a condition in the WHERE-clause of a nested query references an attribute of a relation
declared in the outer query, the two queries are said to be correlated
• The result of a correlated nested query is different for each tuple (or combination of
tuples) of the relation(s) the outer query
• Query 12: Retrieve the name of each employee who has a dependent with the same first name
as the employee.
Slide 8- 71
CORRELATED NESTED QUERIES (contd.)
• In Q12, the nested query has a different result in the outer query
• A query written with nested SELECT... FROM... WHERE... blocks and using the = or IN
comparison operators can always be expressed as a single block query. For example,
Q12 may be written as in Q12A
Q12A: SELECT E.FNAME, E.LNAME
FROM EMPLOYEE E, DEPENDENT D
WHERE E.SSN=D.ESSN AND
E.FNAME=D.DEPENDENT_NAME;
• Nested Subqueries Versus Correlated Subqueries :
• With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query. A correlated subquery, however,
executes once for each candidate row considered by the outer query. In other words,
the inner query is driven by the outer query.
Slide 8- 72
CORRELATED NESTED QUERIES (contd.)
• The original SQL as specified for SYSTEM R also had a CONTAINS comparison
operator, which is used in conjunction with nested correlated queries
• This operator was dropped from the language, possibly because of the
difficulty in implementing it efficiently
• Most implementations of SQL do not have this operator
• The CONTAINS operator compares two sets of values, and returns TRUE if
one set contains all values in the other set
• Reminiscent of the division operation of algebra
Slide 8- 73
• Retrieve the name of each emplo
74
CORRELATED NESTED QUERIES (contd.)
• Query 3: Retrieve the name of each employee who works on all the projects
controlled by department number 5.
Slide 8- 75
CORRELATED NESTED QUERIES (contd.)
• In Q3, the second nested query, which is not correlated with the outer query,
retrieves the project numbers of all projects controlled by department 5
• The first nested query, which is correlated, retrieves the project numbers on
which the employee works, which is different for each employee tuple because
of the correlation
Slide 8- 76
THE EXISTS FUNCTION
• EXISTS is used to check whether the result of a correlated nested query is
empty (contains no tuples) or not
• The result of EXISTS is a boolean value True or False. It can be used in a
SELECT, UPDATE, INSERT or DELETE statement.
• SELECT column_name(s) FROM table_name WHERE EXISTS
(SELECT column_name(s) FROM table_name WHERE condition);
• We can formulate Query 12 in an alternative form that uses EXISTS as
Q12B
Slide 8- 77
THE EXISTS FUNCTION (contd.)
• Query 12: Retrieve the name of each employee who has a
dependent with the same first name as the employee.
Slide 8- 78
THE EXISTS FUNCTION (contd.)
• Query 6: Retrieve the names of employees who have no dependents.
Slide 8- 79
EXPLICIT SETS
• It is also possible to use an explicit (enumerated) set of values
in the WHERE-clause rather than a nested query
• Query 13: Retrieve the social security numbers of all employees
who work on project number 1, 2, or 3.
Q13: SELECT DISTINCT ESSN
FROM WORKS_ON
WHERE PNO IN (1, 2, 3);
Slide 8- 81
Joined Relations Feature in SQL
Slide 8- 82
Joined Relations Feature in SQL (contd.)
• Examples:
Q8: SELECT E.FNAME, E.LNAME, S.FNAME, S.LNAME
FROM EMPLOYEE E S
WHERE E.SUPERSSN=S.SSN;
Slide 8- 83
Joined Relations Feature in SQL (contd.)
• Examples:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM EMPLOYEE, DEPARTMENT
WHERE DNAME='Research' AND DNUMBER=DNO;
• could be written as:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE JOIN DEPARTMENT
ON DNUMBER=DNO)
WHERE DNAME='Research’;
• or as:
Q1: SELECT FNAME, LNAME, ADDRESS
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
AS DEPT(DNAME, DNO, MSSN, MSDATE)
WHERE DNAME='Research’;
Slide 8- 84
Joined Relations Feature in SQL(contd.)
• Another Example: Q2 could be written as follows; this illustrates
multiple joins in the joined tables
Slide 8- 85
Illustration for LEFT OUTER JOIN
AGGREGATE FUNCTIONS
• Include COUNT, SUM, MAX, MIN, and AVG
• Query 15: Find the maximum salary, the minimum salary, and the average
salary among all employees.
Q15: SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY), SUM(SALARY)
FROM EMPLOYEE;
• Some SQL implementations may not allow more than one function in the
SELECT-clause
Slide 8- 87
AGGREGATE FUNCTIONS (contd.)
• Query 16: Find the maximum salary, the minimum salary, and the
average salary among employees who work for the 'Research'
department.
Q16: SELECT MAX(SALARY),
MIN(SALARY), AVG(SALARY)
FROM EMPLOYEE, DEPARTMENT
WHERE DNO=DNUMBER AND
DNAME='Research‘;
Slide 8- 88
AGGREGATE FUNCTIONS (contd.)
• Queries 17 and 18: Retrieve the total number of employees in the company
(Q17), and the number of employees in the 'Research' department (Q18).
Slide 8- 89
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
Slide 8- 90
GROUPING (contd.)
• Query 20: For each department, retrieve the department number, the number
of employees in the department, and their average salary.
Q20: SELECT DNO, COUNT (*), AVG (SALARY)
FROM EMPLOYEE
GROUP BY DNO;
Slide 8- 91
GROUPING (contd.)
• Query 21: For each project, retrieve the project number, project name, and the
number of employees who work on that project.
• In this case, the grouping and functions are applied after the joining of the two
relations
Slide 8- 92
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)
Slide 8- 93
THE HAVING-CLAUSE (contd.)
• Query 22: 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.
Slide 8- 94
COUNT(*) returns the number of rows in a
specified table, and it preserves duplicate
rows. It counts each row separately. This
includes rows that contain null values.
ORDER BY
• The ORDER BY clause is used to sort the tuples in a query result based on the
values of some attribute(s)
• Query 28: Retrieve a list of employees and the projects each works in, ordered
by the employee's department, and within each department ordered
alphabetically by employee last name.
Q28: SELECT DNAME, LNAME, FNAME, PNAME
FROM DEPARTMENT, EMPLOYEE,
WORKS_ON, PROJECT
WHERE DNUMBER=DNO AND SSN=ESSN
AND PNO=PNUMBER
ORDER BY DNAME, LNAME;
Slide 8- 98
ORDER BY (contd.)
• 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
Slide 8- 99
Constraints as Assertions
• General constraints: constraints that do not fit in the basic SQL categories
(presented in chapter 8)
• Mechanism: CREATE ASSERTION
• Components include:
• a constraint name,
• followed by CHECK,
• followed by a condition
Slide 9- 100
Assertions: An Example
• “The salary of an employee must not be greater than the salary of
the manager of the department that the employee works for’’
Slide 9- 101
SQL Triggers
• Objective: to monitor a database and take initiate action when a condition occurs
• A trigger is a stored procedure in database which automatically invokes whenever a special
event in the database occurs. For example, a trigger can be invoked when a row is inserted into
a specified table or when certain table columns are being updated.
• Triggers are expressed in a syntax similar to assertions and include the following:
• Event
• Such as an insert, deleted, or update operation
• BEFORE or AFTER the triggering operation is executed
• Condition: Determines whether the rule action should be executed.
Optional Condition: If Condition exists
If no condition exists
• Action
• To be taken when the condition is satisfied
Slide 9- 102
Syntax
create [or replace ] trigger [trigger_name] //Creates or replaces an existing trigger with the
trigger_name.
[before | after] //This specifies when the trigger will be executed.
{insert | update | delete} //This specifies the DML operation.
on [table_name] //This specifies the name of the table associated with the trigger.
[for each row] //This specifies a row-level trigger, i.e., the trigger will be executed for each row
being affected.
[trigger_body] //This provides the operation to be performed as trigger is fired
103
Example:
Given Student Report Database, in which student marks assessment is recorded. In such schema,
create a trigger so that the total and average of specified marks is automatically inserted
whenever a record is insert.
mysql> desc Student;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| tid | int(4) | NO | PRI | NULL | auto_increment |
| name | varchar(30) | YES | | NULL| |
| subj1 | int(2) | YES | | NULL | |
| subj2 | int(2) | YES | | NULL | |
| subj3 | int(2) | YES | | NULL | |
| total | int(3) | YES | | NULL | |
| avg | int(3) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
104
Example:
Create trigger stumarks
Before insert on student for each row set
student.total=student.sub1+student.sub2+student.sub3,
Student.avg=student.total/3;
mysql> insert into Student values(0, “Ram", 20, 20, 20, 0, 0);
Query OK, 1 row affected (0.09 sec)
105
mysql> select * from Student;
+-----+-------+-------+-------+-------+-------+------+
| tid | name | subj1 | subj2 | subj3 | total | avg |
+-----+-------+-------+-------+-------+-------+------+
| 100 | Ram | 20 | 20 | 20 | 60 | 20 |
+-----+-------+-------+-------+-------+-------+------+
1 row in set (0.00 sec)
106
Example
Given Library Book Management database schema
with Student database schema. In these databases, if
any student borrows a book from library then the
count of that specified book should be decremented.
mysql> select * from book_det;
mysql> select * from book_issue;
+-----+-------------+--------+
+------+------+--------+
| bid | btitle | copies |
| bid | sid | btitle |
+-----+-------------+--------+
+------+------+--------+
| 1 | Java | 10 |
1 row in set (0.00 sec)
| 2 | C++ | 5 |
| 3 | MySql | 10|
| 4 | DBMS | 5|
+-----+-------------+--------+
4 rows in set (0.00 sec)
107
OLD and NEW.
• There is two MySQL extension to triggers 'OLD' and 'NEW'.
• OLD and NEW are not case sensitive.
• Within the trigger body, the OLD and NEW keywords enable you to access
columns in the rows affected by a trigger
• In an INSERT trigger, only NEW.col_name can be used.
• In a UPDATE trigger, you can use OLD.col_name to refer to the columns of a
row before it is updated and NEW.col_name to refer to the columns of the row
after it is updated.
• In a DELETE trigger, only OLD.col_name can be used; there is no new row.
108
mysql> insert into book_issue values(1, 100, "Java");
book_deduction +-----+-------------+--------+
| 1 | Java | 9|
After insert on book_issue for each | 2 | C++ | 5|
row update book_det set | 3 | MySql | 10 |
copies=copies-1 where bid=new.bid; | 4 | DBMS | 5|
+-----+-------------+--------+
• mysql> select * from book_issue;
+------+------+--------+
| bid | sid | btitle |
+------+------+--------+
| 1 | 100 | Java |
+------+------+--------+
109
Populated Database
Slide 8- 110
SQL Triggers: An Example
• A trigger to compare an employee’s salary to his/her supervisor during insert or
update operations:
Slide 9- 111
Views in SQL
• A view is a “virtual” table that is derived from other tables
• Allows for limited update operations
• Since the table may not physically be stored
• Allows full query operations
• A convenience for expressing certain operations
Slide 9- 112
Specification of Views
The view has primarily two purposes:
• Simplify the complex SQL queries.
• Provide restriction to users from accessing sensitive data.
Slide 9- 113
Views in SQL
Deptname Empname Salary
Admin XYZ 20000
114
Example
Department Employee empbydept
D_id D_name Id Name Salary Gender D_id Id Name Salary Gender D_name
1 IT 1 Aman 6000 Male 3 1 Aman 6000 Male HR
2 Accounts 2 Bhavya 4999 Female 2 2 Bhavya 4999 Female Accounts
3 HR 3 Chang 7000 Male 1 3 Chang 7000 Male IT
4 Admin 4 Deep 5000 Male 4 4 Deep 5000 Male Admin
5 Ekta 3500 Female 3 5 Ekta 3500 Female HR
6 Francis 4500 Male 1 6 Francis 4500 Male IT
Create view empbydept as
Select emp.id,emp.name,emp.salary,emp.gender,dept.d_name from emp
join dept on emp.d_id=dept.d_id;
Select * from empbydept;
115
Create view Itemp as select id,name,salary,gender,d_name from emp
join dept in emp.d_id= dept.d_id where dept.d_name=‘IT’;
Select * from Itemp;
116
Types of View
117
Simple View
118
Complex View
119
SQL Views: An Example
• Specify a different WORKS_ON table
Slide 9- 120
Using a Virtual Table
• We can specify SQL queries on a newly create table (view):
SELECT FNAME, LNAME
FROM WORKS_ON_NEW
WHERE PNAME=‘Seena’;
Slide 9- 121
VIEWS Example
Efficient View Implementation
• Query modification:
• Present the view query in terms of a query on the underlying base tables
• Disadvantage:
• Inefficient for views defined via complex queries
• Especially if additional queries are to be applied to the view within a
short time period
Slide 9- 123
Materialized View
124
Efficient View Implementation
• View materialization:
• Involves physically creating and keeping a temporary table
• Assumption:
• Other queries on the view will follow
• Concerns:
• Maintaining correspondence between the base table and the view when
the base table is updated
• Strategy:
• Incremental update
Slide 9- 125
Update Views
• Update on a single view without aggregate operations:
• Update may map to an update on the underlying base table
• Views involving joins:
• An update may map to an update on the underlying base relations
• Not always possible
Slide 9- 126
Un-updatable Views
• Views defined using groups and aggregate functions are not updateable
• Views defined on multiple tables using joins are generally not updateable
• WITH CHECK OPTION: must be added to the definition of a view if the view
is to be updated
• To allow check for updatability and to plan for an execution strategy
Slide 9- 127
Database Stored Procedures
• Persistent procedures/functions (modules) are stored locally and executed
by the database server
• As opposed to execution by clients
• Advantages:
• If the procedure is needed by many applications, it can be invoked by any
of them (thus reduce duplications)
• Execution by the server reduces communication costs
• Enhance the modeling power of views
• Disadvantages:
• Every DBMS has its own syntax and this can make the system less
portable
Slide 9- 128
Stored Procedure Constructs
• A stored procedure
CREATE PROCEDURE procedure-name (params)
local-declarations
procedure-body;
• A stored function
CREATE FUNCTION fun-name (params) RETRUNS return-type
local-declarations
function-body;
• Calling a procedure or function
CALL procedure-name/fun-name (arguments);
Slide 9- 129
END OF MODULE 2
130