Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-3 CH I

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

SQL: QUERIES,

CONSTRAINTS, TRIGGERS
DBMS U3 CH I
• FORM OF BASIC SQL QUERY
• A conceptual evaluation strategy is a way to evaluate the
query that is intended to be easy to understand, rather than
efficient.
• A DBMS would typically execute a query in a different
and more efficient way.
• The basic form of an SQL query is as follows:
SELECT [ DISTINCT ] select-list
FROM from-list
WHERE qualification
• Such a query intuitively corresponds to a relational algebra
expression involving selections, projections, and cross-
products.
• Every query must have a SELECT clause, which species
columns to be retained in the result, and a FROM clause,
which species a cross-product of tables.
• The optional WHERE clause species selection conditions on
the tables mentioned in the FROM clause. Let us consider a
simple query.
Sailors(sid: integer, snarne: string, rating: integer, age: real)
Boats( bid: integer, bnarne: string, coloT: string)
Reserves (sid: integer, bid: integer, day: date)
Find the names and ages of all sailors.
SELECT DISTINCT S.sname, S.age
FROM Sailors S
Find all sailors with a rating above 7.
SELECT S.sid, S.sname, S.rating, S.age
FROM Sailors AS S
WHERE S.rating > 7

• This query uses the optional keyword AS to introduce a range


variable.
The syntax of a basic SQL query in more detail.
• The from-list in the FROM clause is a list of table names. A table name can
be followed by a range variable; a range variable is particularly useful when
the same table name appears more than once in the from-list.
• The select-list is a list of (expressions involving) column names of tables
named in the from-list. Column names can be prefixed by a range variable.
• The qualification in the WHERE clause is a Boolean combination (i.e., an
expression using the logical connectives AND, OR, and NOT) of conditions
of the form expression op expression, where op is one of the comparison
operators {<,<=,=,<>,>=,>}.2 An expression is a column name, a constant,
or an (arithmetic or string) expression.
• The DISTINCT keyword is optional. It indicates that the table computed as
an answer to this query should not contain duplicates, that is, two copies of
the same row. The default is that duplicates are not eliminated.
The following is conceptual evaluation strategy followed:

1. Compute the cross-product of the tables in the from-


list.
2. Delete those rows in the cross-product that fail the
qualification conditions.
3. Delete all columns that do not appear in the select-list.
4. If DISTINCT is specified, eliminate duplicate rows.
We illustrate the conceptual evaluation strategy using the following
query:
Find the names of sailors who have reserved boat number 103.
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid=103

An equivalent way to write this query is:


SELECT Sname
FROM Sailors, Reserves
WHERE Sailors.sid = Reserves.sid AND Reserves.bid=103
Examples of Basic SQL Queries
Find the names of sailors who have reserved a red boat.
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = `red‘

Find the colors of boats reserved by Lubber.


SELECT B.color
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND S.sname = `Lubber'
UNION, INTERSECT, AND EXCEPT
• SQL provides three set-manipulation constructs that extend the basic
query form.
• Since the answer to a query is a multiset of rows, it is natural to
consider the use of operations such as union, intersection, and
difference.
• SQL supports these operations under the names UNION, INTERSECT,
and EXCEPT.
(Q5) Find the names of sailors who have reserved a red or a green boat.
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid
AND (B.color = 'red' OR B.color = 'green')
NESTED QUERIES
• A nested query is a query that has another query embedded
within it; the embedded query is called a subquery.
• When writing a query, we sometimes need to express a condition
that refers to a table that must itself be computed.
• The query used to compute this subsidiary table is a subquery and
appears as part of the main query.
• A subquery typically appears within the WHERE clause of a
query.
• Subqueries can sometimes appear in the FROM clause or the
HAVING clause.
SQL set Operations
• IN : to check if an element is in a given set
E.g.
SELECT Fname, Lname
FROM Employee
WHERE Salary IN (30000, 40000, 25000);
• IN can be prefixed by NOT, to check if an element is not in a given set
Correlated Nested Queries

Correlated Nested Queries


• In the nested queries that we have seen thus far, the inner subquery
has been completely independent of the outer query.
• In general the inner subquery could depend on the row that is
currently being examined in the outer query
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.

• EXISTS can be prefixed by NOT, with the obvious modification to their


meaning.
Find the names of sailors who have reserved boat number 103.
SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103
AND R.sid = S.sid )
• The subquery clearly depends on the current row S and must be re-
evaluated for each row in Sailors.
• The occurrence of S in the subquery (in the form of the literal S.sid) is
called a correlation, and such queries are called correlated queries.
Set-Comparison Operators

• SQL supports op ANY and op ALL, where op is one of the


