DBMS Module 4
DBMS Module 4
Module 4
SQL: SQL data definition and data types, Schema change statements in SQL, specifying
constraints in SQL, retrieval queries in SQL, INSERT, DELETE, and UPDATE
statements in SQL, Additional features of SQL.
Advances Queries: More complex SQL retrieval queries, Specifying constraints as
assertions and action triggers, Views in SQL, Schema change statements in SQL.
Basic SQL
• SQL uses the terms table, row, and column for the formal relational model terms
relation, tuple, and attribute, respectively.
• The main SQL command for data definition is the CREATE statement, which can be
used to create schemas, tables (relations), types, and domains, as well as other
constructs such as views, assertions, and triggers.
• Data Types
The basic data types available for attributes include numeric, character string, bit string,
Boolean, date, and time.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Numeric
• Numeric data types include integer numbers of various sizes (INTEGER or
INT, and SMALLINT) and floating-point (real) numbers of various precision
(FLOAT or REAL, and DOUBLE PRECISION).
• Formatted numbers can be declared by using DECIMAL(i, j)—or DEC(i, j) or
NUMERIC(i, j)—where i, the precision, is the total number of decimal digits
and j, the scale, is the number of digits after the decimal point.
• The default for scale is zero, and the default for precision is implementation-
defined.
Character-string
• Character-string data types are either fixed length—CHAR(n) or
CHARACTER(n), where n is the number of characters—or varying length—
VARCHAR(n) or CHAR VARYING(n) or CHARACTER
VARYING(n), where n is the maximum number of characters.
• When specifying a literal string value, it is placed between single quotation
marks and it is case sensitive (a distinction is made between uppercase and
lowercase).
• For fixed length strings, a shorter string is padded with blank characters to the
right.
• For example, if the value ‘Smith’ is for an attribute of type CHAR(10), it is
padded with five blank characters to become ‘Smith’ if needed.
• Padded blanks are generally ignored when strings are compared.
• For comparison purposes, strings are considered ordered in alphabetic (or
lexicographic) order; if a string str1 appears before another string str2 in
alphabetic order, then str1 is considered to be less than str2.
• There is also a concatenation operator denoted by || (double vertical bar) that
can concatenate two stringsin SQL. For example, ‘abc’ || ‘XYZ’ results in a
single string ‘abcXYZ’.
Bit-string
• Bit-string data types are either of fixed length n—BIT(n)—or varying
length— BIT VARYING(n), where n is the maximum number of bits. The
default for n, the length of a character string or bit string, is 1.
• Literal bit strings are placed between single quotes but preceded by a B to
distinguish them from character strings; for example, B‘10101’.
Boolean
• This data type has the traditional values of TRUE or FALSE.
• In SQL, because of the presence of NULL values, a three-valued logic is
used, so a third possible value for a Boolean data type is UNKNOWN.
Domains
• We can use SSN_TYPE in place of CHAR(9) for the attributes Ssn and
Super_ssn of EMPLOYEE, Mgr_ssn of DEPARTMENT, Essn of WORKS_ON,
and Essn of DEPENDENT.
• A domain can also have an optional default specification via a DEFAULT
clause.
In general, not all users are authorized to create schemas and schema elements.
The privilege to create schemas, tables, and other constructs must be explicitly
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL, Dnumber INT NOT
NULL, Mgr_ssn CHAR(9) NOT NULL, Mgr_start_date DATE,
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );
• Because SQL allows NULLs as attribute values, a constraint NOT NULL may be
specified if NULL is not permitted for a particular attribute.
• This is always implicitly specified for the attributes that are part of the primary key of
each relation, but it can be specified for any other attributes whose values are required
not to be NULL.
• It is also possible to define a default value for an attribute by appending the clause
DEFAULT <value> to an attribute definition.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
• The default value is included in any new tuple if an explicit value is not provided for
that attribute . If no default clause is specified, the default default value is NULL for
attributes that do not have the NOT NULL constraint.
• Another type of constraint can restrict attribute or domain values using the
CHECK clause following an attribute or domain definition.
• The PRIMARY KEY clause specifies one or more attributes that make up the
primary key of a relation.
• If a primary key has a single attribute, the clause can follow the attribute directly.
Dnumber INT PRIMARY KEY,
• The UNIQUE clause specifies alternate (unique) keys, also known as candidate keys.
• The UNIQUE clause can also be specified directly for a unique key if it is a single
attribute, as in the following example:
Dname VARCHAR(15) UNIQUE,
• Referential integrity is specified via the FOREIGN KEY clause.
• A referential integrity constraint can be violated when tuples are inserted or deleted,
or when a foreign key or primary key attribute value is updated.
• The default action that SQL takes for an integrity violation is to reject the update
operation that will cause a violation, which is known as the RESTRICT option.
• However, the schema designer can specify an alternative action to be taken by
attaching a referential triggered action clause to any foreign key constraint. The
options include SET NULL, CASCADE, and SET DEFAULT. An option must be
qualified with either ON DELETE or ON UPDATE.
• Another type of constraint can restrict attribute or domain values using the
CHECK clause following an attribute or domain definition.
• For example: suppose that department numbers are restricted to integer
numbers between 1 and 20; then, we can change the attribute declaration of
Dnumber in the DEPARTMENT table to the following:
Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);
• The CHECK clause can also be used in conjunction with the CREATE DOMAIN
statement.
• For example, we can write the following statement:
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
CREATE TABLE DEPARTMENT ( Dname VARCHAR(15) NOT NULL, Dnumber INT NOT
NULL, Mgr_ssn CHAR(9) NOT NULL, Mgr_start_date DATE,
CONSTRAINT DEPTPK PRIMARY KEY(Dnumber),
CONSTRAINT DEPTSK UNIQUE (Dname),
CONSTRAINT DEPTMGRFK FOREIGN KEY (Mgr_ssn) REFERENCES
EMPLOYEE(Ssn) ON DELETE SET DEFAULT ON UPDATE CASCADE);
Where
• <attribute list> is a list of attribute names whose values are to be retrieved by the
query.
• <table list> is a list of the relation names required to process the query.
• <condition> is a conditional (Boolean) expression that identifies the tuples to be
retrieved by the query.
• In SQL, the basic logical comparison operators for comparing attribute values with
one another and with literal constants are =, <, <=, >, >=, and <>. These correspond to
the relational algebra operators =, <, ≤, >, ≥, and ≠, respectively.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
• The SELECT clause of SQL specifies the attributes whose values are to be retrieved,
which are called the projection attributes in relational algebra and the WHERE
clause specifies the Boolean condition that must be true for any retrieved tuple, which
is known as the selection condition in relational algebra.
• We can think of an implicit tuple variable or iterator in the SQL query ranging or
looping over each individual tuple in the EMPLOYEE table and evaluating the
condition in the WHERE clause. Only those tuples that satisfy the condition—that is,
those tuples for which the condition evaluates to TRUE after substituting their
corresponding attribute values—are selected.
Examples:
i. Retrieve the birth date and address of the employee(s) whose name is ‘John
B. Smith’.
ii. Retrieve the name and address of all employees who work for the
‘Research’ department.
iii. For every project located in ‘Stafford’, list the project number, the controlling
department number, and the department manager’s last name, address, and birth date.
• In SQL, the same name can be used for two (or more) attributes as long as the
attributes are in different tables.
• If this is the case, and a multitable query refers to two or more attributes with the
same name, we must qualify the attribute name with the relation name to prevent
ambiguity. This is done by prefixing the relation name to the attribute name and
separating the two by a period.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Example:
SELECT Fname, EMPLOYEE.Name, Address
FROM EMPLOYEE, DEPARTMENT
WHERE DEPARTMENT.Name = ‘Research’ AND
DEPARTMENT.Dnumber = EMPLOYEE.Dnumber;
• Fully qualified attribute names can be used for clarity even if there is no
ambiguity in attribute names.
• We can also rename the table names to shorter names by creating an alias for each
table name to avoid repeated typing of long table names.
Example: For each employee, retrieve the employee’s first and last name and
thefirst and last name of his or her immediate supervisor.
• We can use this alias-naming or renaming mechanism in any SQL query to specify
tuple variables for every table in the WHERE clause, whether or not the same relation
needs to be referenced more than once.
• It is also possible to rename the relation attributes within the query in SQL by
giving them aliases.
• Example: if we write
EMPLOYEE AS E(Fn, Mi, Ln, Ssn, Bd, Addr, Sex, Sal, Sssn, Dno)
in the FROM clause, Fn becomes an alias for Fname, Mi for Minit, Ln for Lname, and
so on.
• A missing WHERE clause indicates no condition on tuple selection; hence, all tuples
of the relation specified in the FROM clause qualify and are selected for the query
result. If more than one relation is specified in the FROM clause and there is no
WHERE clause, then the CROSS PRODUCT—all possible tuple combinations—of
these relations is selected.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
SELECT *
FROM EMPLOYEE
WHERE Dno = 5;
SELECT *
FROM EMPLOYEE, DEPARTMENT
WHERE Dname = ‘Research’ AND Dno = Dnumber;
The query given below specifies the CROSS PRODUCT of the EMPLOYEE
and DEPARTMENT relations
SELECT *
FROM EMPLOYEE, DEPARTMENT;
.
Tables as Sets in SQL
SQL usually treats a table not as a set but rather as a multiset; duplicate tuples can
appear more than once in a table, and in the result of a query.
SQL does not automatically eliminate duplicate tuples in the results of
queries, for the following reasons:
Duplicate elimination is an expensive operation. One way to implement it is to
sort the tuples first and then eliminate duplicates.
The user may want to see duplicate tuples in the result of a query.
When an aggregate function is applied to tuples, in most cases we do not
want to eliminate duplicates.
An SQL table with a key is restricted to being a set, since the key value must be
distinct in each tuple.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
If we do want to eliminate duplicate tuples from the result of an SQL query, we use
the keyword DISTINCT in the SELECT clause, meaning that only distinct tuples
should remain in the result. In general, a query with SELECT DISTINCT
eliminates duplicates, whereas a query with SELECT ALL does not.
Specifying SELECT with neither ALL nor DISTINCT is equivalent to SELECT ALL.
SQL has directly incorporated some of the set operations from mathematical set
theory, which are also part of relational algebra.
There are set union (UNION), set difference (EXCEPT), and set intersection
(INTERSECT) operations.
The relations resulting from these set operations are sets of tuples; that is,
duplicate tuples are eliminated from the result.
These set operations apply only to type compatible relations, so we must make sure
that the two relations on which we apply the operation have the same attributes and
that the attributes appear in the same order in both relations.
Example: Make a list of all project numbers for projects that involve an
employee whose last name is ‘Smith’, either as a worker or as a manager of the
department that controls the project.
UNION
SQL also has corresponding multiset operations, which are followed by the keyword
ALL (UNION ALL, EXCEPT ALL, INTERSECT ALL). Their results are multisets
(duplicates are not eliminated).
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Example: Find all employees who were born during the 1950s.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Bdate LIKE ‘_ _ 7______ ’;
Arithmetic Operators
The standard arithmetic operators for addition (+), subtraction (−), multiplication (*),
and division (/) can be applied to numeric values or attributes with numeric domains.
Example: raise the salary of all employees who work on the ‘ProductX’ project
by 10%.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
For string data types, the concatenate operator || can be used in a query to append
two string values.
For date, time, timestamp, and interval data types, operators include incrementing
(+) or decrementing (−) a date, time, or timestamp by an interval.
In addition, an interval value is the result of the difference between two date, time, or
timestamp values. Another comparison operator, which can be used for convenience,
is BETWEEN.
Example: Retrieve all employees in department 5 whose salary is between
$30,000 and $40,000.
SELECT *
FROM EMPLOYEE
WHERE (Salary BETWEEN 30000 AND 40000) AND Dno = 5;
SQL allows the user to order the tuples in the result of a query by the values of one or
more of the attributes that appear in the query result, by using the ORDER BY clause.
Example: Retrieve a list of employees and the projects they are working on, ordered
by department and, within each department, ordered alphabetically by last name, then
first name.
Example:
SELECT D.Dname, E.Lname, E.Fname, P.Pname
FROM DEPARTMENT AS D, EMPLOYEE AS E, WORKS_ON AS W, PROJECT AS P
WHERE D.Dnumber = E.Dno AND E.Ssn = W.Essn AND W.Pno =P.Pnumber
ORDER BY D.Dname DESC, E.Lname ASC, E.Fname ASC;
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Example:
INSERT INTO EMPLOYEE VALUES ( ‘Richard’, ‘K’, ‘Marini’, ‘653298653’,
‘1962- 12-30’, ’98 Oak Forest, Katy, TX’, ‘M’, 37000, ‘653298653’, 4 );
A second form of the INSERT statement allows the user to specify explicit
attribute names that correspond to the values provided in the INSERT command.
This is useful if a relation has many attributes but only a few of those attributes are
assigned values in the new tuple.
However, the values must include all attributes with NOT NULL specification and
no default value.
Example: INSERT INTO EMPLOYEE (Fname, Lname, Dno, Ssn)
VALUES (‘Richard’, ‘Marini’, 4, ‘653298653’);
A DBMS that fully implements SQL should support and enforce all the integrity
constraints that can be specified in the DDL.
Example1:
INSERT INTO EMPLOYEE (Fname, Lname, Ssn, Dno)
VALUES (‘Robert’, ‘Hatcher’, ‘980760540’, 2);
The DBMS should reject the operation if no DEPARTMENT tuple exists in the
database with Dnumber = 2.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Another variation for loading data is to create a new table TNEW that has the same
attributes as an existing table T, and load some of the data currently in T into TNEW.
The syntax for doing this uses the LIKE clause.
Example: create a table D5EMPS with a similar structure to the EMPLOYEE table
and load it with the rows of employees who work in department 5,
The clause WITH DATA specifies that the table will be created and loaded with the
data specified in the query, although in some implementations it may be left out.
Example 2:
A missing WHERE clause specifies that all tuples in the relation are to be
deleted; however, the table remains in the database as an empty table.
Example 3: DELETE FROM EMPLOYEE;
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Note: We must use the DROP TABLE command to remove the table
definition.
The UPDATE command is used to modify attribute values of one or more selected
tuples.
As in the DELETE command, a WHERE clause in the UPDATE command selects the
tuples to be modified from a single relation.
However, updating a primary key value may propagate to the foreign key values of
tuples in other relations if such a referential triggered action is specified in the
referential integrity constraints of the DDL .
An additional SET clause in the UPDATE command specifies the attributes to be
modified and their new values.
Example 1: change the location and controlling department number of project
number 10 to ‘Bellaire’ and 5.
UPDATE PROJECT
SET Plocation = ‘Bellaire’, Dnum = 5
WHERE Pnumber = 10;\
UPDATE EMPLOYEE
SET Salary = Salary * 1.1
WHERE Dno = 5;
Note: each UPDATE command explicitly refers to a single relation only. To modify
multiple relations, we must issue several UPDATE commands.
The DROP command can be used to drop named schema elements, such as tables,
domains, types, or constraints.
One can also drop a whole schema if it is no longer needed by using the DROP
SCHEMA command.
There are two drop behavior options: CASCADE and RESTRICT.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
The definition of a base table or of other named schema elements can be changed by
using the ALTER command.
For base tables, the possible alter table actions include adding or dropping a column
(attribute), changing a column definition, and adding or dropping table constraints.
NOTE:
We must still enter a value for the new attribute Job for each individual EMPLOYEE tuple.
This can be done either by specifying a default clause or by using the UPDATE command
individually on each tuple .If no default clause is specified, the new attribute will have
NULLs in all the tuples of the relation immediately after the command is executed; hence, the
NOT NULL constraint is not allowed in this case.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
One can also change the constraints specified on a table by adding or dropping a named
constraint.
To be dropped, a constraint must have been given a name when it was specified.
ALTER TABLE:
1. Add a Column:
ALTER TABLE table_name ADD column_name datatype;
2. Drop a Column:
ALTER TABLE table_name DROP column_name;
3. Modify a Column (Change datatype or other attributes):
ALTER TABLE table_name MODIFY column_name new_datatype;
4. Rename a Column:
ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
5. Add or Drop Constraints (e.g., PRIMARY KEY, FOREIGN KEY, UNIQUE, DEFAULT):
ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint_definition;
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
6. Rename Table:
ALTER TABLE old_table_name RENAME TO new_table_name;
Delete:
Update:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
In general, each individual NULL value is considered to be different from every other
NULL value in the various database records.
When a record with NULL in one of its attributes is involved in a comparison operation, the
result is considered to beUNKNOWN (it may be TRUE or it may be FALSE).
Hence, SQL uses a three-valued logic with values TRUE, FALSE, and UNKNOWN
instead of the standard two-valued (Boolean) logic with values TRUE or FALSE.
It is therefore necessary to define the results (or truth values) of three-valued logical
expressions when the logical connectives AND, OR, and NOT are used.
Example: Retrieve the names of all employees who do not have supervisors.
SELECT Fname, Lname
FROM EMPLOYEE
WHERE Super_ssn IS NULL;
Some queries require that existing values in the database be fetched and then used in a
comparison condition. Such queries can be conveniently formulated by using nested
queries, which are complete select-from-where blocks within another SQL query. That
other query is called the outer query.
These nested queries can also appear in the WHERE clause or the FROM clause or the
SELECT clause or other SQL clauses as needed.
The comparison operator IN, which compares a value v with a set (or multiset) of values
V and evaluates to TRUE if v is one of the elements in V.
If a nested query returns a single attribute and a single tuple, the query result will be a
single (scalar) value.
In such cases, it is permissible to use = instead of IN for the comparison operator.
In general, the nested query will return a table (relation), which is a set or multiset of
tuples.
Example 1: selects the project numbers of projects that have an employee with last
name ‘Smith’ involved as manager or as a employee
SQL allows the use of tuples of values in comparisons by placing them within
parentheses.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Example 2: select the Essns of all employees who work the same (project, hours)
combination on some project that employee ‘John Smith’ (whose Ssn = ‘123456789’) works
on.
Example 4:Retrieve the name of each employee who has a dependent with the same first
name and is the same sex as the employee.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Whenever a condition in the WHERE clause of a nested query references some attribute of a relation
declared in the outer query, the two queries are said to be correlated.
Example 4: Retrieve the name of each employee who has a dependent with the
same first name and is the same sex as the employee.
Example 4: Retrieve the name of each employee who has a dependent with the
same first name and is the same sex as the employee.
Example 6: List the names of managers who have at least one dependent.
Example 7: Retrieve the name of each employee who works on all the projects
controlled by department number 5
RENAMING IN SQL
In SQL, it is possible to rename any attribute that appears in the result of a query by
adding the qualifier AS followed by the desired new name.
Hence, the AS construct can be used to alias both attribute and relation names in
general, and it can be used in appropriate parts of a query.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
The concept of a joined table (or joined relation) was incorporated into SQL to permit
users to specify a table resulting from a join operation in the FROM clause of a query.
This construct may be easier to comprehend than mixing together all the select and join
conditions in the WHERE clause.
Example1: retrieves the name and address of every employee who works for the
‘Research’ department
The concept of a joined table also allows the user to specify different types of join, such
as NATURAL JOIN and various types of OUTER JOIN.
In a NATURAL JOIN on two relations R and S, no join condition is specified; an implicit
EQUIJOIN condition for each pair of attributes with the same name from R and S is
created.
Each such pair of attributes is included only once in the resulting relation.
If the names of the join attributes are not the same in the base relations, it is possible to
rename the attributes so that they match, and then to apply NATURAL JOIN.
In this case, the AS construct can be used to rename a relation and all its attributes in the
FROM clause.
The default type of join in a joined table is called an inner join, where a tuple is included
in the result only if a matching tuple exists in the other relation.
SELECT E.Lname AS Employee_name, S.Lname AS Supervisor_name
FROM (EMPLOYEE AS E LEFT OUTER JOIN EMPLOYEE AS S
ON E.Super_ssn = S.Ssn);
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
It is also possible to nest join specifications; that is, one of the tables in a join may itself be
a joined table.
This allows the specification of the join of three or more tables as a single joined table,
which is called a multiway join.
Not all SQL implementations have implemented the new syntax of joined tables.
In some systems, a different syntax was used to specify outer joins by using the
comparison operators + =, = +, and + = + for left, right, and full outer join, respectively,
when specifying the join condition.
Aggregate functions are used to summarize information from multiple tuples into a
single-tuple summary.
Grouping is used to create subgroups of tuples before summarization. Grouping and
aggregation are required in many database applications, and we will introduce their use in
SQL through examples.
A number of built-in aggregate functions exist: COUNT, SUM, MAX, MIN, and AVG.
The COUNT function returns the number of tuples or values as specified in a query.
The functions SUM, MAX, MIN, and AVG can be applied to a set or multiset of numeric
values and return, respectively, the sum, maximum value, minimum value, and average
(mean) of those values.
These functions can be used in the SELECT clause or in a HAVING clause.
Example10: Find the sum of the salaries of all employees, the maximum salary, the
minimum salary, and the average salary.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
We could use AS to rename the column names in the resulting single-row table; for
example, as in example 10.
SELECT SUM (Salary) AS Total_Sal, MAX (Salary) AS Highest_Sal,
MIN (Salary) AS Lowest_Sal, AVG (Salary) AS Average_Sal
FROM EMPLOYEE;
Example11: Find the sum of the salaries of all employees of the ‘Research’ department,
as well as the maximum salary, the minimum salary, and the average salary in this
department.
Example14: retrieve the names of all employees who have two or more
dependents.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Note: If NULLs exist in the grouping attribute, then a separate group is created for all
tuples with a NULL value in the grouping attribute.
Example 16: For each project, retrieve the project number, the project name, and the
number of employees who work on that project.
Sometimes we want to retrieve the values of these functions only for groups that satisfy
certain conditions. SQL provides a HAVING clause, which can appear in conjunction
with a GROUP BY clause, for this purpose.
HAVING provides a condition on the summary information regarding the group of
tuples associated with each value of the grouping attributes. Only the groups that satisfy
the condition are retrieved in the result of the query.
Example 17: For each project on which more than two employees work, retrieve the
project number, the project name, and the number of employees who work on the project.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Example 18:For each project, retrieve the project number, the project name, and the
number of employees from department 5 who work on the project.
Example 19: For each department that has more than five employees, retrieve the
department number and the number of its employees who are making more than
$40,000.
The WITH clause allows a user to define a table that will only be used in a particular
query; it is somewhat similar to creating a view that will be used only in one query and
then dropped.
Example:
In the above example ,we defined in the WITH clause a temporary table BIG_DEPTS
whose result holds the Dno’s of departments with more than five employees, then used
this table in the subsequent query. Once this query is executed, the temporary table
BIGDEPTS is discarded.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
SQL also has a CASE construct, which can be used when a value can be different based on
certain conditions. This can be used in any part of an SQL query where a value is
expected, including when querying, inserting or updating tuples.
UPDATE EMPLOYEE
SET Salary =
CASE WHEN Dno = 5 THEN Salary +
2000 WHEN Dno = 4 THEN Salary
+ 1500 WHEN Dno = 1 THEN
Salary + 3000
ELSE Salary + 0;
The CASE construct can also be used when inserting tuples that can have different
attributes being NULL depending on the type of record being inserted into a table, as
when a specialization is mapped into a single table or when a union type is mapped into
relations.
SUMMARY:
SELECT <attribute and function list>
FROM <table list>
[ WHERE <condition> ]
[ GROUP BY <grouping attribute(s)> ]
[ HAVING <group condition> ]
[ ORDER BY <attribute list> ];
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
The basic technique for writing such assertions is to specify a query that selects any
tuples that violate the desired condition.
By including this query inside a NOT EXISTS clause, the assertion will specify that the
result of this query must be empty so that the condition will always be TRUE.
Thus, the assertion is violated if the result of the query is not empty.
In the preceding example, the query selects all employees whose salaries are greater than
the salary of the manager of their department. If the result of the query is not empty, the
assertion is violated.
A major difference between CREATE ASSERTION and the individual domain
constraints and tuple constraints is that = the CHECK clauses on individual attributes,
domains, and tuples are checked in SQL only when tuples are inserted or updated in a
specific table.
Hence, constraint checking can be implemented more efficiently by the DBMS in these
cases.
The schema designer should use CHECK on attributes, domains, and tuples only when he
or she is sure that the constraint can only be violated by insertion or updating of tuples.
On the other hand, the schema designer should use CREATE ASSERTION only in cases
where it is not possible to use CHECK on attributes, domains, or tuples, so that simple
checks are implemented more efficiently by the DBMS.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
Actions as Triggers
In many cases it is convenient to specify the type of action to be taken when certain
events occur and when certain conditions are satisfied.
The CREATE TRIGGER statement is used to implement such actions in SQL.
A typical trigger which is regarded as an ECA (Event, Condition, Action) rule has three
components:
a. The event(s):
These are usually database update operations that are explicitly applied to the
database.
In this example the events are: inserting a new employee record, changing an
employee’s salary, or changing an employee’s supervisor.
The person who writes the trigger must make sure that all possible events are
accounted for.
In some cases, it may be necessary to write more than one trigger to cover all
possible cases.
These events are specified after the keyword BEFORE in our example, which
means that the trigger should be executed before the triggering operation is
executed.
An alternative is to use the keyword AFTER, which specifies that the trigger
should be executed after the operation specified in the event is completed.
b. The condition that determines whether the rule action should be executed:
Once the triggering event has occurred, an optional condition may be evaluated.
If no condition is specified, the action will be executed once the event occurs. If a
condition is specified, it is first evaluated, and only if it evaluates to true will the
rule action be executed. The condition is specified in the WHEN clause of the
trigger.
c. The action to be taken:
The action is usually a sequence of SQL statements, but it could also be a
database transaction or an external program that will be automatically executed.
In this example, the action is to execute the stored procedure
INFORM_SUPERVISOR.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
A view in SQL terminology is a single table that is derived from other tables.
These other tables can be base tables or previously defined views.
A view does not necessarily exist in physical form; it is considered to be a virtual table,
in contrast to base tables, whose tuples are always physically stored in the database.
This limits the possible update operations that can be applied to views, but it does not
provide any limitations on querying a view.
In SQL, the command to specify a view is CREATE VIEW.
The view is given a (virtual) table name (or view name), a list of attribute names, and a
query to specify the contents of the view. If none of the view attributes results from
applying functions or arithmetic operations, we do not have to specify new attribute
names for the view, since they would be the same as the names of the attributes of the
defining tables in the default case.
If we do not need a view anymore, we can use the DROP VIEW command to dispose of
it.
a. Query modification:
It involves modifying or transforming the view query into a query on the
underlying base tables.
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
The disadvantage of this approach is that it is inefficient for views defined via
complex queries that are time-consuming to execute, especially if multiple view
queries are going to be applied to the same view within a short period of time.
b. view materialization:
It involves physically creating a temporary or permanent view table when the view
is first queried or created and keeping that table on the assumption that other
queries on the view will follow.
In this case, an efficient strategy for automatically updating the view table when
the base tables are updated must be developed in order to keep the view up-to-date.
Techniques using the concept of incremental update have been developed for
this purpose, where the DBMS can determine what new tuples must be inserted,
deleted, or modified in a materialized view table when a database update is
applied to one of the defining base tables.
The view is generally kept as a materialized (physically stored) table as long as it
is being queried.
If the view is not queried for a certain period of time, the system may then
automatically remove the physical table and recompute it from scratch when
future queries reference the view.
Different strategies as to when a materialized view is updated are possible.
Theimmediate update strategy updates a view as soon as the base tables are
changed; the lazy update strategy updates the view when needed by a view query;
and the periodic update strategy updates the view periodically.
Example: UPDATE WORKS_ON1
SET Pname = ‘ProductY’
WHERE Lname = ‘Smith’ AND Fname = ‘John’ AND Pname = ‘ProductX’;
This query can be mapped into several updates on the base relations to give the desired update
effect on the view. In addition, some of these updates will create additional side effects that
affect the result of other queries. For example, here are two possible updates, (a) and (b), on the
base relations corresponding to the view update operation.
a. UPDATE WORKS_ON
SET Pno = ( SELECT Pnumber
FROM PROJECT
WHERE Pname = ‘ProductY’ )
WHERE Essn IN ( SELECT Ssn
FROM EMPLOYEE
WHERE Lname = ‘Smith’ AND Fname = ‘John’ )
AND
Pno = ( SELECT Pnumber
FROM PROJECT
WHERE Pname = ‘ProductX’ );
DEPT OF AI&ML,BMSIT
BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT
Department of Artificial Intelligence and Machine Learning
b. UPDATE PROJECT
SET Pname = ‘ProductY’
WHERE Pname = ‘ProductX’;
observations:
a. A view with a single defining table is updatable if the view attributes contain the primary
key of the base relation, as well as all attributes with the NOT NULL constraint that do
not have default values specified.
b. Views defined on multiple tables using joins are generally not updatable.
c. Views defined using grouping and aggregate functions are not updatable.
DEPT OF AI&ML,BMSIT