Unit - 3 - DBMS
Unit - 3 - DBMS
SQL is a structured query language, which is used to deal with structured data. Structured data is
data that is generally stored in the form of relations or tables.
Whenever we store the data in tables or relations, we need SQL commands. Moreover, these
commands are also required to retrieve the data which is stored in tables.
Let us take a deeper dive into the classification of SQL commands with the help of practical
examples. We will use the MySQL database for writing all the queries.
(A) DDL
DDL stands for data definition language. DDL Commands deal with the schema, i.e.,
the table in which our data is stored.
All the structural changes such as creation, deletion and alteration on the table can be
carried with the DDL commands in SQL.
Commands covered under DDL are:
1. CREATE
2. ALTER
3. DROP
4. TRUNCATE
5. RENAME
1. CREATE:
In SQL, whenever we wish to create a new database or a table in a database, we use CREATE
command.
Example 1:
Write a query to create a database and give the name of the database as school.
Query:
Here, we have executed a CREATE DATABASE query followed by the database name
'SCHOOL'.
We will execute the following command to verify that the database 'SCHOOL' is created:
Example 2:
Write a query to create a table in the database 'SCHOOL' and give the table's name as t_school.
To create a table 't_school' in the 'SCHOOL' database, we must select the 'SCHOOL' database.
We have executed the 'USE command' followed by the database name, i.e., 'SCHOOL'.
Now just after the execution of this query, we will execute the following query:
Here, we have executed a CREATE TABLE query followed by the table name 't_school'.
We will execute the following command to verify that the table 't_school' is created:
The above command results verify that the 't_school' table is successfully created in the
'SCHOOL' database.
2. ALTER
In SQL, whenever we wish to alter the table structure, we will use the ALTER command. Using
alter command, we can make structural changes to the table, such as adding a new column,
removing or deleting an existing column from the table, changing the datatype of an existing
column and renaming an existing column.
Let's look at the syntax before writing the queries using ALTER command.
Example 1:
Write a query to add a new column Board_of_Education in the t_school table of the datatype
VARCHAR.
Before executing a query to add a new column to the 't_school' table, we will execute the
following query to see the table structure:
Now, we will again apply the DESC command on the t_school table.
This verifies that the new column 'Board_of_Education' is successfully added to the t_school
table.
Example 2:
Write a query to remove the column Board_of_Education from the t_school table.
Before executing a query to remove a column from the 't_school' table, we will execute the
following query to see the table structure:
We have executed the 'ALTER command' on the table t_school followed the DROP COLUMN
keyword with the column 'Board_of_Education'. This simply means that the existing column
named 'Board_of_Education' will be removed from the 't_school' table.
Now, we will again apply the DESC command on the t_school table.
This verifies that the column 'Board_of_Education' has successfully removed from the t_school
table.
Example 3:
Write a query to rename the column Number_of_Students to 'Count_Students' using the alter
command from the t_school table.
Before executing a query to rename a column from the 't_school' table, we will execute the
following query to see the table structure:
We have executed the 'ALTER command' on the table t_school followed by the RENAME
COLUMN keyword. Here, Number_of_Students is the old column name and the column name
specified after the TO keyword, i.e., Count_Students is the new column name. This simply
means that the existing column named 'Number_of_Students' will be replaced by
'Count_Students' from the 't_school' table.
Now, we will again apply the DESC command on the t_school table.
Example 4:
Write a query to change the datatype of 'Number_of_Students' and set the new datatype as
'VARCHAR' with size '20' in the t_school table.
Before executing a query to modify the column datatype and size in the 't_school' table, we will
execute the following query to see the table structure:
We have executed the 'ALTER command' on the table t_school followed by the MODIFY
keyword. Here, ID is the column name, and VARCHAR is the new datatype of the ID column
followed by the size, i.e., 20.
Now, we will again apply the DESC command on the t_school table.
3. DROP
DROP command is used to remove or delete the table's records and the table's structure
from the database.
Syntax:
1. DROP TABLE table_name;
Example:
Write a query to delete the t_school table from the SCHOOL database.
Query:
We will execute the following command to verify that the table 't_school' exists or not.
The above command results verify that the 't_school' table is successfully removed from the
'SCHOOL' database.
4. TRUNCATE
A TRUNCATE command is used to delete the table's records, but the table's structure will
remain unaffected in the database.
Syntax:
Example:
Write a query to remove all the records from the 't_school' table.
Before executing a query to remove the records from the 't_school' table, we will execute the
SELECT query to see records present in the table:
Here, we have executed the 'TRUNCATE command' on the table t_school. This simply means
that all the records from the 't_school' table will be removed, keeping the table structure as it is in
the database.
Now, we will again apply the SELECT query on the t_school table.
5. RENAME
Example:
We will execute the SHOW TABLES command before executing a query to rename the
't_school' table.
1. mysql>SHOW TABLES;
We have executed the 'RENAME command' on the table t_school followed by the 'TO' keyword
with the new table name. This simply means that the 't_school' table will now be renamed to
tbl_school.
1. mysql>SHOW TABLES;
The results above show that the table t_school is not present in the list. Instead, tbl_school is
present in the list, which means the table is now successfully renamed as tbl_school.
(B) DML
DML stands for Data Manipulation Language. Using DML commands in SQL, we can
make changes in the data present in tables.
Whenever we wish to manipulate the data or fetch the data present in SQL tables, we can
use DML commands in SQL.
DML commands in SQL will change the data, such as inserting new records, deleting
or updating existing records from the SQL tables. We can also retrieve all the data
from SQL tables according to our requirements.
Commands covered under DDL are:
1. INSERT
2. SELECT
3. UPDATE
4. DELETE
Let us see each of the commands in the DML category with more details.
1. INSERT
INSERT command is used to insert records in a table. We can insert a single as well as multiple
records for a single table at the same time.
Syntax:
Example:
Query:
Since we wanted to insert ten records in a table, so instead of writing the INSERT command ten
times, we have written a single INSERT command to insert multiple records at a time.
2. SELECT
A SELECT command is used to retrieve the records from the table. According to our
requirements, we can retrieve all the records or some specific records from the table. Whenever
we want to retrieve some specific records from the table, then we have to specify the WHERE
clause in a SELECT query. WHERE clause will contain a condition, any record that matches the
condition will be considered as a part of the output.
Example 1:
Write a query to retrieve all the column values from all the records of the t_school table.
Query:
Here, we have executed a SELECT query with the asterisk (*) on the t_school table. This will
retrieve all the column values for all the records from the t_school table.
Output:
All the records are retrieved successfully from the t_school table.
Example 2:
Write a query to retrieve all the column values of only those schools which has more than 11
classrooms.
Query:
We have executed a SELECT query with the asterisk (*) on the t_school table followed by a
WHERE clause condition. Due to the WHERE clause condition, only those records with a value
greater than 11 in the 'Number_of_classrooms' column will only be retrieved.
Output:
I School_Na Number_Of_Stu Number_Of_Tea Number_Of_Classr
EmailID
D me dents chers ooms
Boys Town
[email protected]
1 Public 1000 80 12
m
School
Guru
Govind
[email protected]
2 Singh 800 35 15
m
Public
School
Ashoka
[email protected]
4 Universal 1110 40 40
m
School
Calibers
English
5 9000 31 50 [email protected]
Medium
School
Cantonmen
t Board
6 7050 41 60 [email protected]
High
School
Podar
podaris89@gmail
7 Internation 12000 120 120
.com
al School
Barnes barnes99@gmail.
8 18000 100 100
School com
D.S
Kothari
9 10000 120 125 [email protected]
Kanya
School
Orchid
1
Internation 20000 200 180 [email protected]
0
al School
There are nine schools in the t_school table, which has more than 11 classrooms.
3. UPDATE
UPDATE command works for the values present in the table. Whenever we wish to update a
value for any record present in a table, we will use the UPDATE command in SQL.
Syntax:
Example:
Write a query to update a record with ID 9 and set the updated value of the Number_of_Teachers
and Number_of_Classrooms as 125 and 9, respectively.
Query:
We will execute the SELECT query to verify whether the number of teachers and classrooms is
updated for the record with ID as 9.
4. DELETE
Syntax:
Example:
Query:
We will execute the SELECT query to verify whether the record with ID 6 is deleted or not.
The results show that the record with ID 6 is deleted successfully from the t_school table.
(C) DCL
DCL stands for Data Control Language.
Whenever we want to control the access to the data present in SQL tables, we will use
DCL commands in SQL. Only the authorized users can access the data stored in the
tables.
Every user will have some pre-defined privileges; accordingly, the data can be accessed
by that particular user. Using the DCL commands in SQL, we can give privileges to the
user on the SQL database and tables, or we can also revoke the given privileges from the
user.
Commands covered under DCL are:
1. GRANT
Access privileges can be assigned to a user for the databases and tables using the GRANT
command.
2. REVOKE
All the access privileges which are already assigned to the user can be revoked by using the
REVOKE command.
(D) TCL:
TCL stands for Transaction Control Language. TCL commands are generally used in
transactions.
Using TCL commands in SQL, we can save our transactions to the database and roll them
back to a specific point in our transaction. We can also save a particular portion of our
transaction using the SAVEPOINT command.
Commands covered under TCL are:
1. COMMIT:
To save all the operations executed in a particular transaction, we need to execute a commit
command just after the transaction completion.
2. ROLLBACK
Using the rollback command in SQL, you can roll to the last saved state of a transaction.
3. SAVEPOINT
Using the SAVEPOINT command, you can assign a name to a specific part of the transaction.
Example:
Till this point, we have started a transaction, inserted records into it, committed the transaction
and also created a SAVEPOINT ins after insertion.
We have deleted a record and created a savepoint del after deletion, but later we thought that we
needed the record we had recently deleted. So, we will roll back to the SAVEPOINT ins.
After rolling back to ins, we can see that all the records are retrieved (including the deleted
record).
SET Operators in SQL
SET operators are special type of operators which are used to combine the result of two
queries.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
There are certain rules which must be followed to perform operations using SET operators
in SQL. Rules are as follows:
Let us see each of the SET operators in more detail with the help of examples.
Table 1: t_employees
Table 2: t2_employees
Table 3: t_students
1. UNION:
Duplicate rows will be eliminated from the results obtained after performing the
UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_employees table.
Since we have performed union operation between both the tables, so only the records
from the first and second table are displayed except for the duplicate records.
Example 2:
Write a query to perform union between the table t_students and the table t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_students table.
2. UNION ALL
This operator combines all the records from both the queries.
Duplicate rows will be not be eliminated from the results obtained after performing
the UNION ALL operation.
Example 1:
Write a query to perform union all operation between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform UNION ALL operation with the
records fetched by the second SELECT query from the t2_employees table.
Since we have performed union all operation between both the tables, so all the records
from the first and second table are displayed, including the duplicate records.
Example 2:
Write a query to perform union all operation between the table t_students and the table
t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform UNION ALL operation with the
records fetched by the second SELECT query from the t2_students table.
Since we have performed union all operation between both the tables, so all the records
from the first and second table are displayed, including the duplicate records.
3. INTERSECT:
It is used to combine two SELECT statements, but it only returns the records which
are common from both SELECT statements.
Example 1:
Write a query to perform intersect operation between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform INTERSECT operation with the
records fetched by the second SELECT query from the t2_employees table.
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
Example 2:
Write a query to perform intersect operation between the table t_students and the table
t2_students.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_students table and perform a UNION operation with the
records fetched by the second SELECT query from the t2_students table.
Since we have performed intersect operation between both the tables, so only the
common records from both the tables are displayed.
4. MINUS
It displays the rows which are present in the first query but absent in the second
query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees and the table
t2_employees.
Query:
Here, in a single query, we have written two SELECT queries. The first SELECT query will
fetch the records from the t_employees table and perform MINUS operation with the
records fetched by the second SELECT query from the t2_employees table.
Since we have performed Minus operation between both the tables, so only the unmatched
records from both the tables are displayed.
Example 2:
Write a query to perform a minus operation between the table t_students and the table
t2_students.
Query:
Since we have performed a minus operation between both the tables, so only the
Unmatched records from both the tables are displayed.
Aggregate Functions
An aggregate function performs a calculation on a set of values, and returns a
single value. Except for COUNT(*), aggregate functions ignore null values.
Aggregate functions are often used with the GROUP BY clause of the SELECT
statement.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax
COUNT(*)
or
COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10
Item2 Com2 3 25
Item3 Com1 2 30
Item4 Com3 5 10
Item5 Com2 2 20
Item6 Cpm1 3 25
Item7 Com1 5 30
Item8 Com1 3 10
Item9 Com2 2 25
Item10 Com3 4 30
Example: COUNT()
SELECT COUNT(*)
FROM PRODUCT_MAST;
Output:
10
SELECT COUNT(*)
FROM PRODUCT_MAST;
WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
SUM Function
Sum function is used to calculate the sum of all selected columns. It works on
numeric fields only.
Syntax
SUM()
or
SUM( [ALL|DISTINCT] expression )
Example: SUM()
SELECT SUM(COST)
FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3;
Output:
320
SELECT SUM(COST)
FROM PRODUCT_MAST
WHERE QTY>3
GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
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
AVG()
or
AVG( [ALL|DISTINCT] expression )
Example:
SELECT AVG(COST)
FROM PRODUCT_MAST;
Output:
67.00
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
MAX()
or
MAX( [ALL|DISTINCT] expression )
Example:
SELECT MAX(RATE)
FROM PRODUCT_MAST;
Output
30
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
MIN()
or
MIN( [ALL|DISTINCT] expression )
Example:
SELECT MIN(RATE)
FROM PRODUCT_MAST;
Output:
10
Nested Queries in SQL
Structured Query Language (SQL) is a programming language. SQL is used to manage data
stored in a relational database. SQL has the ability to nest queries. A nested query is a
query within another query. A nested query allows for more complex and specific data
retrieval. In this article, we will discuss nested queries in SQL, their syntax, and examples.
Nested Query
In SQL, a nested query involves a query that is placed within another query. The output of
the inner query is used by the outer query. A nested query has two SELECT statements: one
for the inner query and another for the outer query.
The basic syntax of a nested query involves placing one query inside of another query. The
inner query or subquery is executed first and returns a set of values that are then used by
the outer query. The syntax for a nested query is as follows:
FROM table1
FROM table2
WHERE condition );
Correlated subqueries are executed once for each row of the outer query. They use values
from the outer query to return results.
In independent nested queries, the execution order is from the innermost query to the
outer query. An outer query won't be executed until its inner query completes its execution.
The outer query uses the result of the inner query.
IN Operator
The IN Operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.
NOT IN Operator
The NOT IN Operator checks if a column value in the outer query's result is not present in
the inner query's result. The final result will have rows that satisfy the NOT IN condition.
ALL Operator
The ALL Operator compares a value of the outer query's result with all the values of the
inner query's result and returns the row if it matches all the values.
ANY Operator
The ANY Operator compares a value of the outer query's result with all the inner query's
result values and returns the row if there is a match with any value.
Inner query uses the value of the selected row. It executes its query and returns a
result set.
Outer query uses the result set returned by the inner query. It determines whether
the selected row should be included in the final output.
Steps 2 and 3 are repeated for each row in the outer query's result set.
EXISTS Operator
The EXISTS Operator checks whether a subquery returns any row. If it returns at least one
row. EXISTS operator returns true, and the outer query continues to execute. If the subquery
returns no row, the EXISTS operator returns false, and the outer query stops execution.
The NOT EXISTS Operator checks whether a subquery returns no rows. If the subquery
returns no row, the NOT EXISTS operator returns true, and the outer query continues to
execute. If the subquery returns at least one row, the NOT EXISTS operator returns false,
and the outer query stops execution.
ANY Operator
The ANY Operator compares a value of the outer query's result with one or more values
returned by the inner query. If the comparison is true for any one of the values returned by
the inner query, the row is included in the final result.
ALL Operator
The ALL Operator compares a value of the outer query's result with all the values returned
by the inner query. Only if the comparison is true for all the values returned by the inner
query, the row is included in the final result.
These operators are used to create co-related nested queries that depend on values from
the outer query for execution.
Examples
1 John 1
2 Mary 2
3 Bob 1
4 Alice 3
5 Tom 1
dept_id dept_name
1 Sales
2 Marketing
3 Finance
1 1 1000
2 2 2000
3 3 3000
4 1 4000
5 5 5000
6 3 6000
7 2 7000
Required query
SELECT emp_name
FROM employees
FROM departments
emp_name
John
Bob
Tom
Example 2: Find the names of all employees who have made a sale
Required query
SELECT emp_name
FROM employees
FROM sales
Output
emp_name
John
Mary
Bob
Alice
Tom
This query selects all employees from the "employees" table where there exists a sale
record in the "sales" table for that employee.
Example 3: Find the names of all employees who have made sales greater than $1000.
Required query
SELECT emp_name
FROM employees
FROM sales
emp_name
John
Mary
Bob
Alice
Tom
This query selects all employees from the "employees" table. With the condition that where
their emp_id equals all the emp_ids in the "sales" table where the sale amount is greater
than $1000. Since all employees have made a sale greater than $1000, all employee names
are returned.
Enhances flexibility: By enabling the use of results from one query within another,
nested queries allow dynamic filtering and indirect joins, which can simplify query
logic.
Improves readability: When properly written, nested queries can make complex
operations more intuitive by encapsulating logic within inner queries.
The IN operator is used to filter rows based on a set of values returned by a subquery. It is
commonly used to match a column value against a list or result set. This operator simplifies
queries by avoiding the need for multiple OR conditions.
This query filters the students enrolled in the specified courses by chaining multiple nested
queries.
SELECT S_NAME FROM STUDENT
WHERE S_ID IN (
SELECT S_ID FROM STUDENT_COURSE
WHERE C_ID IN (
SELECT C_ID FROM COURSE WHERE C_NAME IN ('DSA', 'DBMS')
)
);
2. NOT IN Operator
The NOT IN operator excludes rows based on a set of values from a subquery. It is
particularly useful for filtering out unwanted results. This operator helps identify records that
do not match the conditions defined in the subquery.
This query excludes students who are enrolled in the courses ‘DSA’ or ‘DBMS’.
Output
S_ID
S3
EXISTS
The EXISTS operator checks for the existence of rows in a subquery. It returns true if the
subquery produces any rows, making it efficient for conditional checks. This operator is
often used to test for relationships between tables.
The inner query checks for matching records in the STUDENT_COURSE table, and the
outer query returns the corresponding student names.
The ANY operator compares a value with any value returned by the subquery, while ALL
ensures comparison with all values.
SQL views are particularly useful for managing complex queries, enhancing security, and
presenting data in a simplified format. In this guide, we will cover the SQL create view
statement, updating and deleting views, and using the WITH CHECK OPTION clause.
A view in SQL is a saved SQL query that acts as a virtual table. It can fetch data from one or
more tables and present it in a customized format, allowing developers to:
Simplify Complex Queries: Encapsulate complex joins and conditions into a single
object.
Present Data Flexibly: Provide tailored data views for di erent users.
StudentDetails
NAME VARCHAR(255),
ADDRESS VARCHAR(255)
);
VALUES
StudentMarks
NAME VARCHAR(255),
Marks INT,
Age INT
);
VALUES
We can create a view using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
FROM table_name
WHERE condition;
Parameters:
Let’s look at some examples of CREATE VIEW Statement in SQL to get a better
understanding of how to create views in SQL.
In this example, we will create a View named DetailsView from the table StudentDetails.
Query:
FROM StudentDetails
To see the data in the View, we can query the view in the same manner as we query a table.
SELECT * FROM DetailsView;
Output:
In this example, we will create a view named StudentNames from the table StudentDetails.
Query:
FROM StudentDetails
ORDER BY NAME;
Output:
In this example we will create a View named MarksView from two tables StudentDetails
and StudentMarks. To create a View from multiple tables we can simply include multiple
tables in the SELECT statement. Query:
Output:
We can list View using the SHOW FULL TABLES statement or using the
information_schema table. A View can be created from a single table or multiple tables.
Syntax:
USE "database_name";
Using information_schema
SELECT table_name
FROM information_schema.views
OR
FROM information_schema.views
Syntax:
Example
If you want to update the existing data within the view, use the UPDATE statement.
Syntax:
UPDATE view_name
WHERE [condition];
Note: Not all views can be updated using the UPDATE statement.
If you want to update the view definition without a ecting the data, use the CREATE OR
REPLACE VIEW statement. you can use this syntax
FROM table_name
WHERE condition;
Certain conditions need to be satisfied to update a view. If any of these conditions are not
met, the view can not be updated.
1. The SELECT statement which is used to create the view should not include GROUP
BY clause or ORDER BY clause.
5. The view should be created from a single table. If the view is created using multiple
tables then we will not be allowed to update the view.
Examples
Let’s look at di erent use cases for updating a view in SQL. We will cover these use cases
with examples to get a better understanding.
We can use the CREATE OR REPLACE VIEW statement to add or replace fields from a
view.
If we want to update the view MarksView and add the field AGE to this View from
StudentMarks Table, we can do this by:
Output:
We can insert a row in a View in the same way as we do in a table. We can use the INSERT
INTO statement of SQL to insert a row in a View.
In the below example, we will insert a new row in the View DetailsView which we have
created above in the example of “creating views from a single table”.
Output:
Deleting rows from a view is also as simple as deleting rows from a table. We can use the
DELETE statement of SQL to delete rows from a view. Also deleting a row from a view first
deletes the row from the actual table and the change is then reflected in the view.
In this example, we will delete the last row from the view DetailsView which we just added
in the above example of inserting rows.
WHERE NAME="Suresh";
Output:
WITH CHECK OPTION Clause
The WITH CHECK OPTION clause in SQL is a very useful clause for views. It applies to an
updatable view.
The WITH CHECK OPTION clause is used to prevent data modification (using INSERT or
UPDATE) if the condition in the WHERE clause in the CREATE VIEW statement is not
satisfied.
If we have used the WITH CHECK OPTION clause in the CREATE VIEW statement, and if the
UPDATE or INSERT clause does not satisfy the conditions then they will return an error.
In the below example, we are creating a View SampleView from the StudentDetails Table
with a WITH CHECK OPTION clause.
FROM StudentDetails
In this view, if we now try to insert a new row with a null value in the NAME column then it
will give an error because the view is created with the condition for the NAME column as
NOT NULL. For example, though the View is updatable then also the below query for this
View is not valid:
VALUES(6);
Uses of a View
2. Hiding data complexity – A view can hide the complexity that exists in multiple
joined tables.
3. Simplify commands for the user – Views allow the user to select information from
multiple tables without requiring the users to actually know how to perform a join.
5. Rename Columns – Views can also be used to rename the columns without
a ecting the base tables provided the number of columns in view must match the
number of columns specified in a select statement. Thus, renaming helps to hide
the names of the columns of the base tables.
6. Multiple view facility – Di erent views can be created on the same table for
di erent users.
1
PL/SQL:
Syntax:
Declare
Variable declaration
Begin
Process statements
Or execution statement
[Exception
Exception statement]
End;
A PL/SQL block can be divided into four sections. They are
1. Declaration section
2. Begin section
3. Exception section
4. End section
1. Declaration Section:
Code blocks start with a declaration section
In this block memory variable and other oracle objects can be declared
2
2. Begin Section:
It consists of a set of SQL and PL/SQL statements
It describes process that has to be applied to table data.
Actual data manipulation, retrieval, looping and branching constructs arespecified in this
section.
3. Exception Section:
This section deals with handling of errors
That arise during execution of the data manipulation statements
The errors can arise due to syntax and logic.
4. End Section:
a. This makes the end of a PL/SQL block.
Example:
Declare
a number(4);
b number(4);
c number(4);
begin
b:=20;
c:=a+b;
dbms_output.put_line(c);
end;
1. dbms_ouput: it is a package.
2. That includes a number of procedures and functions that accumulate informationin a buffer so
that it can be retrieved later.
3. These functions can also be used to display message.
4. put_line: put a piece of information in the package buffer followed by an end-of-line marker.
5. dbms_ouput.put_line(‘Hello’);
3
1. Character Set
1. A PL/SQL program consists of text having specific set of characters.
2. Character set may include the following characters:
a. Alphabets, both in upper case [A–Z] and lower case [a–z]
b. Numeric digits [0–9]
c. Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ %
d. Blank spaces, tabs, and carriage returns.
2. Lexical Units
1. A line of PL/SQL program contains groups of characters known as lexical units,which can be
classified as follows:
A. Delimiters
B. Identifiers
C. Literals
D. Comments
A. Delimiters
a. A delimiter is a simple or compound symbol
b. That has a special meaning to PL/SQL.
c. Simple symbol consists of one character
d. Compound symbol consists of more than one character.
B. Identifiers
a. Identifiers are used in the PL/SQL programs
4
C. Literals
a. A literal is an explicitly defined character, string, numeric, or Booleanvalue,
D. Comments
1. Comments are used in the PL/SQL program
2. It used to improve the readability and understandability of a program.
3. A comment can appear anywhere in the program code.
4. The compiler ignores comments.
5. Generally, comments are used to describe the purpose and use of eachcode segment.
Ex: /* Hello World! This is an example of multiline comments in PL/SQL */
Q) Introduction to PL/SQL data types
Each value in PL/SQL such as a constant, variable and parameter has a data type that determines the
storage format, valid values, and allowed operations.
PL/SQL has two kinds of data types: scalar and composite. The scalar types are types that store single
values such as number, Boolean, character, and datetime whereas the composite types are types that
store multiple values, for example, record and collection.
This tutorial explains the scalar data types that store values with no internal components.
Number
Boolean
Character
Datetime
A scalar data type may have subtypes. A subtype is a data type that is a subset of another data type,
which is its base type. A subtype further defines a base type by restricting the value or size of the base
data type.
5
The numeric data types represent real numbers, integers, and floating-point numbers. They are stored
as NUMBER, IEEE floating-point storage types (BINARY_FLOAT and BINARY_DOUBLE),
and PLS_INTEGER.
The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean values are
typically used in control flow structure such as IF-THEN, CASE, and loop statements like LOOP, FOR
LOOP, and WHILE LOOP.
SQL does not have the BOOLEAN data type, therefore, you cannot:
The character data types represent alphanumeric text. PL/SQL uses the SQL character data types such
as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID, and UROWID.
The date time data types represent dates, timestamp with or without time zone and intervals.
PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME
ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH,
and INTERVAL DAY TO SECOND.
Operator Description
** Exponentiation
*, / Multiplication, division
AND Conjunction
OR Inclusion
Conditional control
1. Conditional control, which run different statements for different data values.
2. It check the condition for single time only even it is true or false
7
Syntax:
if(condition) then
Statement 1;
… ................ Statement n;
End if;
Example:
DECLARE
a number:=&a;
BEGIN
if(a<10)then
dbms_output.put_line(‘welcome to pl/sql’);
end if;
END;
Syntax:
if(condition) then
Statement 1;
else
end if;
statement 2;
8
Example:
declare
a integer;
b integer; begin
a:=&a; /* it take run time values*/
b:=&b; /* it take run time values*/
if(a>b) then
dbms_output.put_line(‘A is big’);
else
dbms_output.put_line(‘b is big’);
end if;
end;
Syntax:
if(condition) then
Statement 1;
elsif(condition) then
statement 2;
else
statement 3;
end if;
Example:
declare
a integer; b integer;
c integer;
begin
a:=&a;
b:=&b;
c:=&c;
9
Nested if statement
Inner if is called nested if. if condition is false it execute stamen 3. Other wise it is true its check for
another condition if it is true it execute statement 1 other wise execute statement 2.
Syntax:
if(condition) then
if(condition) then
statement 1;
else
statement 2;
end if;else
statement 3;
end if;
Case:
Syntax
case variable_name
When value1 then stmt; When value2 then stmt;
… ............... Else stmt;
End case;
1. The case statement runs the first statements for which value equals variablename remaining
conditions are not evaluated.
2. If no value equals to variable name, the case statements runs else statements.
10
Ex:
Declare
Grade char:=’&grade’;
Begin
case grade
when ‘A’ then
dbms_output.put_line(‘Excellent’);
when ‘B’ then
dbms_output.put_line(‘Very good’);
when ‘C’ then
dbms_output.put_line(‘Good’);
when ‘D’ then
dbms_output.put_line(‘Fair’);
when ‘F’ then
dbms_output.put_line(‘poor’);
else
dbms_output.put_line(‘no such grade’);
end case;
end;
The PL/SQL loops are used to repeat the execution of one or more statements for specified number of
times. These are also known as iterative control statements.
LOOP
Sequence of statements;
END LOOP;
11
PL/SQL exit loop is used when a set of statements is to be executed at least once before the termination
of the loop. There must be an EXIT condition specified in the loop, otherwise the loop will get into an
infinite number of iterations. After the occurrence of EXIT condition, the process exits the loop.
LOOP
Sequence of statements;
END LOOP;
LOOP
statements;
EXIT;
{or EXIT WHEN condition;} END LOOP;
Example :
DECLARE
i NUMBER := 1;
BEGIN
LOOP
EXIT WHEN i>10;
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
PL/SQL while loop is used when a set of statements has to be executed as long as a condition is true, the
While loop is used. The condition is decided at the beginning of each iteration and continues until the
condition becomes false.
WHILE <condition>
LOOP statements;
END LOOP;
DECLARE
i INTEGER := 1;
BEGIN
13
PL/SQL for loop is used when when you want to execute a set of statements for a predetermined number
of times. The loop is iterated between the start and end integer values. The counter is always incremented
by 1 and once the counter reaches the value of end integer, the loop ends.
o You don't need to declare the counter variable explicitly because it is declared implicitly in the
declaration section.
o The counter variable is incremented by 1 and does not need to be incremented explicitly.
o You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done often.
Q) PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or more
specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or variables passed to
the procedure.
o Body: The body contains a declaration section, execution section and exception section similar to
a general PL/SQL block.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
Where,
Example :
The following example creates a simple procedure that displays the string 'Hello World!' on the screen
when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
Executing a Standalone Procedure
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
Hello World
PL/SQL procedure successfully completed.
BEGIN
greetings;
END;
/
The above call will display − Hello World . PL/SQL procedure successfully completed.
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a
procedure is −
16
You can drop the greetings procedure by using the following statement −
Q) PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between procedure and
a function is, a function must always return a value, and on the other hand a procedure may or may not
return a value. Except this, all the other things of PL/SQL procedure are true for PL/SQL function too.
Here:
EXAMPLE :
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
/
Calling PL/SQL Function:While creating a function, you have to give a definition of what the function
has to do. To use a function, you will have to call that function to perform the defined task. Once the
function is called, the program control is transferred to the called function.
After the successful completion of the defined task, the call function returns program control back to the
main program.
To call a function you have to pass the required parameters along with function name and if function
returns a value then you can store returned value
Example
Create Function:
RETURN total;
END;
/
After the execution of above code, you will get the following result.
Function created.
Calling function code:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
PL/SQL Drop Function
If you want to remove your created function from the database, you should use the following syntax.
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers
are, in fact, written to be executed in response to any of the following events −
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions
Creating a trigger:
Here,
o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with
the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
20
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various
DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each
row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
Type of Triggers
1. BEFORE Trigger: BEFORE trigger execute before the triggering DML statement (INSERT,
UPDATE, DELETE) execute. Triggering SQL statement is may or may not execute, depending
on the BEFORE trigger conditions block.
2. AFTER Trigger: AFTER trigger execute after the triggering DML statement (INSERT,
UPDATE, DELETE) executed. Triggering SQL statement is execute as soon as followed by the
code of trigger before performing Database operation.
3. ROW Trigger: ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table. If row deleting is define as trigger event, when
trigger file, deletes the five rows each times from the table.
4. Statement Trigger: Statement trigger fire only once for each statement. If row deleting is define
as trigger event, when trigger file, deletes the five rows at once from the table.
5. Combination Trigger: Combination trigger are combination of two trigger type,
1. Before Statement Trigger: Trigger fire only once for each statement before the
triggering DML statement.
2. Before Row Trigger : Trigger fire for each and every record before the triggering DML
statement.
3. After Statement Trigger: Trigger fire only once for each statement after the triggering
DML statement executing.
4. After Row Trigger: Trigger fire for each and every record after the triggering DML
statement executing.
DBMS
(DATABASE MANAGEMENT SYSTEM)
II Year ,IV Sem
Integrity Constraints
•Integrity constraints are a set of rules.
•Condition that is satisfied.
•It is used to maintain the quality of information.
• Integrity constraints ensure that the changes ,data
insertion, updating, and other processes have to be
performed in such a way that data integrity is not
affected.
•Thus, integrity constraint is used to guard against
accidental damage to the database.
•It is the rules that database is not permitted to
violate.
Integrity Constraints..
•Integrity constraints used to ensure accuracy and
consistency of the data in a relational database,
•Constraints may apply to each attribute or they
may apply to the relationship between
tables(foreign key).
•Here changes made to the database by authorized
users donot result in a loss of data consistency.
•Example :- Blood Group:- A,B,AB,O not C D E
1. Domain constraints
•Domain constraints can be defined as the definition of a valid set of
values for an attribute.
•It defines domain only.
•The data type of domain includes string, character, integer, time,
date, currency, etc. The value of the attribute must be available in
the corresponding domain. Example is phone number has only 10
digits.
Example:-
2. Entity integrity constraints
Example:-
3. Referential Integrity Constraints
X → Y
The left side of FD is known as a determinant, the right
side of the production is known as a dependent.
For example:
Assume we have an employee table with attributes:
Emp_Id, Emp_Name, Emp_Address.
Functional Dependency…
Example:
X = {a, b, c, d, e}
Y = {a, b, c}
2. Augmentation Rule (IR2)
The augmentation is also called as a partial dependency. In
augmentation, if X determines Y, then XZ determines YZ for
any Z.
If X → Y then XZ → YZ
Example:
For R(ABCD), if A → B then AC → BC
3. Transitive Rule (IR3)
In the transitive rule, if X determines Y and Y determine Z,
then X must also determine Z.
If X → Y and Y → Z then X → Z
4. Union Rule (IR4)
Union rule says, if X determines Y and X determines Z, then
X must also determine Y and Z.
If X → Y and X → Z then X → YZ
Proof:
1. X → Y (given)
2. X → Z (given)
3. X → XY (using IR2 on 1 by augmentation with X. Where
XX = X)
4. XY → YZ (using IR2 on 2 by augmentation with Y)
5. X → YZ (using IR3 on 3 and 4)
5. Decomposition Rule (IR5)
Decomposition rule is also known as project rule. It is the
reverse of union rule.
This Rule says, if X determines Y and Z, then X determines Y
and X determines Z separately.
If X → YZ then X → Y and X → Z
Proof:
1. X → YZ (given)
2. YZ → Y (using IR1 Rule)
3. X → Y (using IR3 on 1 and 2)
6. Pseudo transitive Rule (IR 6)
In Pseudo transitive Rule, if X determines Y and YZ
determines W, then XZ determines W.
If X → Y and YZ → W then XZ → W
Proof:
1. X → Y (given)
2. WY → Z (given)
3. WX → WY (using IR2 on 1 by augmenting with W)
4. WX → Z (using IR3 on 3 and 2)
Normalization
❖Normalization is the process of organizing the data in the
database.
❖Normalization is used to minimize the redundancy from a
relation or set of relations.
❖It is also used to eliminate the undesirable characteristics
like Insertion, Update and Deletion Anomalies.
❖Normalization divides the larger table into the smaller
table and links them using relationship.
❖The normal form is used to reduce redundancy from the
database table.
Normalization
➢ This is the process which allows you to winnow out
redundant data within your database.
➢ This involves restructuring the tables to successively
meeting higher forms of Normalization.
➢ A properly normalized database should have the
following characteristics
1. Scalar values in each fields
2. Absence of redundancy.
3. Minimal use of null values.
4. Minimal loss of information.
Levels of Normalization
Levels of normalization based on the amount of
redundancy in the database.
Various levels of normalization are:
1. First Normal Form (1NF)
2. Second Normal Form (2NF)
Redundancy
Number of Tables
3. Third Normal Form (3NF)
Complexity
4. Boyce-Codd Normal Form (BCNF)
5. Fourth Normal Form (4NF)
6. Fifth Normal Form (5NF)
Most databases should be 3NF or BCNF in order to avoid the database anomalies.
Levels of Normalization
1NF
2NF
3NF
4NF
5NF
0-55-123456-9 Main Street Small House 714-000-0000 $22.95 0-55-123456-9 Jones 123-333-3333
Example 1
Example 3
6 Joyce 666-666-6666
7 Roman 444-444-4444
Second Normal Form (2NF)
For a table to be in 2NF, there are two requirements
➢ The database is in first normal form
➢ All non-key attributes in the table must be functionally
dependent on the entire primary key
➢ The table should not contain any partial dependency.
Note: Remember that we are dealing with non-key attributes
In Database Management Systems (DBMS), Stored Procedures and Triggers are two
powerful and distinct database objects used to encapsulate and automate SQL code,
but they serve different purposes and are invoked differently.
Stored Procedures
A stored procedure is a pre-compiled set of one or more SQL statements (and often
includes procedural logic like IF-THEN-ELSE, loops, etc.) that is stored in the
database. It can be executed as a single unit, performing a specific task or a series of
tasks.
Triggers
A trigger is a special type of stored procedure that automatically executes (or "fires")
in response to specific events occurring in the database. These events are typically
Data Manipulation Language (DML) operations (INSERT, UPDATE, DELETE) on a table
or view.
Both stored procedures and triggers are vital components of a robust DBMS, offering
ways to improve performance, security, and data integrity by centralizing and
automating database logic. The choice between using a stored procedure or a trigger
depends on the specific requirements and how the logic needs to be invoked.
Join Dependency