arithmetic comparison operators {<, <=, =, <>, >=, >}.
• SOME is also available, which is just a synonym for ANY.
• The ANY and ALL operators are used with a WHERE or
HAVING clause.
• The ANY operator returns true if any of the subquery values
meet the condition.
• The ALL operator returns true if all of the subquery values
meet the condition.
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

ALL Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
• Product(ProductID,ProductName,SupplierID,CategoryID,Unit,Price)
• Orderdetails(OrderDetailID,OrderID, ProductID,Quantity)

• Example
SELECT ProductName FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE
Quantity = 10);

• Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE
Quantity = 10);
(Q22) Find sailors whose rating is better than some sailor called Horatio.

SELECT S.sid FROM Sailors S


WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2 WHERE S2.sname = 'Horatio’ )

(Q23) Find sailors whose rating is better than every sailor' called Horatio.
Find the sailors with the highest rating.
SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating
FROM Sailors S2 )
More Examples of Nested Queries
• This formulation of the query illustrates how queries involving
INTERSECT can be rewritten using IN, which is useful to know if
your system does not support INTERSECT.
• Queries using EXCEPT can be similarly rewritten by using NOT
IN.
• To Find the sids of sailors who have reserved red boats but not
green boats, we can simply replace the keyword IN in the previous
query by NOT IN.
AGGREGATE OPERATORS
• SQL supports five aggregate operations, which can be applied on
any column, say A, of a relation:
Count the number of sailors.
SELECT COUNT (*)
FROM Sailors S

Count the number of different sailor names.


SELECT COUNT ( DISTINCT S.sname )
FROM Sailors S
(Q,"21) Find the name and age of the oldest sailor.

SELECT S.sname, S.age


FROM Sailors S
WHERE S.age = ( SELECT MAX (S2.age)
FROM Sailors S2 )
The GROUP BY and HAVING clauses
Group By
• The GROUP BY clause is a SQL command that is used to group rows that have
the same values.
• The GROUP BY clause is used in the SELECT statement . It is used in conjunction
with aggregate functions to produce summary reports from the database.
• It is used in summarizing data from the database.
• The queries that contain the GROUP BY clause are called grouped queries and only
return a single row for every grouped item.
Syntax:
SELECT statements... GROUP BY column_name1[,column_name2,...]
[HAVING condition];

Examples:
• select sec from student group by sec;
• select sec,count(sec) from student group by sec;
• select branch,sec from student group by branch,sec;
Having
• The HAVING clause is used in the SELECT statement to specify filter conditions for
a group of rows or aggregates.
• The HAVING clause is used with the GROUP BY clause to filter groups based on a
specified condition. If the GROUP BY clause is omitted, the HAVING clause behaves
like the WHERE clause.
• HAVING clause applies a filter condition to each group of rows, while the WHERE
clause applies the filter condition to each individual row.
Syntax:
SELECT expression1, expression2, ... expression_n, aggregate_function
(expression)
FROM tables [WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;
Example:
select branch,sec,count(sec) from student group by branch,sec having
count(sec)>1;
• (Q31) Find the age of the youngest sailor for each rating level.
SELECT S.rating, MIN (S.age)
FROM Sailors S
GROUP BY S.rating

(QS2) Find the age of the youngest sailor who is eligible to vote for each rating level with
at least two such sailors.
SELECT S.rating, MIN (S.age) AS minage
FROM Sailors S
WHERE S.age >= 18
GROUP BY S.rating
HAVING COUNT (*) > 1
NULL VALUES
• we use null when the column value is either ‘Unknown or inapplicable’.

The impact of null values on SQL


Comparisons Using Null Values
• SQL provides a special comparison operator IS NULL to test whether a
column value is null;

Logical Connectives AND, OR, and NOT


• The expression NOT unknown is defined to be unknown.
• OR of two arguments evaluates to true if either argument evaluates to true, and to unknown if one
argument evaluates to false and the other evaluates to unknown. If both arguments are false, of
course, OR evaluates to false.
• AND of two arguments evaluates to false if either argument evaluates to false, and to unknown if one
argument evaluates to unknown and the other evaluates to true or unknown. (If both arguments are
true, AND evaluates to true.)
Outer Joins
SELECT S.sid, R.bid
FROM Sailors S NATURAL LEFT OUTER JOIN Reserves R
• The NATURAL keyword specifies that the join condition is equality on all
common attributes (in this example, sid), and the WHERE clause is not
required (unless we want to specify additional, non-join conditions).

Disallowing Null Values


• We can disallow null values by specifying NOT NULL as part of the field
definition;
• for example, sname CHAR(20) NOT NULL.
• In addition, the fields in a primary key are not allowed to take on null values.
• Thus, there is an implicit NOT NULL constraint for every field listed in a
PRIMARY KEY constraint.
COMPLEX INTEGRITY CONSTRAINTS IN SQL

Constraints over a Single Table

We can specify complex constraints over a single table using table constraints,
It has the form CHECK conditional-expression.
Sailors(sid: integer, sname: string, rating: integer, age: real)
Boats( bid: integer, bnarne: string, color: string)
Reserves (sid: integer, bid: integer, day: date)
we can name a constraint by preceding it with CONSTRAINT constraint-name. If the constraint is violated, the constraint
name is returned and can be used to identify the error.
Domain Constraints

 rating ratingval
Assertions: ICs over Several Tables
• Table constraints are associated with a single table, although the
conditional expression in the CHECK clause can refer to other
tables.
• Table constraints are required to hold only if the associated
table is nonempty.
• Thus, when a constraint involves two or more tables, the table
constraint mechanism is sometimes cumbersome and not quite
what is desired.
• To cover such situations, SQL supports the creation of
assertions, which are constraints not associated with any one
table.
TRIGGERS AND ACTIVE DATABASES

• A trigger is a procedure that is automatically invoked by the


DBMS in response to specified changes to the database, and is
typically specified by the DBA.
• A database that has a set of associated triggers is called an
active database.
• A trigger description contains three parts:
Event: A change to the database that activates the trigger.
Condition: A query or test that is run when the trigger is
activated.
Action: A procedure that is executed when the trigger is
activated and its condition is true.
Syntax:
Syntax for Creating a Trigger
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
• Before|After : This tells us when the trigger will be executed. It tells us
the time at which the trigger will be initiated i.e., either before on-
going event or after on-going event.
• Before triggers are used to update / validate values before they are
saved by the database.
• After triggers are used to access fields values that are sent by the
system and to effect changes in other records. The records that
activate the ‘after’ trigger are read-only. We cannot use after trigger if
we want to “update” a record because it will lead to “read-only”
error.
Examples on Triggers
Trigger’s Example
A delimiter is a blank space, comma, or other
• Create table character or symbol that indicates the beginning
• mysql> delimiter **; or end of a character string, word, or data item.

• mysql> desc student;


-> **;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid | int(4) | NO | PRI | NULL | |
| name | varchar(10) | YES | | NULL | |
| sub1 | int(3) | YES | | NULL | |
| sub2 | int(3) | YES | | NULL | |
| sub3 | int(3) | YES | | NULL | |
| total | int(3) | YES | | NULL | |
• mysql> create trigger stdmk before insert on student for each row set
new.total=new.sub1+new.sub2+new.sub3;
• -> **;
• Query OK, 0 rows affected (0.09 sec)

• mysql> insert into student values(2,'bbb',56,78,94,0);


• -> **;
• Query OK, 1 row affected (0.02 sec)

• mysql> select * from student;


• -> **;
• +-----+------+------+------+------+-------+
• | sid | name | sub1 | sub2 | sub3 | total |
• +-----+------+------+------+------+-------+
• | 2 | bbb | 56 | 78 | 94 | 228 |
• +-----+------+------+------+------+-------+
• 1 rows in set (0.00 sec)
Example
 First, create a new table named employees_audit to keep
the changes of the employee table. The following
statement creates the employee_audit table.
CREATE TABLE employees_audit (
id INT AUTO_INCREMENT PRIMARY KEY,
employeeNumber INT NOT NULL,
lastname VARCHAR(50) NOT NULL,
changedat DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL
);
 Next, create a BEFORE UPDATE trigger that is invoked before a change is
made to the employees table.
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees
FOR EACH ROW
INSERT INTO employees_audit
SET action = 'update',
employeeNumber = OLD.employeeNumber,
lastname = OLD.lastname,
changedat = NOW();
 After that, update the employees table to check
whether the trigger is invoked.
UPDATE employees
SET
lastName = 'Phan'
WHERE
employeeNumber = 1056;
 Inside the body of the trigger, we used the OLD keyword to access
employeeNumber and lastname column of the row affected by the
trigger.
 Notice that in a trigger defined for INSERT, you can use NEW
keyword only. You cannot use the OLD keyword.
 However, in the trigger defined for DELETE, there is no new row so
you can use the OLD keyword only.
 In the UPDATE trigger, OLD refers to the row before it is updated and
NEW refers to the row after it is updated.
 Finally, to check if the trigger was invoked by the UPDATE
statement, you can query the employees_audit table using
the following query:
 SELECT * FROM employees_audit;

As you see, the trigger was really invoked, and it inserted a


new row into the employees_audit table.
 Then, to view all triggers in the current
database, you use SHOW TRIGGERS
statement as follows:
 SHOW TRIGGERS;

You might also like