DBMS Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

The basic structure of an SQL query consists of several components:

1. SELECT: The SELECT statement specifies the columns or fields that you want to retrieve
from the database table. You can select specific columns or use the asterisk (*) to select all
columns.

Example:

SELECT column1, column2 FROM table_name;

2. FROM: The FROM clause indicates the table or tables from which you want to retrieve the
data. It specifies the name of the table or tables separated by commas.

Example:

SELECT column1, column2 FROM table1, table2;

3. WHERE: The WHERE clause is used to specify conditions that filter the rows returned by
the query. It allows you to define criteria that the data must meet to be included in the result
set.

Example:

SELECT column1, column2 FROM table_name WHERE condition;

4. GROUP BY: The GROUP BY clause is used to group rows based on one or more
columns. It is often used in conjunction with aggregate functions like SUM, COUNT, AVG,
etc.

Example:

SELECT column1, SUM(column2) FROM table_name GROUP BY column1;

5. HAVING: The HAVING clause is used to specify conditions for the grouped rows after
the GROUP BY clause has been applied. It filters the groups based on the specified
conditions.

Example:
SELECT column1, SUM(column2) FROM table_name GROUP BY column1 HAVING
condition;

6. ORDER BY: The ORDER BY clause is used to sort the result set based on one or more
columns. It can sort in ascending (ASC) or descending (DESC) order.

Example:

SELECT column1, column2 FROM table_name ORDER BY column1 ASC, column2


DESC;
7. LIMIT: The LIMIT clause is used to restrict the number of rows returned by the query. It
specifies the maximum number of rows to be retrieved.

Example:

SELECT column1, column2 FROM table_name LIMIT 10;


The SQL UNION Operator

The UNION operator is used to combine the result-set of two or more SELECT statements.

• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
UNION ALL Syntax

The UNION operator selects only distinct values by default. To allow duplicate values,
use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set are usually equal to the column names in the
first SELECT statement.

SQL UNION Example

The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:

Example:
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
o/p:
City

Aachen
Annecy
Bend
Berlin
Cork
Delhi

INTERSECT in SQL
The INTERSECT operator in SQL is used to retrieve the records that are identical/common
between the result sets of two SELECT (tables) statements.
In real-time scenarios, there will be a huge number of tables in a database that contains
information. The user may find it challenging to gather common information from various
tables. So we use the INTERSECT operator to accomplish that. It helps to retrieve the common
data from various tables.
Syntax
To retrieve identical records from two different tables, we use the following syntax
SELECT column1, column2,…, columnN
FROM table1, table2,…, tableN
INTERSECT
SELECT column1, column2,…, columnN
FROM table1, table2,…, tableN
Example
First of all, let us create a table named “STUDENTS” using the following query −
SQL> CREATE TABLE STUDENTS(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
HOBBY VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY(ID)
);
Once the table is created, let us insert some values to the table using the query below −

Let us verify whether the table “STUDENTS” is created or not using the following query −

SQL> SELECT * FROM STUDENTS;


