Unit III SQL
Unit III SQL
Form of Basic SQL Query, Union, intersect and Except, Nested Queries, Aggregative Operators, NULL values,
Complex Integrity Constraints in SQL, Triggers and Active Data bases.
……………………………………………………………………………………………………………………………..
Structured Query Language (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).
Clauses are used to construct an SQL statement so that when executed the statement will perform a
particular function.
The table below lists and describes the most commonly used SQL clauses. An SQL clause within bracket [ ]
indicates the clause is optional.
SQL Datatype is used to define the values that a column can contain.
Every column is required to have a name and data type in the database table.
There are Three types of binary Datatypes which are given below:
1 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
image It has a maximum length of 2,147,483,647 bytes. It contains variable-length binary data.
float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.
Data
Description
type
char It has a maximum length of 8000 characters. It contains Fixed-length non-unicode characters.
varchar It has a maximum length of 8000 characters. It contains variable-length non-unicode characters.
Datatype Description
timestamp It stores the year, month, day, hour, minute, and the second value.
2 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Q) SQL commands
SQL commands are instructions. It is used to communicate with the database. It is also used to
perform specific tasks, functions, and queries of data.
SQL can perform various tasks like create a table, add data to tables, drop the table, modify the
table, set permission for users.
DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc.
All the command of DDL are auto-committed that means it permanently save all the changes in the
database.
CREATE
ALTER
DROP
TRUNCATE
3 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
b. DROP: It is used to delete both the structure and record stored in the table.
c. ALTER: It is used to alter the structure of the database. This change could be either to modify the
characteristics of an existing attribute or probably to add a new attribute.
d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.
DML commands are used to modify the database. It is responsible for all form of changes in the
database.
The command of DML is not auto-committed that means it can't permanently save all the changes in
the database. They can be rollback.
INSERT
UPDATE
DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES (value1, value2, value3, .... valueN);
(OR)
b. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
4 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
c. DELETE: It is used to remove one or more row from a table.
Syntax:
WHERE Author="Sonoo";
DCL commands are used to grant and take back authority from any database user.
Grant
Revoke
Example:
Example
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
These operations are automatically committed in the database that's why they cannot be used while creating
tables or dropping them.
COMMIT
ROLLBACK
SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
COMMIT;
COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been saved to the
database.
Syntax:
ROLLBACK;
5 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
DELETE FROM CUSTOMERS
ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back the entire
transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to select the attribute
based on the condition described by WHERE clause.
Syntax:
SELECT expressions
FROM TABLES
WHERE conditions;
For example:
SELECT emp_name
FROM employee
6 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
2. Union, intersect and except (MINUS) / Set operations in SQL
The SQL-92 operations ‘Union’, ‘intersect’ and ‘except’ operates on relations (tables) and are similar to the
relational algebra operations. But, the relations participating in the operations must have the same number
of columns.
The UNION, INTERSECTION, and the MINUS (Difference) operations are considered as SET operations. Out
of these three set operations, UNION, INTERSECTION operations are commutative, whereas MINUS
(Difference) operation is not commutative. All the three operations are binary operations.
1. UNION operation:
The union operator is used to combine the result set of two or more select statements.
Each select statement within union must have the same number of columns
The columns must also have similar data types.
The column in each select statement must also be in the same order.
Example:
The union operator results only distinct records, if you want to allow duplicate records use ‘ UNION ALL’
operator
7 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
2. Intersection operator
The intersection operation results the records that are common to the two relations
3. minus operation
If R and S are two union compatible relations then R–S returns the tuples that are present in R but not in S.
S–R returns the tuples that are present in S but not in R. It is to be noted that MINUS operation is not
commutative. That is R–S # S–R.
8 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
3. Nested Queries
One of the most powerful features of SQL is 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.
Scalar subquery
Example: Find the name of the student who has opted for the course RDBMS?
From the STUDENT and COURSE table, it is clear that only one student has opted for RDBMS (just for
example). We can get the name of the student using scalar subquery.
Correlated Subquery
In the case of correlated subquery, the processing of subquery requires data from the outer query.
9 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Example: The orderID which gives the order for the car “Maruti Esteem” can be found using the SQL
command EXISTS
Set-Comparison Operators
These include EXISTS, ANY, ALL, IN, <, >, =, <=, =>, <>.
For demonstrating above operators working consider the following three relations
10 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
1. EXISTS
The EXISTS operator is used to search for the presence of a row in a specified table that meets a certain
criterion
Example:- Find the names of sailors who have reserved boat number 103.
SQL> SELECT S.sname
FROM Sailors S
WHERE EXISTS (SELECT *
FROM Reserves R
WHERE R.bid = 103 AND R.sid = S.sid )
2. ANY
The ANY operator is used to compare a value to any applicable value in the list as per the condition.
Example:- Find sailors whose rating is better than some sailor called Horatio.
FROM Sailors S
FROM Sailors S2
3. ALL
The ALL operator is used to compare a value to all values in another value set.
FROM Sailors S
4. IN
The IN operator is used to compare a value to a list of literal values that have been specified.
Example:- Find the names of sailors who have reserved a red boat
FROM Sailors S
FROM Reserves R
FROM Boats B
11 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
4. Aggregative Operators
SQL provides seven built-in functions to facilitate query processing. The seven built-in functions are COUNT,
MAX, MIN, SUM, AVG, STDDEV, and VARIANCE.
1. COUNT Function
Example:
In order to understand MAX, MIN, and AVG aggregate function consider the relation CONSUMER
PRODUCTS. The relation CONSUMER PRODUCTS has two attributes, the name of the product and the
price associated with the product as shown in Table 4.4.
a) MAX Command
The MAX command stands for maximum value. The MAX command returns the maximum value of an
attribute. The syntax of MAX command is:
12 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Example-1: to get the maximum price of the product, the SQL command
Exampe-2: to find the name of the product which has maximum price by using PROJECTION operation and
the IN operator
b) MIN Command
The MIN command is used to return the minimum value of an attribute. The syntax of MIN
command is same as MAX command.
Syntax of MIN Command is
Example-1: To find the minimum price of the product is 3,500 which are returned as the result.
13 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Example-2: To know the name of the product which has minimum price, we can use IN operator
c) AVG Command
d) STDDEV Function
14 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
e) VARIANCE Function
The variance function is used to get the variance of the attribute values. The syntax of VARIANCE function
is:
f) GROUP BY Function
The GROUP BY clause is used to group rows to compute group-statistics. It is to be noted that when the
GROUP BY clause is present, then the SELECT clause may include only the columns that appear in the
GROUP BY clause and aggregate functions.
In order to understand the GROUP BY Function let us consider the table PLACEMENT as shown in Table 4.5
which refers to the number students placed in different companies. The table PLACEMENT consists of three
attributes (columns) which are company name, department name which refers to the curriculum stream and
strength which refers to the number of students placed.
15 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
g) HAVING Command
The HAVING command is used to select the group. In other words HAVING restricts the groups according to
a specified condition. The syntax of HAVING command is:
HAVING condition
Example: to find the details of the department in which more than 90 students got placement
16 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
h) SORTING of Results
The SQL command ORDER BY is used to sort the result in ascending or descending order.
The table used to understand ORDER BY command is BESTCRICKETER. The table BESTCRICKETER as shown
in Table 4.6 gives the details of best batsman of the world. The attributes of the BESTCRICKETER are the
name of the batsman, the country they belong to, and the number of centuries they scored.
Case 1: The syntax of ORDER BY command to arrange the result in ascending order is:
SELECT *
The SQL has built-in command BETWEEN which is used to perform range queries.
Let us try to find the details of the batsman who has scored centuries greater than 20 and less than 30.
17 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
5. Complex Integrity Constraints in SQL
We can specify complex constraints over a single table using table constraints, which have the form
CHECK conditional-expression
Example: To ensure that rating must be an integer in the range 1 to 10, we could use:
sname CHAR(10),
rating INTEGER,
age REAL,
2. Domain Constraints
A user can define a new domain using the CREATE DOMAIN statement, which makes use of CHECK
constraints.
18 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
3. 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.
As an example, suppose that we wish to enforce the constraint that the number of boats plus the number of
sailors should be less than 100.
sname CHAR(10),
rating INTEGER,
age REAL,
The best solution is to create an assertion instead of above complex form, as follows:
More precisely, it is like an event which occurs whenever a change is done to the tables or columns of the
tables.
1. Event
2. Condition
3. Action
Event: Event describes the modifications done to the database which lead to the activation of trigger. The
following fall under the category of events
a) Inserting, updating, deleting columns of the tables or rows of tables may activate trigger.
b) Creating, altering or dropping any database object may also lead to activation of trigger.
c) An error message or user log-on or log-off may also activate the trigger.
19 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Condition: Conditions are used to specify whether the particular action must be performed or not. If the
condition is evaluated to true then the respective action is taken otherwise the action is rejected.
Action: Action specifies the action to be taken when the corresponding event occurs and the condition
evaluates to true. An action is a collection of SQL statements that are executed as a part of trigger activation.
It is possible to activate the trigger before the event or after the event.
Examples-1:
The trigger called incr_count increments the counter for each inserted tuple that satis_es the condition age <
18.
DECLARE
count INTEGER;
BEGIN /* Action */
count := 0;
END
count := count + 1;
END
Example-2:
Develop programs using before and after triggers, row and statement triggers and instead of triggers
begin
(2) Insert
*trigger fired*
*1 row created*
(3)UPADTE
*trigger fired*
20 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
*1 row updated*
(4)DELETE
*trigger fired*
*1 row deleted*
Statement level trigger − It is fired only once for DML statement irrespective of number of rows
affected by statement. Statement-level triggers are the default type of trigger.
Before-triggers − At the time of defining a trigger we can specify whether the trigger is to be fired
before a command like INSERT, DELETE, or UPDATE is executed or after the command is executed.
Before triggers are automatically used to check the validity of data before the action is performed.
For instance, we can use before trigger to prevent deletion of rows if deletion should not be allowed
in a given case.
After-triggers − It is used after the triggering action is completed. For example, if the trigger is
associated with the INSERT command then it is fired after the row is inserted into the table.
Row-level triggers − It is fired for each row that is affected by DML command. For example, if an
UPDATE command updates 150 rows then a row-level trigger is fired 150 times whereas a statement-
level trigger is fired only for once.
Active Databases
Active database contains a set of triggers and therefore it becomes quite difficult to maintain active dataset.
Whenever a change is done to a database it may activate a trigger and then action part of the trigger is
executed. This action may inturn activate other trigger or it may activate the same trigger that initialized this
action. Such type of trigger that activates itself is called as recursive trigger. The DBMS executes such chains of
trigger in same pre-defined manner but it effects the concept of understanding the collection of triggers.
Triggers are used to maintain the data integrity in the database. Whenever a change is done in a database, a
trigger can be used to indicate that change. There are several uses of triggers.
21 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
7. NULL values
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a value in a field that
appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a NULL value is
different than a zero value or a field that contains spaces.
Syntax
Here, NOT NULL signifies that column should always accept an explicit value of the given data type. There
are two columns where we did not use NOT NULL, which means these columns could be NULL.
A field with a NULL value is the one that has been left blank during the record creation.
Example
The NULL value can cause problems when selecting data. However, because when comparing an
unknown value to any other value, the result is always unknown and not included in the results.
You must use the IS NULL or IS NOT NULL operators to check for a NULL value.
Consider the following CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
22 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
This would produce the following result −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+
If an aggregate function against a column that contains nulls is executed, the function ignores the nulls. This
prevents unknown or inapplicable values from affecting the result of the aggregate.
Aggregate functions, except COUNT(), return null for an aggregate that has an argument that evaluates to an
empty set. (COUNT() returns 0 for an empty set.)
When specifying a column that contains nulls as a grouping column (that is, in the GROUP BY clause) for an
aggregate function, nulls in the column are treated as equal for the purposes of grouping as if IS NOT
DISTINCT FROM were used. In all other situations, nulls do not compare as equal to other nulls.
Questions:
2. What is nested query? Explain with an example. Also write about correlated nested queries.
6. Explain the necessity of NULL values in SQL with an example and also explain how these NULL values are
treated by aggregate functions?
23 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Exercise questions.
i) Write a query to find the names of sailors with age over 20 years and not reserved a red color boat
ii) Write a query to find the age of the youngest sailor for each rating level.
i) Write a query to find the names of sailors who have reserved both red and blue color boats on 01-JAN-
2021.
ii) Write a query to find the name and age of oldest sailor
iii) Write a query to find sailors with high rating reserves ‘Red’ color boat.
DR-CR:varchar,AMT:number(8,2),CURBAL:number(8,2))
i) The account number for which the transaction is being performed is a valid account number.
ii) In case of a withdrawal the amount does not exceed the current balance for that account number.
i) Write a query to find the names of sailors who have not reserved red color boat.
ii) Write a query to find all sids of sailors who are having rating of 10 and reserved boat number 104.
6. Given Student Report Database, in which student marks assessment is recorded(Assume 3 subjects). Create
a trigger so that the total and average of specified marks is automatically inserted whenever a record is insert.
24 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
9. Write queries for the following using the given information:
ii) Find months between employee DOJ and DOR from emp-schema.
10. Write the SQL expressions for the following relational database:
Sailor schema (sailor id, Boat id, sailor name, rating, age)
Reserves (Sailor id, Boat id, Day)Boat Schema (boat id, Boat name, color)
i) Find the age of the youngest sailor for each rating level.
ii) Find the age of the youngest sailor who is eligible to vote for each rating level with at lead two such
sailors.
iv) Find the average age of sailor for each rating level that at least 2 sailors
25 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED