You are on page 1of 14

SQL: QUERIES, CONSTRAINTS, TRIGGERS

DEFINE SQL.

SQL stands for Structured Query Language. It uses a combination of relational algebra and relational calculus
construct. SQL is the most widely used commercial relational database language. It was originally developed at IBM
in the SEQUEL XRM and system-R projects (1974-1977).

The SQL language has several aspects to it.

b Data Definition language (DDL):

The DDL provides commands for defining relational schemas, deleting relations, modifying relational
schemas. The DDL also provides commands for specifying access rights or privileges to tables and views

b Data Manipulation Language (DML):

The DML includes the query language based on relational algebra and tuple relational calculus. It allows
users to pose queries to insert, delete and modify rows.

b Embedded and dynamic SQL:

The embedded form of SQL is designed for use within general-purpose programming language such as C or
COBOL. Dynamic SQL features allow a query to be executed at run time.

b Triggers:

The SQL support for triggers, which are actions executed by the DBMS whenever changes to the database
meet conditions specified in the trigger.

b Security:

SQL provides mechanisms to control user access to data objects such as tables and views.

b Transaction management:

SQL provides commands for specifying the transaction. Several implementations also allowed explicit
locking of data for concurrency control.

b Client-server execution and remote data access:

Various SQL commands are also used to connect client application program to an SQL database server, or
access data from a database over a network.

b Integrity:

The DDL includes commands for specifying integrity constraints that the data stored in the database must
satisfied.

b Authorization:

The SQL DDL includes commands for specifying access rights to relations and views.

EXPLAIN THE FORM OF SQL QUERY.

The form of a basic sql query:

A conceptual evaluation strategy is a way to evaluate the query that is intended to be easy to understand rather

1
than efficient.

Basic form:

Select [distinct] select-list


v Select à specifies columns to be retained in the result.
From from-list
v From à specifies a cross-product of tables.
Where qualification
v Whereà specifies selection conditions on the table mentioned in the from clause

The close relationship between sql and relational algebra is the basis for query optimization in a relational
DBMS.

Ex: Select Distinct name, age

From student

The answer is a set of rows, each of which is a pair <name, age>. If two or more students have the same
name and age, the answer still contains just one pair with that name and age.

If the keyword distinct is omitted, then we get a copy of the row <n, a> for each student with name n and age
a, the answer would be a multiset of rows. A multiset is similar to set in that it is an unordered collection of elements.

Ex:

· {a, b, b} and {b, a, b} denote the same multiset, and differ from the multiset {a, a, b}.

· 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.

é Select * à notation is useful for interactive querying, but it is poor style for queries that are intended to be
reused and maintained because the schema of the result is not clear form the query itself.

é The select clause is actually used to do projection, whereas selections in the relational algebra sense are
expressed using the where clause.

Syntax of a basic sql query:

v The from-list in the from clause is a list of table names. A table name can be followed by a range variable, it
is useful when the same table name appears more than once in the from-list

v The select-list is a list of column names of tables named in the from-list column names can be prefixed by a
range variable.

v The Qualification in the where clause is a Boolean combination of conditions of the form, expression op
expression Where, op is one of the comparison operators {<, <=, >, >=, <>, =}. An expression is a column
name, a constant, or an (arithmetic or string) expression.

v The Distinct keyword is optional. It indicates that the table does not contain duplicates. The default is that the

2
duplicates are not eliminated.

Conceptual evaluation strategy:

è Compute the cross-product of the tables in the from-list.

è Delete rows in the cross-product that fail the qualification conditions.

è Delete all columns that do not appear in the select-list.

è If Distinct is specified, eliminate duplicate rows.

Ex: Find the name of sailors who have reserved boat number 103

Select S.name

From sailors S, reserves R,

Where S.sid = R.sid and R.bid = 103

Examples of basic SQL queries:

1. Find the sids of sailors who have reserved a red boat.

Select R.sid

From boats B, Reserves R

Where B.bid = R.bid and B.color = ’red’

2. Find the names of sailors who have reserved a red boat.

Select S.name

From sailors S, reserves R, boats B

Where S.sid = R.sid and R.bid = B.bid and B.color=’red’

This query contains a join of three tables followed by a selection on the color of boats. This allows finding out
that according to reserves tuple R, has reserved a red boat described by tuple.

3. Find the colors of boats reserved by Axe.

Select B.color

From sailors S, reserves R, boats B

Where S.sid = R.sid and R.bid and S.name = ‘Axe’

4. Find the names of sailors who have reserved at least one boat.

Select S.name

From sailor S, Reserves R

Where S.sid = R.sid

3
Expressions and Strings in the SELECT command:

v SQL supports a more general version of the select-list than just a list of columns. Each item in a select-list
can be of the form expression as column-name, where expression is any arithmetic or string expression over
column name and constants, and column-name is a new name for this column in the output of the query. It
can also contain aggregates such as sum and count.

v The SQL standard also includes expressions over date and time values. Many implementations also support
the use of built-in functions such as sqrt, sin and mod.

v SQL supports a general concept of a collation, or sort order for a character set. A collation allows the user to
specify which characters are less than which others and provides great flexibility in string manipulation.

v SQL provides pattern matching through like operator along with the use of %.

Example:

“Perry%”àMatches any string beginning with “Perry”

“%idge%”àMatches any string containing “idge” as a substring

v Find the names of sailors whose name begins with N.

· Select * from student where sname like ‘N%’;

v Find the names of sailors whose name ends with a.

· Select * from student where sname like ‘%a’;

EXPLAIN SET MANIPULATIONS IN BRIEF.

UNION, INTERSECT AND EXCEPT:

The SQL provides three set-manipulation constructs. It supports these operations under the names union,
intersect and except. It also provides other set operations:

© In à To check if an element is in a given set.

© Op all / Op any à To compare a value with the elements in a given set, using comparison operator
op.

© Exists à To check if a set is empty.

Union:

The union operation combines two sets of rows into a single set composed of all the rows in either or both of
the two original sets, provided the two original seta are union compatible.

For union compatibility:

Ø The two sets must contain the same number of columns.

Ø Each column of the first set must be either the same data type as the corresponding column of the

4
second set.

It automatically eliminates duplicate values. If we want to retain all duplicates we must write union all in
place of union.

Ex: To find all customers having a loan, an account, or both at the bank,

è SELECT cname FROM depositor

UNION

SELECT cname FROM borrower

Result à This query returns only the original tuples.

è SELECT cname FROM depositor

UNION ALL

SELECT cname FROM borrower

Resultà It retains all duplicates values.

Intersect:

The result of the intersect operation is a relation that includes all tuples that are in two relations. It
automatically eliminates duplicate values. If we want to retain all duplicates we must write intersect all in place of
intersect.

Ex: To find all customers who have both a loan and an account

8 SELECT cname FROM depositor

INTERSECT ALL

SELECT cname FROM borrower

Resultà This query returns only the original tuples.

8 SELECT cname FROM depositor

INTERSECT ALL

SELECT cname FROM borrower

Result à It retains all duplicates values.

Except:

The result of the except operation is the relation that contains all tuples in one relation and not in another
relation. It automatically eliminates duplicate values. If we want to retain all duplicates we must write except all in
place of except.

Ex: To find all customers who have an account but no loan.

5
8 SELECT cname FROM depositor

EXCEPT

SELECT cname FROM borrower

Resultà This query returns only the original tuples.

8 SELECT cname FROM depositor

EXCEPT ALL

SELECT cname FROM borrower

Result à It retains all duplicates values.

WRITE SHORT NOTES ON NESTED QUERIES?

Introduction to Nested Queries:

Ø The nested query is a query that has another query embedded with in it; the embedded query is called sub
query.

Ø A sub query appears within the where clause of a query.

Ø A common use of the sub queries is to perform tests for set membership, set comparison and set cardinality.

Ex: Find the names of students who have got total above 400.

SELECT s.sname

FROM student s

WHERE s.rollno IN ( SELECT m.rollno

FROM mark m

WHERE total > 400 );

Find the names of students who have not got pass in the result.

SELECT s.sname

FROM student s

WHERE s.rollno NOT IN ( SELECT m.rollno

FROM mark m

WHERE result = “fail”);

WHAT IS MEANT BY CORRELATED NESTED QUERIES?

LIST OUT THE SET COMPARISON OPERATORS WITH EXAMPLES.

² Correlated nested queries:

6
The occurrence of relation in the sub query is called a correlation, and such queries are called correlated
queries.

² Set comparison operator:

The SQL supports the following comparison operators. These are:

1. Exists & Not exists

2. In & Not in

3. unique

SQL also supports op any and op all, where op is one of the arithmetic operators (=, <, >, >=, <=, <>….).
Some is also available, but it is just a synonym for Any.

² EXISTS:
This command is used to test whether the nonempty record is appearing there or not.

Ex: Find the name of students who have gained total 400.

SELECT s.name

FROM student s

WHERE EXISTS (SELECT * FROM mark r WHERE total = 400 AND r.rollno = s.rollno)

² IN:

This operator allows us to test whether a value is in a given set of elements. An SQL query is used to generate
the set to be tested.

Ex: Find the name of students whose total is equal to 400

SELECT name

FROM student

WHERE rollno IN ( SELECT rollno FROM mark m WHERE total = 400)

Find the name of students whose total is not equal to 400

SELECT name

FROM student

WHERE rollno NOT IN (SELECT rollno FROM mark WHERE total = 400)