As we can see in the below output, the table has been created in the database.
+-----+----------+--------------+-------+
| ID | NAME | HOBBY | AGE |
+-----+----------+--------------+-------+
| 1 | Vijay | Cricket | 18 |
| 2 | Varun | Football | 26 |
| 3 | Surya | Cricket | 19 |
| 4 | Karthik | Cricket | 25 |
| 5 | Sunny | Football | 26 |
| 6 | Dev | Cricket | 23
Let us create another table “ASSOCIATES” using the following query –
SQL> CREATE TABLE ASSOCIATES(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
SUBJECT VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
HOBBY VARCHAR(20) NOT NULL,
PRIMARY KEY(ID)
);
Let’s insert some values into the table using the following query –
SQL> INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(1,
'Naina', 'Maths', 24, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(2, 'Varun',
'Physics', 26, 'Football');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(3, 'Dev',
'Maths', 23, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(4, 'Priya',
'Physics', 25, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(5,
'Aditya', 'Chemistry', 21, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(6,
'Kalyan', 'Maths', 30, 'Football');
Let us verify whether the table “ASSOCIATES” is created or not using the following query

SQL> SELECT * FROM ASSOCIATES;
As we can see in the below output, the table has been created in the database.
+-----+----------+---------------+-------+----------+
| ID | NAME | SUBJECT | AGE | HOBBY |
+-----+----------+---------------+-------+----------+
| 1 | Naina | Mathematics | 24 | Cricket |
| 2 | Varun | Physics | 26 | Football |
| 3 | Dev | Mathematics | 23 | Cricket |
| 4 | Priya | Physics | 25 | Cricket |
| 5 | Adithya | Chemistry | 21 | Cricket |
| 6 | Kalyan | Mathematics | 30 | Football |
Now, we are trying to retrieve the common records from both the tables using the following
query –
SQL> SELECT NAME, AGE, HOBBY FROM STUDENTS
INTERSECT
SELECT NAME, AGE, HOBBY FROM ASSOCIATES
Output
When we execute the above query, the output is obtained as follows −
+-----------+-------+----------+
| NAME | AGE | HOBBY |
+-----------+-------+----------+
| Dev | 23 | Cricket |
| Varun | 26 | Football |
+-----------+-------+----------+
INTERSECT with BETWEEN operator
As we discussed in the initial syntax, we can also use the INTERSECT operator along with
conditional operators.
We can use the INTERSECT operator with the BETWEEN operator in SQL to find rows that
fall within a specified range.
Example
Now, let us retrieve the records that are common in both tables. In addition; we are retrieving
the records who are aged between 25 and 30 using the following query.
SQL> SELECT NAME, AGE, HOBBY FROM STUDENTS
WHERE AGE BETWEEN 25 AND 30

INTERSECT

SELECT NAME, AGE, HOBBY FROM ASSOCIATES


WHERE AGE BETWEEN 20 AND 30
Output
The output for the above query is produced as given below −
+-----------+-------+----------+
| NAME | AGE | HOBBY |
+-----------+-------+----------+
| Varun | 26 | Football |
+-----------+-------+----------+
INTERSECT with IN operator
We can also use the INTERSECT operator with the IN operator in SQL to find the common
rows that have the specified values. The IN operator is used to filter a result set based on a list
of specified values.
Example
Here, we are trying to retrieve the common records from both tables. In addition; we are using
the IN operator to retrieve the records whose hobby is ‘Cricket’.
SQL> SELECT NAME, AGE, HOBBY FROM STUDENTS
WHERE HOBBY IN('Cricket')

INTERSECT

SELECT NAME, AGE, HOBBY FROM ASSOCIATES


WHERE HOBBY IN('Cricket')
Output
When we execute the above query, the output is obtained as follows −
+-----------+-------+----------+
| NAME | AGE | HOBBY |
+-----------+-------+----------+
| Dev | 26 | Cricket
INTERSECT with LIKE operator
The LIKE operator is used to perform pattern matching on a string. The INTERSECT operator
can also be used with the LIKE operator in SQL to find the common rows that matches with
the specified pattern.
Example
Let us use the wildcard ‘%’ with the LIKE operator to retrieve the names which starts with
‘v’ from the common names of both tables.
SQL> SELECT NAME, AGE, HOBBY FROM STUDENTS
WHERE NAME LIKE 'v%'

INTERSECT

SELECT NAME, AGE, HOBBY FROM ASSOCIATES


WHERE NAME LIKE 'v%'
Output
The output for the above query is produced as given below −
+-----------+-------+----------+
| NAME | AGE | HOBBY |
+-----------+-------+----------+
| Varun | 26 | Football

EXCEPT:
The EXCEPT operator in SQL is used to retrieve the unique records that exist in the first table,
not the common records of both tables. This operator acts as the opposite of the SQL UNION
operator.
For better understanding consider two tables with records as shown in the following image −
If we perform the EXCEPT operator on the above two tables to retrieve the names, it will
display the records only from the first table which are not in common with the records of the
second table.
Here, “Dev” is common in both tables. So, the EXECPT operator will eliminate it and retrieves
only “Sara” and “Jay” as output.
Syntax
Following is the syntax of the EXCEPT operator in SQL −
SELECT column1, column2,…, columnN
FROM table1, table2,…, tableN
[Conditions] //optional
EXCEPT
SELECT column1, column2,…, columnN
FROM table1, table2,…, tableN
[Conditions] //optional
Note − The number and order of columns in both SELECT statements should be the same.
Example
First of all, let us create a table named “STUDENTS” using the following query −
SQL> CREATE TABLE STUDENTS(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
HOBBY VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY(ID)
);
Once the table is created, let us insert some values to the table using the query below –
SQL> INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(1, 'Vijay',
'Cricket', 18);
INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(2, 'Varun', 'Football',
26);
INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(3, 'Surya', 'Cricket', 19);
INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(4, 'Karthik', 'Cricket',
25);
INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(5, 'Sunny', 'Football',
26);
INSERT INTO STUDENTS(ID, NAME, HOBBY, AGE) VALUES(6, 'Dev', 'Cricket', 23);
Let us verify whether the table “STUDENTS” is created or not using the following query −
SQL> SELECT * FROM STUDENTS;
As we can see in the below output, the table has been created in the database.
+-----+----------+--------------+-------+
| ID | NAME | HOBBY | AGE |
+-----+----------+--------------+-------+
| 1 | Vijay | Cricket | 18 |
| 2 | Varun | Football | 26 |
| 3 | Surya | Cricket | 19 |
| 4 | Karthik | Cricket | 25 |
| 5 | Sunny | Football | 26 |
| 6 | Dev | Cricket | 23 |
+-----+----------+--------------+-------+

Let us create another table named “ASSOCIATES” using the following query −
SQL> CREATE TABLE ASSOCIATES(
ID INT NOT NULL,
NAME VARCHAR(20) NOT NULL,
SUBJECT VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
HOBBY VARCHAR(20) NOT NULL,
PRIMARY KEY(ID)
);

Once the table is created, let us insert some values to the table using the query below −

SQL> INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(1,


'Naina', 'Maths', 24, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(2, 'Varun',
'Physics', 26, 'Football');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(3, 'Dev',
'Maths', 23, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(4, 'Priya',
'Physics', 25, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(5,
'Aditya', 'Chemistry', 21, 'Cricket');
INSERT INTO ASSOCIATES(ID, NAME, SUBJECT, AGE, HOBBY) VALUES(6,
'Kalyan', 'Maths', 30, 'Football');
Let us verify whether the table “ASSOCIATES” is created or not using the following query
− SQL> SELECT * FROM ASSOCIATES;
As we can see in the below output, the table has been created in the database.
+-----+----------+---------------+-------+----------+
| ID | NAME | SUBJECT | AGE | HOBBY |
+-----+----------+---------------+-------+----------+
| 1 | Naina | Mathematics | 24 | Cricket |
| 2 | Varun | Physics | 26 | Football |
| 3 | Dev | Mathematics | 23 | Cricket |
| 4 | Priya | Physics | 25 | Cricket |
| 5 | Adithya | Chemistry | 21 | Cricket |
| 6 | Kalyan | Mathematics | 30 | Football |
+-----+----------+--------------+-------+----------

Let us retrieve the records that are only unique in the first table using the below query –
SQL> SELECT NAME, HOBBY, AGE
FROM STUDENTS

EXCEPT

SELECT NAME, HOBBY, AGE


FROM ASSOCIATES
Output
When we execute the above query, the output is obtained as follows −
+-----------+--------------+-------+
| NAME | HOBBY | AGE |
+-----+----------+---------+-------+
| Karthik | Cricket | 25 |
| Sunny | Football | 26 |
| Surya | Cricket | 19 |
| Vijay | Cricket | 18 |
+-----------+--------------+-------+
EXCEPT with BETWEEN operator
As we discussed in the initial syntax, we can also use the EXCEPT operator along with
conditional operators. We can use the EXCEPT operator with the BETWEEN operator in SQL
to exclude rows that fall within a specified range.
Example
Let us retrieve the records that are only unique in the first table. In addition; we are retrieving
the records who are aged between 20 and 30 using the following query.
SQL> SELECT NAME, HOBBY, AGE
FROM STUDENTS
WHERE AGE BETWEEN 20 AND 30

EXCEPT

SELECT NAME, HOBBY, AGE


FROM ASSOCIATES
WHERE AGE BETWEEN 20 AND 30
Output
When we execute the program query, the output is obtained as follows −
+----------+----------+-----+
| NAME | HOBBY | AGE |
+----------+----------+-----+
| Karthik | Cricket | 25 |
| Sunny | Football | 26 |
+----------+----------+-----+
Except with IN operator
We can also use the EXCEPT operator with the IN operator in SQL to exclude rows that have
the specified values. The IN operator is used to filter a result set based on
a list of specified values.
Example
Here, we are fetching the records that are only unique in the first table. In addition; we are
using the IN operator to retrieve the records whose hobby is ‘Cricket’.
SQL> SELECT NAME, HOBBY, AGE FROM STUDENTS
WHERE HOBBY IN('Cricket')

EXCEPT

SELECT NAME, HOBBY, AGE FROM ASSOCIATES


WHERE HOBBY IN('Cricket')
Output
When we execute the above query, the output is obtained as follows −
+-----------+--------------+-------+
| NAME | HOBBY | AGE |
+-----+----------+---------+-------+
| Karthik | Cricket | 25 |
| Surya | Cricket | 19 |
| Vijay | Cricket | 18 |
EXCEPT with LIKE operator
The EXCEPT operator can also be used with the LIKE operator in SQL to exclude rows that
matches with the specified pattern. The LIKE operator is used to perform pattern matching on
a string.
Example
Let us use the wildcard ‘%’ with the LIKE operator to retrieve the names which starts with
‘v’ from the result set of first SELECT statement.
SQL> SELECT NAME, AGE, HOBBY FROM STUDENTS
WHERE NAME LIKE 'v%'

EXCEPT

SELECT NAME, AGE, HOBBY FROM ASSOCIATES


WHERE NAME LIKE 'v%'
Output
The output for the above query is produced as given below −
+-----------+-------+----------+
| NAME | AGE | HOBBY |
+-----------+-------+----------+
| Vijay | 18 | Cricket |
+-----------+-------+----------+
Definition of Nested Query :

Query written inside a query is called as SQL Nested Query


The user has question in mind that the query inside query will be Select query or any other
query.There are Four types of nested queries.

1.Nested Queries with Select Statement


2.Nested Queries with Insert Statement
3.Nested Queries with Update Statement
4.Nested Queries with Delete Statement.

These are some most important types of Nested queries which we will look with example in
next sections.

How to Write SQL Nested Queries :


Bullet-points needs to be considered while writing nested Queries :

1.The SQL Nested Query will be always enclosed inside the parentheses.

2.Nested sub-query can have only one column in select clause.


3.Order by clause is restricted in query which is inner query but outer query or main query
can use order by clause.

4.User needs to take care of multiple rows operator (IN,ANY) if sub-query will return more
than one rows.

5.Between–And Operator can not be used inside the Nested Query.

Type 1 : SQL Nested Queries with Select Statement

There are so many business situations where user needs to use nested subqueries to fetch the
exact data from two or more tables.It is also called as Inline view in SQL.

Syntax :
Select Column1,Column2… From Table_Name

Where Column_Name Operator

(Select Column1,Column2…. From Table_Name_2)…

Operator (Select Column1,Column2…..From Table_Name_3)…

;
The user can use N Number of Inner Queries to fetch the required output. But using nesting
of Queries is not a good practice for performance tuning perspective.

Real Life Examples of Nested Queries :


Following are two tables,

Employee Table :

Employee No Employee Name Department

1 Rohan SQL

2 Rajiv PL SQL

3 Ram Java

Salary Table :
Employee No Salary

1 25000
2 35000

3 45000

If user wants to fetch the all records of Employees who’s salary is greater that 25000.

In this case user needs to go for Nested Query.

Query :
Select * from Employee where Employee_No

In (Select Employee_No From Salary where Salary > 25000);

The Above Query is nested query which will give you the Employees data whose salary is
greater than 25000.

Type 2 : SQL Nested Queries with Insert Statement

There are so many real life situations where user needs to use nested queries to insert the data
in table. So many times user needs to use the testing and will need some special data.To
tackle this situation Nested Queries with Insert statements will work.

Syntax :
Insert in to Tablename

(Select Column_1,Column2….From Tablename_1);

Real Life Example :


Let us consider the same tables given in Select Statement nested queries. User has created the
replica of Employee table and needs the data where salary is greater than 25000. The
Employee table replica name is Employee_Bkp.

Query :
Insert in to Employee_Bkp

(Select * from Employee where Employee_No

In (Select Employee_No From Salary where Salary > 25000));


The above nested query will help user to insert the required data in Employee_Bkp table.
Inner and Outer Query
Type 3 : SQL Nested Queries with Update Statement

There are sometimes user needs to update the data according to client requirements.If the data
is not huge then user can use the nested queries to update the data.

Syntax :
Update Table Set Column_name =

(Select column1,Column2….From table);

Real Life Example :


I would like you to refer the above two tables only. User wants to change the name of
Employee to Amit where Salary of that Employee is 25000.

Update Employee Set Name =

Select ‘Amit’ from Employee where Employee_No

= (Select Employee_No From Salary where Salary = 25000));


The above query will help you to update name to ‘Amit’.

Type 4 : SQL Nested Queries with Delete Statement

Sometimes user needs to delete the data with specific condition.So to delete the data with
condition user needs to use Delete nested queries.

Syntax :
Delete from tablename

Where Column_Name Operator

(Select Columnname1,Columnname2… from Tablename2);


Real Life Example :

We need to delete data from Employee table where salary is greater than 25000.

Query :
Delete from Employee where Employee_No IN

( Select Employee_No From Salary where Salary > 25000 );


The above statement will delete the data from Employee table where salary is greater than
25000

SQL Aggregate Functions


o SQL aggregation function is used to perform the calculations on multiple rows of a
single column of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION

o COUNT function is used to Count the number of rows in a database table. It can work
on both numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.

Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: COUNT()

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;

Output:

10

Example: COUNT with WHERE


1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST;

Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY;

Output:

Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING

1. SELECT COMPANY, COUNT(*)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING COUNT(*)>2;

Output:

Com1 5
Com2 3

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields
only.
Syntax

1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )

Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;

Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;

Output:

320

Example: SUM() with GROUP BY

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;

Output:

Com1 150
Com2 170

Example: SUM() with HAVING

1. SELECT COMPANY, SUM(COST)


2. FROM PRODUCT_MAST
3. GROUP BY COMPANY
4. HAVING SUM(COST)>=170;
Output:

Com1 335
Com3 170

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.

Syntax

1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )

Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;

Output:

67.00

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.

Syntax

1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )

Example:

1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines
the smallest value of all selected values of a column.
Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )

Example:

1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;

Output:

10

NULL Values:
In SQL there may be some records in a table that do not have values or data for every field
and those fields are termed as a NULL value.

NULL values could be possible because at the time of data entry information is not available.
So SQL supports a special value known as NULL which is used to represent the values of
attributes that may be unknown or not apply to a tuple.
Importance of NULL Value
It is important to understand that a NULL value differs from a zero value.
A NULL value is used to represent a missing value, but it usually has one of three different
interpretations:
The value unknown (value exists but is not known)
Value not available (exists but is purposely withheld)
Attribute not applicable (undefined for this tuple)
It is often not possible to determine which of the meanings is intended. Hence, SQL does not
distinguish between the different meanings of NULL.
Principles of NULL values
Setting a NULL value is appropriate when the actual value is unknown, or when a value is
not meaningful.
A NULL value is not equivalent to a value of ZERO if the data type is a number and is not
equivalent to spaces if the data type is a character.
A NULL value can be inserted into columns of any data type.
A NULL value will evaluate NULL in any expression.
A trigger is a procedure which is automatically invoked by the DBMS in response to
changes to the database, and is specified by the database administrator (DBA). A
database with a set of associated triggers is generally called an active database.

Parts of trigger
A triggers description contains three parts, which are as follows −
• Event − An event is a change to the database which activates the
trigger.
• Condition − A query that is run when the trigger is activated is called as
a condition.
• Action −A procedure which is executed when the trigger is activated
and its condition is true.

Use of trigger
Triggers may be used for any of the following reasons −
• To implement any complex business rule, that cannot be implemented
using integrity constraints.
• Triggers will be used to audit the process. For example, to keep track of
changes made to a table.
• Trigger is used to perform automatic action when another concerned
action takes place.

Types of triggers
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.
Create database trigger
To create a database trigger, we use the CREATE TRIGGER command. The details
to be given at the time of creating a trigger are as follows −

• Name of the trigger.


• Table to be associated with.
• When trigger is to be fired: before or after.
• Command that invokes the trigger- UPDATE, DELETE, or INSERT.
• Whether row-level triggers or not.
• Condition to filter rows.
• PL/SQL block is to be executed when trigger is fired.
The syntax to create database trigger is as follows −

CREATE [OR REPLACE] TRIGGER triggername


{BEFORE|AFTER}
{DELETE|INSERT|UPDATE[OF COLUMNS]} ON table
[FOR EACH ROW {WHEN condition]]
[REFERENCE [OLD AS old] [NEW AS new]]
BEGIN
PL/SQL BLOCK
END.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy