0% found this document useful (0 votes)
10 views25 pages

Unit III SQL

This document provides an overview of SQL, covering its basic query structure, data types, commands, and set operations. It details the four types of SQL commands: Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), along with examples. Additionally, it explains nested queries, aggregative operators, and set operations like UNION, INTERSECT, and EXCEPT.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
10 views25 pages

Unit III SQL

This document provides an overview of SQL, covering its basic query structure, data types, commands, and set operations. It details the four types of SQL commands: Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), and Transaction Control Language (TCL), along with examples. Additionally, it explains nested queries, aggregative operators, and set operations like UNION, INTERSECT, and EXCEPT.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

UNIT-III SQL: Queries, Constraints, Triggers

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

1. The form of basic SQL Query

Clauses are used to construct an SQL statement so that when executed the statement will perform a
particular function.

The basic form of an SQL query is:

SELECT [DISTINCT] {*| column_name (, column_name,...)}


FROM table_name [alias] (, table_name,...)
[WHERE condition]
[GROUP BY column_list] [HAVING condition]
[ORDER BY column_list]

The table below lists and describes the most commonly used SQL clauses. An SQL clause within bracket [ ]
indicates the clause is optional.

S.No SQL Clause Function Performed


1 SELECT specifies which columns are to appear in the output
2 DISTINCT eliminates duplicates
3 From specifies the tables to be used
4 Where filters the rows according to the condition
5 Group By forms groups of rows with the same column value
6 Having filters the group
7 Ordered By sorts the order of the output

Q) SQL Data types

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

1. Binary Data types

There are Three types of binary Datatypes which are given below:

Data Type Description

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.

2. Approximate Numeric Data type :

The subtypes are given below:

Data type From To Description

float -1.79E + 308 1.79E + 308 It is used to specify a floating-point value e.g. 6.2, 2.9 etc.

real -3.40e + 38 3.40E + 38 It specifies a single precision floating point number

3. Exact Numeric Datatype

The subtypes are given below:

Data type Description

int It is used to specify an integer value.

smallint It is used to specify small integer value.

bit It has the number of bits to store.

decimal It specifies a numeric value that can have a decimal number.

numeric It is used to specify a numeric value.

4. Character String Datatype

The subtypes are given below:

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.

It has a maximum length of 2,147,483,647 characters. It contains variable-length non-unicode


text
characters.

5. Date and time Data types

The subtypes are given below:

Datatype Description

date It is used to store the year, month, and days value.

time It is used to store the hour, minute, and second values.

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.

1. Data Definition Language (DDL)

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

Here are some commands that come under DDL:

 CREATE

 ALTER

 DROP

 TRUNCATE

a. CREATE It is used to create a new table in the database.

Syntax: CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example: CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);

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.

Syntax: DROP TABLE table_name;

Example: DROP TABLE EMPLOYEE;

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.

1. To add a new column in the table

Syntax: ALTER TABLE table_name ADD column_name COLUMN-definition;

Example: ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));

2. To modify existing column in the table:

Syntax: ALTER TABLE table_name MODIFY(column_definitions....);

Example: ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space containing the table.

Syntax: TRUNCATE TABLE table_name;

Example: TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

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

Here are some commands that come under DML:

 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)

INSERT INTO TABLE_NAME VALUES (value1, value2, value3, .... valueN);

Example: INSERT INTO books (Author, Subject) VALUES ("Sonoo", "DBMS");

b. UPDATE: This command is used to update or modify the value of a column in the table.

Syntax:

UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CONDITION]

Example: UPDATE students

SET User_Name = 'Sonoo'

WHERE Student_Id = '3'

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:

DELETE FROM table_name [WHERE condition];

Example: DELETE FROM Books

WHERE Author="Sonoo";

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

 Grant
 Revoke

a. Grant: It is used to give user access privileges to a database.

Example:

GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example

REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language

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.

Here are some commands that come under TCL:

 COMMIT
 ROLLBACK
 SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

COMMIT;

DELETE FROM CUSTOMERS

WHERE AGE = 25;

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

WHERE AGE = 25;

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;

5. Data Query Language

 DQL is used to fetch the data from the database.


 It uses only one command:

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

WHERE age > 20;

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

A scalar subquery returns single row, single column result.

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.

SQL> SELECT S.sid

FROM Sailors S

WHERE S.rating > ANY (SELECT S2.rating

FROM Sailors S2

WHERE S2.sname = `Horatio’);

3. ALL

The ALL operator is used to compare a value to all values in another value set.

Example:- Find the name of the sailor with heights rating

SQL> SELECT S.Sid

FROM Sailors S

WHERE S.rating >= ALL (SELECT S2.rating

FROM Sailors S2);

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

SQL> SELECT S.sname

FROM Sailors S

WHERE S.sid IN (SELECT R.sid

FROM Reserves R

WHERE R.bid IN (SELECT B.bid

FROM Boats B

WHERE B.color = `red’);

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

The built-in function returns the number of rows of the table.

The syntax of Count (*) function is:

SELECT COUNT (*)

FROM table name;

Example:

2. MAX, MIN, and AVG Aggregate Function

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:

SELECT MAX (attribute name)

FROM table name;

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

SELECT MIN (attribute name)

FROM table name;

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

The AVG command is used to get the average value of an attribute.

The syntax of AVG command is:

SELECT AVG (attribute name)

FROM table name;

Example: to get the average price of the product

d) STDDEV Function

The STDDEV function is used to compute the


standard deviation of the attribute values. The
syntax of the standard deviation function is:

SELECT STDDEV (attribute name)

FROM table name;

Example: The STDDEV function applied to the


relation CONSUMERPRODUCT

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:

VARIANCE (attribute name)

FROM table name;

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.

The syntax of GROUP BY command is:

SELECT attribute name, aggregate function

FROM table name

GROUP BY attribute name;

Example: to find the total number of students placed in each branch is

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:

SELECT attribute name, aggregate function

FROM table name

GROUP BY attribute name

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 *

FROM table name

ORDER BY attribute name ASC;

i) Range Queries Using Between

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

1. Constraints over a Single Table

Example: To ensure that rating must be an integer in the range 1 to 10, we could use:

SQL> CREATE TABLE Sailors ( Sid INTEGER,

sname CHAR(10),

rating INTEGER,

age REAL,

PRIMARY KEY (sid),

CHECK (rating >= 1 AND rating <= 10))

2. Domain Constraints

A user can define a new domain using the CREATE DOMAIN statement, which makes use of CHECK
constraints.

SQL> CREATE DOMAIN ratingval INTEGER DEFAULT 0

CHECK (VALUE >= 1 AND VALUE <= 10);

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.

We could try the following table constraint:

SQL> CREATE TABLE Sailors ( sid INTEGER,

sname CHAR(10),

rating INTEGER,

age REAL,

PRIMARY KEY (sid),

CHECK (rating >= 1 AND rating <= 10)

CHECK ((SELECT COUNT (S.sid) FROM Sailors S )

+ (SELECT COUNT (B.bid) FROM Boats B )< 100 ))

The best solution is to create an assertion instead of above complex form, as follows:

SQL> CREATE ASSERTION smallClub

CHECK ((SELECT COUNT (S.sid) FROM Sailors S )

+ (SELECT COUNT (B.bid) FROM Boats B)< 100

6. Triggers and Active Data bases


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.

More precisely, it is like an event which occurs whenever a change is done to the tables or columns of the
tables.

The general format of the trigger includes the following

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.

CREATE TRIGGER init count BEFORE INSERT ON Students /* Event */

DECLARE

count INTEGER;

BEGIN /* Action */

count := 0;

END

CREATE TRIGGER incr 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

Example-2:

Develop programs using before and after triggers, row and statement triggers and instead of triggers

(1) Create a trigger

create or replace trigger trg2 after insert or delete or update on dept1

for each row when(new.deptno>0)

begin

dbms_output.put_line('trigger fired'); end;

(2) Insert

SQL> insert into dept values('sindhu',30);

*trigger fired*

*1 row created*

(3)UPADTE

SQL> udpate dept1 set deptno=19 where dname='sindhu';

*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

SQL> delete from dept where deptno=30;

*trigger fired*

*1 row deleted*

The different types of triggers are explained below −

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

 Triggers can be used to maintain data integrity.


 Triggers can be used to identify the usual events that occur in a database.
 Triggers can be used for security checks and also for auditing.

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

The basic syntax of NULL while creating a table.

SQL> CREATE TABLE CUSTOMERS(

ID INT NOT NULL,

NAME VARCHAR (20) NOT NULL,

AGE INT NOT NULL,

ADDRESS CHAR (25) ,

SALARY DECIMAL (18, 2),

PRIMARY KEY (ID) );

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 | |
+----+----------+-----+-----------+----------+

Now, following is the usage of the IS NOT NULL operator.

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY


FROM CUSTOMERS
WHERE SALARY IS NOT NULL;

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 |
+----+----------+-----+-----------+----------+

Now, following is the usage of the IS NULL operator.

SQL> SELECT ID, NAME, AGE, ADDRESS, SALARY


FROM CUSTOMERS
WHERE SALARY IS NULL;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | |
| 7 | Muffy | 24 | Indore | |
+----+----------+-----+-----------+----------+

How null values are treated by aggregate function?

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:

1. Explain the form of a basic SQL query in detail with examples.

2. What is nested query? Explain with an example. Also write about correlated nested queries.

3. Explain different aggregative functions in SQL with examples.

4. Explain in details complex integrity constraints in SQL.

5. Explain triggers and active databases.

6. Explain the necessity of NULL values in SQL with an example and also explain how these NULL values are
treated by aggregate functions?

7. Write about various set operations in SQL.

23 © www.tutorialtpoint.net all rights reserved Prepared by D. VENKATA REDDY M.Tech(CS), UGC NET, APSET QUALIFIED
Exercise questions.

1. Why correlated sub queries are exhibit slower performance?

2. Consider the following Relational schemas,

Sailors( sid: Integer, sname: String, age: Integer, rating: Integer)

Boats(bid: Integer, bname: String, bcolor: String)

Reserves(sid: Integer, bid: Integer, date: Date)

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.

3. Consider the following Relational schemas,

Sailors( sid: Integer, sname: String, age: Integer, rating: Integer)

Boats(bid: Integer, bname: String, bcolor: String)

Reserves(sid: Integer, bid: Integer, date: Date)

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.

4. Consider the following relational schema:

Trans-Mstr (TID: Integer,ACCNO: Integer,DATE:Date,

DR-CR:varchar,AMT:number(8,2),CURBAL:number(8,2))

Write a database trigger on the TRANS-MSTR that checks the following:

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.

5. Consider the following Relational schemas,

Sailors( sid: Integer, sname: String, age: Integer, rating: Integer)

Boats(bid: Integer, bname: String, bcolor: String)

Reserves(sid: Integer, bid: Integer, date: Date)

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.

7. Write SQL queries to perform modifications of relational databases

8. Write the differences between constraints and triggers in SQL

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:

Emp_Name DOB DOJ EmpSalary Bonus DOR


Buelin 06-12-1983 07-08-2005 15000 600 07-08-2055

Andy 12-01-1970 06-12-1973 20000 1200 06-12-2043

Lubber 07-08-1985 12-04-2006 13000 500 12-04-2056

Zobra 08-02-1960 07-03-1982 25000 1500 07-03-2032

i) Find total salary of employees from emptable.

ii) Find months between employee DOJ and DOR from emp-schema.

iii) Arrange empnames in ascending and descending order.

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.

iii) Find the number of reservations for each red boat.

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

You might also like