This query allows to find all students whose total is not equal to 400.

² ANY:

SQL supports OP ANY, Where op is one of the arithmetic comparison operators {<, <=, =, <>, >=, >}.

Ex: Find the students name whose age is greater than some students named ‘Jeni’

7
SELECT s.name

FROM student s

WHERE s.age > ANY (SELECT s1.age FROM student s1 WHERE s1.name = ‘Jeni’)

If there are number of students named ‘Jeni’, this query finds all students name whose age is that of some
students named “Jeni”.

² ALL:

Ex: Find sailors name whose rating is better than all sailors called peter

SELECT S.rollno

FROM student S

WHERE S.age > ALL (SELECT S1.age

FROM student S1

WHERE S1.name = ‘sathya’)

If there are several students named sathya, this query finds all students rollno whose age is greater than that of
all students named “sathya”. IN and NOT IN operators are equivalent to = ANY and <> ALL respectively.

WHAT IS MEANT BY AGGREGATE OPERATORS


AND LIST OUT THEM?
Aggregate operators:

Aggregate operators are functions that take a collection of values as input and return a single value as a result.
The SQL supports five aggregate operations. They are:

1. COUNT ([DISTINCT]) A à The number of (unique) values in the A column.

2. SUM ([DISTINCT]) Aà The sum of all (unique) values in the A column

3. AVG ([DISTINCT]) Aà The average of all (unique) values in the A column.

4. MAX (A) à The maximum value in the column A.

5. MIN (A) à The minimum value in the A column.

The input to sum and avg must be a collection of numbers, but the other operators can operate on collections
of nonnumeric data types, such as strings.

Example:

z SELECT AVG(mark1) FROM student;

z SELECT MIN(mark1) FROM student;

z SELECT MAX(mark1) FROM student;

8
z SELECT SUM(mark1) FROM student;

z SELECT COUNT(*) FROM student;

WRITE SHORT NOTES ON GROUP BY AND HAVING CLAUSE?

The Group By and Having clause:

8 The aggregate operators also applied to group the set of tuples; we specify this is by group by clause.

8 Tuples with same value on all attributes in the group by clause are placed in one group.

8 Having clause contains predicates that applied after the formulation of groups.

General format:

Select (distinct) select-list from from-list

Where qualification Group by group-list

Having group-qualification

The expression appearing in the group-qualification in the HAVING clause must have a single value per
group.

Example:

1. Find the age of the youngest sailor who is eligible to vote for each rating level with atleast 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;

2. Find the number of reservations for each red boat.

SELECT b.bid, count(*) as reservationcount

FROM boats b, reserves r WHERE r.bid = b.bid and b.color =’red’

GROUP BY b.bid

3. Find the average age of sailors for each rating level that has atleast two sailors.

SELECT s.rating, Avg (s.age) AS average

FROM sailors s GROUP BY s.rating

9
HAVING COUNT(*) > 1;

4. Find those ratings for which the average age of sailors is the minimum over all ratings.

SELECT s.rating FROM sailors s

WHERE avg(s.age) = (select min(avg(s2.age)) from sailors s2

GROUP BY s2.rating)

WHAT IS THE USE OF NULL VALUES AND ALSO EXPLAIN ITS DISADVANTAGES?

Null values:

Ó SQL allows the use of null values to indicate absence of information about the value of an attribute.

Ó The keyword null is used to test for null values. SQL also provides a special comparison operator is null to test
whether a column value is null.

Ó Not null constraint is used to disallow the null values.

Ó The primary key constraints are not allowed to take on null values.

Comparisons using Null values:

è If we compare two null values using <, >, = and so on the result is always unknown.

è If we have null in two distinct rows of the sailor relation any comparison returns unknown.

è SQL provides a special comparison operator IS NULL to test whether a column value is null.

Logical connectives AND, OR, and NOT:

ÿ We use null values we must define the logical operators AND, OR and NOT using a three-valued logic in which
expressions evaluate to true, false or unknown.

ÿ The expression not unknown is defined to be unknown.

ÿ OR of two arguments evaluates to true if either argument evaluate to true, and to unknown if one argument
evaluate to false and other evaluate to unknown.

ÿ AND of the two arguments evaluates to false if either argument evaluates to false and to unknown if one
argument evaluate to unknown and other evaluate to true or unknown.

WRITE SHORT NOTES ON THE IMPACT ON SQL CONSTRUCTS.

Impact on SQL constructs:

z The presence of null values, any row that evaluates to false or unknown is eliminated. Eliminating rows that
evaluate to unknown has a subtle but significant impact on queries especially nested queries involving exists or
unique.

z Another issue in the presence of null values is the definition of when two rows in a relation instance or regarded
as duplicates.

10
z The SQL definition is that two rows are duplicates if corresponding columns are either equal or both contain null.

z The arithmetic operations + - * and / all return null if one of their argument is null. Count (*) handles null values
that are they get counted. All other aggregate operations simply discard null values.

z If one of these operators—other than Count is applied to only null values, the result is again null.

Ex: select register-no from student where mark1 is null;

DEFINE OUTER JOIN WITH ITS TYPES?

Outer join:

© The join operation is one of the most useful operations in relational algebra and used to combine information
from two or more relations.

© The outer join is an extension of the join operation to deal with missing information.

© It contains three types. They are:

1) Left outer join

2) Right outer join

3) Full outer join

² Left outer join:

It takes all tuples in the left relation that did not match with any tuples in right relation, pads the tuples with
the null values for all other attributes from the right relation, and adds them to the result of natural join.

Example: Employee relation Factory-Works Relation

Empname Branch-name Salary


Jones 4 roads 1900
Satya 5 roads 2300 Empname Street City
Gates ammapet 53000 Jones south Salem
Smith 4 roads 6000 Sathya Tunnel Attur
Smith north Salem

Results of natural join:

Empname Street City Branch-name Salary


Jones south Salem 4 roads 1900
Sathya Tunnel Attur 5 roads 2300
Smith north Salem Redmond 53000
Gates null null ammapet 53000

Result of left outer join:

11
Empname Street City Branch-name Salary
Jones south Salem 4 roads 1900
Sathya Tunnel Attur 5 roads 2300
Smith north Salem Redmond 53000

² Right outer joins:

It takes all tuples in the right relation that did not match with any tuples in left relation, pads the tuples with
the null values and adds to the result of natural join. All information from right relation is present in the result right
outer join.

Result:

Empname Street City Branch-name Salary


Jones south Salem 4 roads 1900
Sathya Tunnel Attur 5 roads 2300
Smith north Salem Redmond 53000

² Full outer-join:

It is a combination of the above join operations, padding tuples from left relation that did not match any from
the right relation, as well as tuples from right relation that did not match any from left relation, and padding them to
the result of the join.

Empname Street City Branch-name Salary


Jones south Salem 4 roads 1900
Sathya Tunnel Attur 5 roads 2300
Smith north Salem Redmond 53000
Gates Null Null ammapet 53000

WRITE SHORT NOTES ON TRIGGERS.

Triggers and active database.

è 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.

Ó Active Database à A database that has a set of associated triggers.

è Trigger description contains three parts:

Ó Event à A change to the database that activates the trigger

Ó Condition à A query or test is run when the trigger is activated

Ó Action à A procedure is executed when the trigger is activated and its condition is True.

è A trigger / daemon can monitor a database and is executed when the database is modified in a way that matches
the event specification.

è An insert, delete, or update statement could activate a trigger or application invoked the activating statement.

è A condition in a trigger can be a true or false statement or a query. A query is interpreted as true if the answer
set is nonempty and false if the query has no answers. If the condition part evaluates to true, the action
associated with the trigger is executed.

12
è An action can even execute a series of data-definition commands and transaction-oriented commands or call-
host language procedures.

Example of triggers in SQL:

CREATE TRIGGER init-count BEFORE INSERT ON students /* EVENT */

DECLARE

Count INTEGER;

BEGIN

Count := 0; /* ACTION */

END

CREATE TRIGGER init-count AFTER INSERT ON students /* EVENT */

WHEN (new.age < 18) /* condition; new is just-inserted tuple */

FOR EACH ROW

BEGIN /* Action; a procedure in oracle’s PL/SQL syntax */

Count := Count + 1;

END

v Where the keyword new refers to the newly inserted tuple. If an existing tuple were modified, the keyword Old
and New could be used to refer to the value before and after the modification.

v SQL:1999 also allows the action part of the trigger to refer to the set of changed records, rather than just one
changed record at a time.

CREATE TRIGGER SET-COUNT AFTER INSERT ON STUDENT /* EVENT*/

REFERENCING NEW TABLE AS insertedtuples

FOR EACH STATEMENT

INSERT /* ACTION */

INTO Statisticstable(Modifiedtable, Modificationtype, Count)

SELECT ‘students’, ‘insert’, COUNT *

FORM Insertedtuples I

WHERE I.age < 18

13
[Set-Oriented Triggers]

v The keyword clause NEW TABLE enables us to give a table name to the set of newly inserted tuples.

v The FOR EACH STATEMENT clause specifies a statement-level trigger and can be omitted because it is the
default.

v This definition does not have a WHEN clause; if such a clause is included it follows the FOR EACH
STATEMENT clause, just before the action specification.

v The trigger is evaluated once for each SQL statement that inserts tuples in to students and inserts a single tuple in
to a table that contains statistics on modification to database table.

v The first two fields of the tuple contain constants and the third field is the number of inserted students tuples with
age < 18.

14

You might also like