Database Lab Manual
Database Lab Manual
Sub.Code : CB3412
Sub.Name : Database management system and security Lab
Regulation : R2021
1
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
SYLLABUS
COURSE OBJECTIVES :
To learn and implement important commands in SQL.
To learn the usage of nested and joint queries.
To understand functions, procedures and procedural extensions of databases.
To understand attacks on databases and to learn to defend against the
attacks on databases.
To learn to store and retrieve encrypted data in databases
EXPERIMENTS
1. Create a database table, add constraints (primary key, unique, check, Not
null), insert rows, update and delete rows using SQL DDL and DML
commands.
2. Create set of tables, add foreign key constraints and incorporate referential integrity.
3. Query the database tables using different ‘where’ clause conditions and also
implement aggregate functions.
4. Query the database tables and explore sub queries and simple join operations.
5. Query the database tables and explore natural, equi and outer joins.
6. Write user defined functions and stored procedures in SQL.
7. Execute complex transactions and realize DCL and TCL commands.
8. Write SQL Triggers for insert, delete, and update operations in database table.
9. Use SQLi to authenticate as administrator, to get unauthorized access over
sensitive data, to inject malicious statements into form field.
10.Write programs that will defend against the SQLi attacks given in the previous exercise.
11.Write queries to insert encrypted data into the database and to retrieve the
data using decryption.
TOTAL: 60 Periods
CONTENT BEYOND SYLLABI: Simulate SQL injection and implement mitigation techniques.
COURSE OUTCOMES:
2
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
SOFTWARE REQUIREMENT:
SQL Map
JSQL Injection or equivalent
HARDWARE REQUIREMENT:
Oracle Database 12 or higher
MySQL 5.7 or higher
SQL Server 2022(16.x)
PostgresQL
LIST OF EXPERIMENTS
Sl.
List of Experiments Page No
No
Create a database table, add constraints (primary key, unique, check, Not
1. null), insert rows, update and delete rows using SQL DDL and DML 3-7
commands.
Create set of tables, add foreign key constraints and incorporate 14-15
2. referential integrity.
Query the database tables using different ‘where’ clause conditions and 16-20
3.
also implement aggregate functions
Query the database tables and explore sub queries and simple join 21-31
4.
operations
5. Query the database tables and explore natural, equi and outer joins. 32-34
7. Execute complex transactions and realize DCL and TCL commands 37-42
Write SQL Triggers for insert, delete, and update operations in database 43-46
8.
table.
Use SQLi to authenticate as administrator, to get unauthorized access over 47-54
9.
sensitive data, to inject malicious statements into form field.
10. Write programs that will defend against the SQLi attacks 55-56
Write queries to insert encrypted data into the database and to retrieve the 57-58
11.
data using decryption.
3
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex. No: 1 a Create a database table, add constraints (primary key, unique, check, not
null), insert rows, update and delete rows using SQL DDL and DML commands.
AIM:
To study and execute the DDL Commands in DBMS PROCEDURE:
Definition and Syntax SQL:
SQL Stands Structured Query Language. SQL composed of commands that enable users to
create database and table structures perform various type of data manipulation and data
administration and query the database to extract useful information.
Data Definition Language (DDL)
The Language used to define the database schema is called data definition language. DDL
is to create, update and drop the database. The commands used for DDL are
CREATE ALTER RENAME TRUNCATE DROP
SQL: create command
Create is a DDL SQL command used to create a table or a database in relational database
management system.
Creating a Database
To create a database in RDBMS, create command is used. Following is the syntax,
CREATE DATABASE <DB_NAME>;
Example for creating Database CREATE DATABASE dbms;
The above command will create a database named dbms, which will be an empty schema without
any table.
To create tables in this newly created database, we can again use the create command.
Creating a Table
Create command can also be used to create tables. Now when we create a table, we have to
specify the details of the columns of the tables too. We can specify the names and data types of
various columns in the create command itself.
Following is the syntax,
CREATE TABLE <TABLE_NAME>
( column_name1 datatype1, column_name2 datatype2, column_name3 datatype3,.............
column_namen datatypen );
create table command will tell the database system to create a new table with the given table name
and column information.
SQL: ALTER command
alter command is used for altering the table structure, such as, to add a column to existing table to
rename any existing column to change datatype of any column or to modify its size. to drop a
column from the table.
ALTER Command: Add a new Column
Using ALTER command we can add a column to any existing table. Following is the syntax,
ALTER TABLE table_name ADD( column_name datatype);
4
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
RENAME query
RENAME command is used to set a new name for any existing table. Following is the syntax,
RENAME TABLE old_table_name to new_table_name
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not
destroy the table's structure. When we use TRUNCATE command on a table its (auto- increment)
primary key is also initialized. Following is its syntax,
TRUNCATE TABLE table_name
DROP command
DROP command completely removes a table from the database. This command will also
destroy the table structure and the data stored in it. Following is its syntax,
DROP TABLE table_name
Table Creation
SQL> create table employee(empid number(5),empname varchar2(10),dept varchar2(20)
,dob date,salary number(6));
Table created.
DESCRIBING TABLE:
SQL> desc
employee
Name Null?
Type
5
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
EMPID NUMBER(5)
EMPNAME
VARCHAR2(10) DEPT
VARCHAR2(20)
DOB DATE
SALARY NUMBER(6)
ALTERING A TABLE
ADDING A NEW
CLOUMN:
SQL> alter table employee add date of joining date; Table altered.
Describing a table
SQL> desc
employee; Name
Null? Type
EMPID NUMBER(5)
EMPNAME
VARCHAR2(10) DEPT
VARCHAR2(20)
DOB DATE
SALARY NUMBER(6)
DATEOFJOINING DATE
MODIFY:
SQL> alter table employee modify empname
varchar2(15); Table altered.
SQL> desc
employee; Name
Null? Type
EMPID NUMBER(5)
EMPNAME
VARCHAR2(15) DEPT
VARCHAR2(20)
DOB DATE
SALARY
NUMBER(6)
DATEOFJOINING
DATE DROPING
A CLOUMN:
SQL> alter table employee drop column date of
joining; Table altered.
6
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
EMPID NUMBER(5)
EMPNAME
VARCHAR2(15) DEPT
VARCHAR2(20)
DOB DATE
SALARY NUMBER(6)
TRUNCATE:
SQL> truncate table
employee; Table truncated.
RENAME:
SQL> rename employee to
emp; Table renamed
RESULT:
Thus the table was created successfully and applied all the DDL commands.
Augmented Question:
Create a Database Table with Constraints:
Create a table named Employee with the following columns:
EmpID (integer, primarykey)
EmpName (varchar(50), not null)
Salary (decimal, check constraint for salary greater than 0)
Email (varchar(100), unique constraint)
Date Of Joining (date, not null)
Viva Question:
1. What is the purpose of the PRIMARY KEY constraint?
2. How does the DELETE statement affect rows in a table?
3. What happens when you try to insert a duplicate value in a column that has a UNIQUE constraint?
7
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex no: 1b Create set of tables, add foreign key constraints and incorporate referential
Integrity
AIM:
To add and execute the constraints in create command
PROCEDURE:
To practice basic SQL constraints like NOT NULL, primary key and check constraints.
Constraints:
Constraints are used to limit the type of data, that can go into a table this ensures the
accuracy and reliability of the data in the table.
If there is any violation between the constraints and the data action, the action is aborted.
Primary Key constraints:
A combination of NOT NULL and unique uniquely identifies each row in the data.
Syntax:
Create table tablename(column1 datatype1 primary key, coulmn2 datatype2,…..column datatypen);
Eg:
Create table branches(branched number(10) primary key, branchname varchar2(20));
Unique Constraints
It ensures that all the values in a column are different
Syntax:
Create table tablename(column1 datatype1, column2 datatype2,......columnn datatypen unique);
Eg:
Create table person(id int NOT NULL unique, lastname varchar2(25),firstname varchar2(25) not null,
age int);
Check Constraint
It works for numerical value conditions ensures that the values in a column satisfies a specific condition
Syntax:
Create table tablename(column1 datatype1, column2 datatype, colunmn3 datatype3.....check condition);
Eg:
Create table person(id int NOT NULL,lastname varchar2(25) NOT NULL,Firstname
varchar2(25),age int check(age>=18));
NOT NULL constraints:
It ensures that a column cannot have a null value
8
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Syntax:
Create table tablename(column1 not null,column2 not null,column3 not
null); Eg:
Create table person(id int NOT NULL,lastname varchar2(25) NOT NULL,firstname varchar2(25)
NOT NULL, age int );
9
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
111 pendrive 15
SQL> insert into stock1
values(111,'cd',20); insert into stock1
values(111,'cd',20)
*
ERROR at line 1:
ORA-00001: unique constraint (CSE132.SYS_C0012501) violated
PRIMARY KEY:
SQL> create table stock3(itemno number(5)primary key ,itemname
varchar2(10)); Table created.
SQL> insert into stock3
values('','pendrive'); insert into stock3
values('','pendrive') ERROR at line 1:
ORA-01400: cannot insert NULL into ("CSE132"."STOCK3"."ITEMNO")
SQL> insert into stock3
values('3','cd'); 1 row created.
SQL> insert into stock3
values('3','dvd'); insert into stock3
values('3','dvd') ERROR at line 1:
ORA-00001: unique constraint (CSE132.SYS_C0012551) violated
RESULT:
Thus the SQL constraints like primary key, unique, check and not null constraints are executed
successfully.
10
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Augmented Question:
Explain the concept of foreign key constraints with examples. Create tables for a student
management system where students can enroll in multiple courses. Define the necessary foreign key
relationships to ensure referential integrity, and discuss how ON DELETE CASCADE and ON
UPDATE CASCADE work in maintaining referential integrity.
Viva Question:
1. What is referential integrity, and why is it important in relational databases?
2. Can you explain how foreign key constraints help enforce referential integrity?
11
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex: No: 1c Create a database table, add constraints (primary key, unique, check, Not null), insert
rows, update and delete rows using SQL DML commands.
AIM:
To execute the Data Manipulation Commands
PROCEDURE:
INSERT:
ONETIME INSERTION:
SQL> insert into emp values(1181,'harini','production','16-jun-1999',30000);
1 row created.
SELECT:
SQL> select * from emp;
EMPID EMPNAME DEPT DOB SALARY
13
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
RESULT:
Thus the DML commands are executed successfully
Augmented Question:
Create a table called Employees with the following columns: employee_id (primary key), first_name, last_name, email,
salary, and hire_date. Ensure the following constraints:
employee_id is the primary key.
email is unique.
salary must be greater than 0 (use a CHECK constraint).
first_name and last_name cannot be null (use NOT NULL constraint).
Viva Question:
1. What SQL command would you use to delete a specific employee from the table, and what are the implications of
using this command in terms of data integrity?
2. How would you update an employee's salary using SQL? What would happen if the updated value violates any
constraints like the CHECK constraint?
14
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex: No: 2 Create set of tables, add foreign key constraints and incorporate referential
integrity.
AIM:
To create a set of tables, add foreign key constraints and incorporate referential integrity.
PROCEDURE:
Referential Integrity
A referential integrity constraint is also known as foreign key constraint. A foreign key is a key
whose values are derived from the Primary key of another table.
The table from which the values are derived is known as Master or Referenced Table and the Table
in which values are inserted accordingly is known as Child or Referencing Table, In other words, we can
say that the table containing the foreign key is called the child table, and the table containing the Primary
key/candidate key is called the referenced or parent table.
Program:
Parent Table:
SQL> create table stock3(itemno number(5)primary key ,itemname varchar2(10));
Table created.
Child Table
SQL> create table stock4(itemno number(5)references stock3(itemno),price number(5));
Table created.
SQL> insert into stock4 values(3,100);
1 row created.
SQL> insert into stock4 values(3,100);
1 row created.
15
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
3 100
SQL> insert into stock4 values(2,100);
insert into stock4 values(2,100)
*
ERROR at line 1:
RESULT:
Thus the Create a set of tables, add foreign key constraints and incorporate referential integrity are
executed successfully.
Augmented Question:
Design a library management system that tracks books, authors, and borrowers. Create the appropriate tables with
foreign key relationships between them, ensuring referential integrity. Use the ON DELETE CASCADE and ON UPDATE
CASCADE actions where necessary, and discuss how these actions help maintain data consistency and integrity in the
system.
Viva Question:
1. How does the FOREIGN KEY constraint in the BorrowedBooks table ensure that only valid borrowers and books are
recorded?
2. How does the FOREIGN KEY constraint in the BorrowedBooks table ensure that only valid borrowers and books are
recorded?
16
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex: No: 3 Query the database tables using different ‘where’ clause conditions and also
implement aggregate functions
AIM:
To Query the database tables using different ‘where’ clause conditions and also implement
Aggregate functions.
PROCEDURE:
A WHERE clause in SQL is used with the SELECT query, which is one of the data manipulation
language commands. WHERE clauses can be used to limit the number of rows to be displayed in the
result set, it generally helps in filtering the records. It returns only those queries which fulfill the specific
conditions of the WHERE clause. WHERE clause is used in SELECT, UPDATE, DELETE statement,
etc. WHERE Syntax
SELECT column1, column2, FROM table name
WHERE condition;
Consider the employee table with the following data:
Date_of_
E_ID Name Salary City Designation Age
Joining
1 Sakshi Kumari 50000 Mumbai Project Manager 2021-06-20 24
2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23
3 Anuja Sharma 40000 Jaipur Manager 2021-08-15 26
4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24
5 Rucha Jagtap 45000 Bangalore Project Manager 2020-08-09 23
6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26
7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24
8 Sana Sheik 45000 Pune Software Engineer 2020-09-10 26
9 Swati Kumari 50000 Pune Software Tester 2021-01-01 25
10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24
11 Simran Khanna 45500 Kolhapur HR 2019-01-02 26
12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25
13 Kiran Maheshwari 50000 Nashik HR 2013-12-12 23
14 Tejal Jain 40000 Delhi Project Manager 2017-11-10 25
15 Mohini Shah 38000 Pune Software Developer 2019-03-05 20
Example 1:
Write a query to retrieve all those records of an employee where employee salary is greater than 50000.
Query:
sql> SELECT * FROM employees WHERE Salary > 50000;
17
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Output
2 Tejaswini Naik 75000 Delhi System Engineer 2019-12-24 23
4 Anushka Tripathi 90000 Mumbai Software Tester 2021-06-13 24
6 Rutuja Deshmukh 60000 Bangalore Manager 2019-07-17 26
7 Swara Baviskar 55000 Jaipur System Engineer 2021-10-10 24
10 Mayuri Patel 60000 Mumbai Project Manager 2020-10-02 24
12 Shivani Wagh 50500 Delhi Software Developer 2016-09-10 25
AGGREGATE FUNCTIONS:
An aggregate function in SQL performs a calculation on multiple values and returns a single value. SQL
provides many aggregate functions that include avg, count, sum, min, max, etc. An aggregate function
ignores NULL values when it performs the calculation, except for the count function
EID NUMBER
ENAME VARCHAR2(10)
AGE NUMBER
SALARY NUMBER
(ii) Count number of employee names from employee
table. SQL> select count(ename) from emp;
COUNT(ENAME)
7
(iii) Find the Maximum age from employee table.
SQL> select max(age) from emp;
MAX(AGE)
44
(iv) Find the Minimum age from employee
table. SQL> select min(age) from emp;
MIN(AGE)
22
220
(vi) Display the Average of age from Employee
table. SQL> select avg(age) from emp;
AVG(AGE)
31.4285714
(vii) Create a View for age in employee table
SQL> create or replace view A as select age from emp where age select * from A;
AGE
22 29 27 29
(ix)Find grouped salaries of employees.(group by clause)
SQL> select salary from emp group by salary;
SALARY
9000 10000 8000 6000 7000
(x).Find salaries of employee in Ascending Order.(order by clause)
SQL> select ename,salary from emp order by salary;
ENAME SALARY
rohan 6000
alex 7000
shane 8000
abhi 8000
tiger 8000
anu 9000
scott 10000
7 rows selected.
(xi) Find salaries of employee in Descending Order.
SQL> select ename,salary from emp order by salary desc;
ENAME SALARY
scott 10000
anu 9000
shane 8000
abhi 8000
19
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
tiger 8000
alex 7000
rohan 6000
7 rows selected.
(xii)Having Clause.
SQL> select ename,salary from emp where age
ENAME SALARY
alex 7000
anu 9000
RESULT:
Thus the Query database tables using different ‘where’ clause conditions implementation.
Augmented Question:
1. Retrieve the names of employees who have a salary greater than 50,000.
2. Retrieve the total salary expense for each department.
3. Find the highest salary in the Employees table.
Viva Question:
1. How do aggregate functions like SUM(), COUNT(), and MAX() work in SQL? Can you give an example of each?
2. What is the difference between WHERE and HAVING clauses when using aggregate functions?
3. How would you write a query to find the average salary of employees in a particular department?
20
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex. No: 4 Query the database tables and explore sub queries and simple join operations
AIM:
To Query the database tables and explore sub queries and simple join operations.
PROCEDURE:
SQL - SELECT Query
The SQL SELECT statement is used to fetch the data from a database table which returns this data in the
form of a result table. These result tables are called result-sets.
Syntax
The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
SELECT * FROM table_name;
Sub Query:
While creating a database if we want to extract some information regarding the data in the database
then we use a Query. In other words, if we want to retrieve some data from a table or some tables that we
created earlier then we write/use a Query.
Sub Queries are very useful for selecting rows from a table having a condition that depends on the data of
the table itself. A Sub Query can also be called a Nested/Inner Query. These Sub Queries can be used with:
• WHERE Clause
• SELECT Clause
• FROM Clause
SELECT <column, ...> FROM <table> WHERE expression operator ( SELECT <column, ...> FROM
<table> WHERE <condition> );
Nested Subquery:
A subquery can be nested inside other subqueries. SQL has an ability to nest queries within one
another. A subquery is a SELECT statement that is nested within another SELECT statement and
which return intermediate results. SQL executes innermost subquery first, then next level
Join:
Join is the most powerful operation for merging information from multiple tables based on a common field.
There are various types of joins but an INNER JOIN is the common of them.
21
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Syntax
SELECT col1, col2, col3... FROM table_name1, table_name2 WHERE table_name1.col2 =
table_name2.col1;
Eg:
CREATE TABLE Customer ( Cust_id Number(10) NOT NULL, Cust_name varchar2(20), Country
varchar2(20), Receipt_no Number(10), Order_id Number(10) NOT NULL, );
CREATE TABLE Orders ( Order_id Number(10), Item_ordered varchar2(20), Order_date date );
Using and ON clause
SELECT Cust_id, Cust_name, Country, item_Ordered, Order_date FROM Customer C JOIN Orders O
USING (Order_id);
SELECT Cust_id, Cust_name, Country, item_Ordered, Order_date FROM Customer C JOIN Orders O ON
(C.Order_id = O.Order_id);
Equi Join
An Equi join is used to get the data from multiple tables where the names are common and the
columns are specified. It includes the equal ("=") operator.
Example
SELECT Cust_id, Cust_name, item_Ordered, Order_date FROM Customer C, Orders O WHERE
C.Order_id = O.Order_id;
Program:
SQL OPERATORSSQL> select * from stock1
4 gk pen
7 kkk pen
12 gk pen
12 kk pen
SQL> select *from stock1 where sname='gk';
SNO SNAME ITEM
4 gk pen
12 gk pen
22
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
7 kkk pen
12 kk pen
SQL> select *from stock1 where sno> 7;
SNO SNAME ITEM
12 gk pen
12 kk pen
SQL> select *from stock1 where sno>= 7 and sname='gk';
SNO SNAME ITEM
12 gk pen
SQL> select *from stock1 where sno>= 7 or sname='gk';
SNO SNAME ITEM
4 gk pen
7 kkk pen
12 gk pen
12 kk pen
SQL> select *from stock1 where (sno>= 7 and sname='gk') or (item='pen');
SNO SNAME ITEM
4 gk pen
7 kkk pen
12 gk pen
12 kk pen
SQL> select *from stock1 where (sno>= 7 and sname='gk') order by item;
23
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
12 gk pen
SQL> select all sno from stock1 where sname='kkk';
SNO
7
SQL> select distinct sno from stock1 where sname='gk'; SNO
4
12
4 gk pen
7 kkk pen
12 gk pen
SQL> select * from stock1 where sname not in('gk','kkk');
SNO SNAME ITEM
12 kk pen
SQL> select * from stock1 where sname <> 'gk';
SNO SNAME ITEM
7 kkk pen
12 kk pen
SQL> select * from stock1 where sname <> 'null';
SNO SNAME ITEM
4 gk pen
24
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
7 kkk pen
12 gk pen
12 kk pen
SQL> select * from stock1 where sname is null;
no rows selected
SQL> select * from stock1 where sname is not null;
SNO SNAME ITEM
4 gk pen
7 kkk pen
12 gk pen
12 kk pen
SQL> select * from stock1 where sname like 'k%';
7 kkk pen
12 kk pen
4 gk pen
12 gk pen
SQL> select *from stock4;
SNO SNAME ITEM AGE
6 fff watch 9
7 ggg hhh 10
7 ggg hhh 20
7 ggg hhh 22
25
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Watch
SQL> select * from stock4 where age between 10 and 22;
7 ggg hhh 10
7 ggg hhh 20
7 hhh 22
Alias Column
SQL> select sno as stno from
stock4; STNO
6
7
7
7
ANY
SQL> select * from
stock4;
SNO SNAME ITEM AGE
6 fff watch 9
7 ggg hhh 10
7 ggg hhh 20
7 ggg hhh 22
SQL> select * from
stock1;
SNO SNAME ITEM
26
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
4 gk pen
7 kkk pen
12 gk pen
12 kk pen
SQL> select sno,sname from stock4 where sno=any(select sno from stock1 where sno
=7);
SNO SNAME
7 ggg
7 ggg
7 ggg
Soe
SQL> select sno,sname from stock4 where sno=some(select sno from stock1 where sn o=7);
GROUP BY:
SQL> select dept,min(marks) from student group by dept;
DEPT MIN(MARKS)
cse 100
it 87
ece 94
SQL> select dept,min(marks) from student group by dept having min(marks)>90;
DEPT MIN(MARKS)
ece 94
UNION:
SQL> select sname from student union select name from railway;
SNAME
max
melvina
27
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
sarah
selvi
sophia
stella
6 rows selected.
INTERSECT:
SQL> select sname from student intersect select name from railway;
SNAME
max
sarah
sophi
EXCEPT OR MINUS:
SQL> select sname from student minus select name from
railway; SNAME
Stella
CONVERSION FUNCTIONS:
SQL> select nvl(' ',2) from dual;
N
-
SQL> select decode(10,20,30,40,50,25) from
dual; DECODE(10,20,30,40,50,25)
25
SQL> select decode(10,10,30,40,50,25) from
dual; DECODE(10,10,30,40,50,25)
30
28
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
30
50
JOINS:
SQL> create table stud(rollno number(5),studname varchar2(10),dept varchar2(5));
Table created.
SQL> create table marks(rollno number(5),marks number(5),cgpa number(5));
Table created.
SQL> insert into stud
values(101,'harini','cse'); 1 row created.
SQL> insert into stud values(102,'priya','cse');
1 row created.
SQL> select * from stud;
ROLLNO STUDNAME DEPT
101 77 8
29
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
30
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
RESULT:
Thus the Database Querying – Simple Queries, Nested Queries, Sub Queries and Joins are executed
successfully.
Augmented Question:
1. Retrieve the names of employees who work in a department that has a budget greater than 1,000,000.
2. Find the employees whose salary is greater than the average salary in their respective department using a
subquery.
3. List all departments with the total salary expenditure greater than 500,000 by joining the Departments and
Salaries tables.
Viva Question:
1. What is a subquery in SQL, and how does it differ from a regular query?
2. Can you explain the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN in SQL? Provide an
example for each.
3. What is the role of a subquery in a WHERE clause? Can you give an example where it is used to filter records?
31
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
EX. NO: 5 Query the database tables and explore natural, equi and outer joins.
AIM:
To create the tables and explore natural, equi and outer join
PROCEDURE:
1. Inner Join An Inner Join retrieves the matching records, in other words it retrieves all the rows
where there is at least one match in the tables.
Example SELECT Cust_id, Cust_name, Country, item_ordered, Order_date
FROM Customer INNER JOIN Orders USING (Order_id);
2. Outer Join
The records that don't match will be retrieved by the Outer join. It is of the following three types:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
1. Left Outer Join
A Left outer join retrieves all records from the left hand side of the table with all the matched records. This
query can be written in one of the following two ways.
Eg:
SELECT Cust_id, Cust_name, Country, item_ordered, Order_date FROM customer C, LEFT OUTER JOIN
Orders O ON (C. Order_id = O.Order_id)
2. Right Outer Join A Right Outer Join retrieves the records from the right hand side columns.
Eg:
SELECT Cust_id, Cust_name, Country, item_ordered, Order_date FROM customer C, RIGHT OUTER
JOIN Orders O ON (C. Order_id = O.Order_id)
3. Full Outer Join
To retrieve all the records, both matching and unmatched from all the tables then use the FULL OUTER
JOIN.
Example
SELECT Cust_id, Cust_name, Country, item_ordered, Order_date
FROM customer C, FULL OUTER JOIN Orders OON (C. Order_id = O.Order_id)
4. Non-Equi Join A Non-Equi join is based on a condition using an operator other than equal to "=".
Example
SELECT Cust_id, Cust_name, Country, Item_ordered, Order_date FROM Customer C, Oredrs O WHERE
C. Order_id > O.Order_id;
5. Self-join When a table is joined to itself only then that condition is called a self-join.
Example
SELECT C1.Cust_id, C2.Cust_name, C1.Country, C2.Order_id FROM Customer C1, Customer C2
WHERE C. Cust_id > O.Order_id;
32
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
JOINS:
SQL> create table stud(rollno number(5),studname varchar2(10),dept varchar2(5));
Table created.
SQL> create table marks(rollno number(5),marks number(5),cgpa number(5));
Table created.
SQL> insert into stud values(101,'harini','cse');
1 row created.
SQL> insert into stud values(102,'priya','cse');
1 row created.
SQL> select * from stud;
ROLLNO STUDNAME
DEPT
Result:
The Database Querying – Join operations are executed successfully.
Augmented Question:
1. Perform a RIGHT OUTER JOIN between Employees and Departments to list all departments, including those
without any employees.
2. Perform a FULL OUTER JOIN between Employees and Departments to retrieve all employees and
departments, including records that do not have matches in either table.
34
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Viva Question:
1. What is the role of the ON clause in a join, and how does it differ in various types of joins (e.g., INNER JOIN,
OUTER JOIN)?
2. How does a NATURAL JOIN automatically match columns between two tables, and what happens if two tables
have columns with the same name but different data types?
Ex. No: 6 Write user defined functions and stored procedures in SQL.
AIM:
To write user defined functions and stored procedures in SQL.
PROCEDURE:
A subprogram is a program unit/module that performs a particular task. These subprograms
are combined to form larger programs. This is basically called the 'Modular design'. A subprogram
can be invoked by another subprogram or program which is called the calling program.
Functions
These sub programs return a single value; mainly used to compute and return a value.
Creating a function
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS |
AS}
BEGIN
< function_body >
END [function_name];
• Procedures − These subprograms do not return a value directly; mainly used to perform an
action. Parts of PL/SQL Program:
Declarative Part-> It is an optional part.Declarative part does not start with the DECLARE keyword.
Executable Part-> Mandatory part
Exception Handling-> optional part.
Creating a Procedure:
Syntax:
35
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
/
The above call will display −
Hello World
Deleting a Standalone Procedure
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a procedure
is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
36
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
z:= y; END
IF; END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
Minimum of (23, 45) : 23 66
PL/SQL procedure successfully completed.
Creating a function
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
37
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
Function created.
Calling a
function:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
Total no. of Customers: 6
PL/SQL procedure successfully completed.
RESULT:
Augmented Question:
1. Write a user-defined function in SQL that takes an employee's salary and returns the annual salary (multiply
the monthly salary by 12).
2. Create a stored procedure that accepts a department name as input, retrieves all employees in that department,
and returns a list of employee names and their salaries.
Viva Question:
38
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
1. What is the purpose of input and output parameters in stored procedures? Can you provide an example of both?
2. How do you execute a stored procedure, and what is the difference between calling a function and calling a stored
procedure in SQL?
3. Can you explain the scope of variables in a stored procedure? How do local variables differ from global variables
in the context of stored procedures?
Ex. No: 7 Execute complex transactions and realize DCL and TCL Commands
AIM:
DCL COMMANDS
DCL stands for Data Control Language in Structured Query Language (SQL). As the name suggests these
commands are used to control privilege in the database. The privileges (Right to access the data) are
required for performing all the database operations like creating tables, views, or sequences. DCL command
is a statement that is used to perform the work related to the rights, permissions, and other control of the
database system
39
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
This command is used to grant permission to the user to perform a particular operation on a particular
object. If you are a database administrator and you want to restrict user accessibility such as one who only
views the data or may only update the data. You can give the privilege permission to the users according to
your wish.
Syntax:
GRANT privilege_list ON Object_name TO user_name;
REVOKE
REVOKE
This command is used to take permission/access back from the user. If you want to return permission from
the database that you have granted to the users at that time you need to run REVOKE command.
Syntax:
REVOKE privilege_list ON object_name FROM user_name;
TCL Commands
COMMIT command
COMMIT command is used to permanently save any transaction into the database. To avoid that, we use
the COMMIT command to mark the changes as permanent. Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last committed state. It is also used with SAVEPOINT command to
jump to a savepoint in an ongoing transaction.
REVOKE COMMAND
TCL COMMANDS:
SQL> desc
employee Name
Null? Type
EMPID NUMBER(5)
EMPNAME VARCHAR2(10)
DEPT VARCHAR2(20)
DOB DATE
SALARY NUMBER(6)
INSERT:
ONETIME INSERTION:
41
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
SELECT:
UPDATE:
42
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
SAVEPOINT:
SQL> commit;
Commit complete.
43
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
ROLL BACK:
RESULT:
Augmented Question:
2. After the transaction, use DCL (Data Control Language) commands to:
Viva Question:
1. What are the differences between DCL (Data Control Language) and TCL (Transaction Control Language)
in SQL? Can you give examples of commands from each?
2. How do COMMIT and ROLLBACK work in SQL, and what happens when a transaction is rolled back?
3. How does TRUNCATE differ from DELETE in terms of DCL and TCL? What impact does each have on
transactions?
44
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex. No: 8 Write SQL Triggers for insert, delete, and update operations in database table.
AIM:
To Write SQL Triggers for insert, delete, and update operations in a database table.
PROCEDURE:
A PL/SQL trigger is a named database object that encapsulates and defines a set of actions that are to
be performed in response to an insert, update, or delete operation against a table. Triggers are created using
the PL/SQL CREATE TRIGGER statement.
Create trigger syntax:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
45
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Executable-statements
EXCEPTION
Exception-handling-statements
END;
General Syntax:
CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing trigger with the
trigger_name.
Insert/Update Trigger
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML
operation. [OF col_name]: This specifies the column name that would be
updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[OR 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.
WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is
valid only for row level triggers .
PROGRAM
SQL> set serveroutput on
1 create or replace trigger dmlo
2 after update or insert or delete on emp
3 for each row
4 begin
5 if updating then
6 dbms_output.put_line('table is updated');
7 elsif inserting then
7 dbms_output.put_line('table is inserted');
8 elsif deleting then
10 dbms_output.put_line('table is deleted');
11 end if;
12*
end; 13 /
46
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Trigger created.
OUTPUT
SQL> set serveroutput on
SQL> select *from emp;
ENO ENAME BP HRA
DA
47
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
2. PROGRAM
SQL> set serveroutput on
1 create trigger t1age
2 before insert or update of age on trig
3 for each row
4 begin
5 if(:new.age<0) then
6
7 raise_application_error(-20000,'no negative age allowed');
7 else
8 dbms_output.put_line('valid age');
9 end if; \10*
end;
SQL> /
Trigger created.
OUTPUT
48
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
RESULT:
Thus the PL/SQL Trigger are executed successfully
Augmented Question:
1. Create an INSERT trigger that logs the insertion of a new product into a Products table into an Audit table.
2. Write a DELETE trigger to log the deletion of a product, recording the product details before deletion.
3. Write an UPDATE trigger that tracks price changes in the Products table and logs the old and new price values in
the Audit table.
Viva Question:
1. What are SQL triggers, and how do they differ from stored procedures?
2. Can you explain the difference between BEFORE and AFTER triggers in SQL? When would you use each?
3. How do you handle multiple AFTER triggers in the same table? Can they run in parallel or sequent
EX.NO: 9 Use SQLi to authenticate as administrator, to get unauthorized access over sensitive
data, to inject malicious statements into form field.
PROCEDURE:
Authentication - it is the act of checking users credentials to identify whether user is authenticated
one and can have access to sensitive information that comes under that specific user role like (Normal
User, Admin user, etc.)
Authorization - it is the process of role mapping or providing access to different part of the application
interfaces, Functionalities and sensitive information based on user role. For ex: Admin user role can
49
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
have access to web interfaces which allows Admin users to create different normal users, delete them if
needed and providing and restricting access to different part of the application.
Used total debugging approach to make you understand every step in identifying and exploiting SQL
Injection to bypass Authentication mechanism.
Tools Used:
50
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Code to Create Designer of Login Page, Error Page, Welcome Screen is given below:
Login Screen
51
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Error Screen
Welcome Screen
52
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Created SQL Server Database SpitFireDB and table TblLogin using below Queries:
53
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Login Screen Code on Button Click to perform credential check with database
Notice as shown above, Most of the developer write inline SQL queries directly into code to perform
dynamic task. Here user supplied input for Username and Password will be captured
from txtusername.Text Textbox and txtpwd.Text Textbox and appended into inline SQL queries
without any validation and sanitization which will later leads to Authentication Bypass.below.
If user credentials are correct then it will redirect to Welcome Screen. I have inserted Breakpoint into
code to make readers understand how correct credentials redirect user to Welcome Screen and Wrong
Credentials on Error Screen.
Correct Credentials are Any of given below:
Debugger shows Correct credentials in CommandText Property and Redirection on Welcome.aspx Screen
54
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Debugger shows Wrong credentials in CommandText Property and Redirection on Error.aspx Screen
55
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
So far, I have shown normal behaviour of the web application with proof with the help of debugging that
How web application send different responses and redirect on different web page based on authenticity of
entered credentials. Now lets come to our pen-testing part and let’s try to bypass authentication by
entering wrong credentials. Let’s call it as “Hacker’s Way of Exploitation”
Payload Used: ‘ or 1=1--
Now try to login using Hacker’s perspective let’s see whether we can login using wrong credentials.
Below figure shows I have entered wrong credentials which is,
Wrong Credentials:
Username: ‘ or 1=1--
Password: foo
56
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Debugging: Understanding Query Logic which incorporates our payload ‘ or 1=1-- and Bypass
Authentication Mechanism
RESULT:
Thus the authentication and authorization using SQL injection executed successfully.
Augmented Question:
Explain what SQL Injection is and describe how attackers might exploit it to gain unauthorized access to
sensitive data. Then, discuss how database administrators and developers can prevent SQL injection vulnerabilities by
using prepared statements, input validation, and other best practices.
Viva Question:
1. What is SQL Injection (SQLi), and how does it work? Can you provide an example of how an attacker might
exploit SQLi?
2. How can SQL injection lead to unauthorized access to sensitive data? What types of databases or applications
are most vulnerable to SQLi attack
57
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex. No 10 Write programs that will defend against the SQLi attacks
PROCEDURE :
Database Connection: The script establishes a connection to the MySQL database using the
mysql.connector module. This connection is essential for executing queries against the database.
conn = mysql.connector.connect(
host="localhost",
user="your_mysql_username",
password="your_mysql_password",
database="sqli_authorization_example"
)
Replace "your_mysql_username" and "your_mysql_password" with your actual MySQL username and
password. This establishes a connection to the database named sqli_authorization_example running on
localhost.
Prepared Statement: Instead of constructing SQL queries by concatenating strings, the script uses
parameterized queries. This is crucial for defending against SQL injection attacks. Parameterized
queries separate SQL code from user input, preventing malicious inputs from altering the SQL logic.
query = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (username,))
(),
The result is retrieved using cursor.fetchone which fetches the next row of the result set returned by
the query. If a matching record is found in the database for the provided username, it is stored in the
result variable
58
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Authorization Check: The script checks the role associated with the username retrieved from the
database. If the role is 'admin', it indicates that the user is authorized as an admin.
The result is retrieved using cursor.fetchone(), which fetches the next row of the result set returned by the
query. If a matching record is found in the database for the provided username, it is stored in the result
variable.
Authorization Check: The script checks the role associated with the username retrieved from the
database. If the role is 'admin', it indicates that the user is authorized as an admin.
RESULT:
Thus the Program for defend against SQLi attacks program was executed successfully.
Augmented Question:
Write a program in SQL and/or a web application (e.g., PHP, Python) that defends against SQL Injection (SQLi)
attacks by:
Viva Question:
59
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Ex. No: 11 Write queries to insert encrypted data into the database and to retrieve the data using
decryption.
AIM:
To write queries to insert encrypted data into the database and to retrieve the
data using decryption.
PROCEDURE:
AS
BEGIN
END;
@decryptionKey NVARCHAR(50)
AS
BEGIN
60
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
WHERE ID = @id;
RESULT:
61
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
Augmented Question:
How do encryption and decryption functions like AES_ENCRYPT and AES_DECRYPT work in SQL, and what
precautions should be taken when using encryption to ensure data security?"
Viva Question:
What are the advantages and potential challenges of storing encrypted data in a database, and how does SQL's
AES_ENCRYPT and AES_DECRYPT functions help in ensuring the confidentiality of sensitive information?"
62
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
63
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
64
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
65
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
66
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
67
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
68
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
69
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
70
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
71
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
72
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
73
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
74
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
75
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
76
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
77
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
78
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
79
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
80
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
81
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
82
Downloaded by Abii ([email protected])
lOMoARcPSD|54505038
83