0% found this document useful (0 votes)
12 views69 pages

Dbms Manual

The document outlines the objectives and outcomes of a Database Management System lab course at Jawaharlal Nehru Technological University, Kakinada. It details various experiments involving SQL commands, PL/SQL programming, and the implementation of database integrity constraints. The course aims to equip students with practical skills in database creation, manipulation, and advanced querying techniques.

Uploaded by

sivanagaraju779
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views69 pages

Dbms Manual

The document outlines the objectives and outcomes of a Database Management System lab course at Jawaharlal Nehru Technological University, Kakinada. It details various experiments involving SQL commands, PL/SQL programming, and the implementation of database integrity constraints. The course aims to equip students with practical skills in database creation, manipulation, and advanced querying techniques.

Uploaded by

sivanagaraju779
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 69

1 | Page

--------------`444]

DR2D24CREATE 4
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY: KAKINADA
KAKINADA – 533 003, Andhra Pradesh, India
DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS
\

2 | Page
3 | Page
4 | Page
5 | Page
6 | Page
L T P C
I Year – II Semester
0 0 3 1
.
5
DATABASE MANAGEMENT SYSTEM LAB

Course Objectives:
1) This Course will enable students to
2) Populate and query a database using SQL DDL/DML Commands
3) Declare and enforce integrity constraints on a database
4) Writing Queries using advanced concepts of SQL
5) Programming PL/SQL including procedures, functions, cursors and triggers

Course Outcomes:
1) At the end of the course the student will be able to:
2) Utilize SQL to execute queries for creating database and performing data manipulation operations
3) Examine integrity constraints to build efficient databases

7 | Page
4) Apply Queries using Advanced Concepts of SQL
5) Build PL/SQL programs including stored procedures, functions, cursors and triggers

List of Experiments:
1) Execute all DDL, DML and DCL commands on sample tables.
2) Implementation of different types of operators and built-in functions with suitable examples
3) Implementation of different types of joins with suitable examples
4) Create views, partitions, Sequence, Indexes and locks for a particular DB
5) Implement different types of constraints on relations.
6) Implementation of subqueries and nested queries.
7) Implement Queries on Group by & Having Clauses, ALIAS, Sequence By, Order By
8) Control Structure
a) Write a PL/SQL block for Addition of Two Numbers
b) Write a PL/SQL block for IF, IF and else condition
c) Write a PL/SQL block for implementation of loops
d) Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
9) Exception Handling- Implement the following with respect to exception handling. Raising Exceptions, User Defined
Exceptions, Pre-Defined Exceptions
10) Write PL/SQL block for an application using exception handling Procedures
a) Write a PL/SQL Procedure using Positional Parameters
b) Write a PL/SQL Procedure using notational parameters
c) Write a PL/SQL Procedure for GCD Numbers
d) Write a PL/SQL Procedures for cursor implementation (explicit and implicit cursors)
11) Functions:
a) Write a PL/SQL block to implement factorial using functions
b) Write a PL/SQL function to search an address from the given database
12) Write a DBMS program to prepare Pl/SQL reports for an application using functions.
13) Triggers:
a) Write a Trigger to pop-up the DML operations
b) Write a Trigger to check the age valid or not Using Message Alert.
c) Create a Trigger to Raise appropriate error code and error message.
d) Create a Trigger on a table so that it will update another table while inserting values
14) Write a PL/SQL block for an application using cursors and all types of triggers.
15) Write a PL/SQL block for transaction operations of a typical application using package

INDEX
Experiments Page No

1) Execute all DDL, DML and DCL commands on sample tables. 4


2) Implementation of different types of operators and built-in functions 7
with suitable examples
3) Implementation of different types of joins with suitable examples 15
4) Create views, partitions, Sequence, Indexes and locks for a particular DB 21
5) Implement different types of constraints on relations. 35

8 | Page
6) Implementation of subqueries and nested queries . 38
7)Implement Queries on Group by & Having Clauses, ALIAS, Sequence By, 43
Order By
8) Control Structure 45
a) Write a PL/SQL block for Addition of Two Numbers
b) Write a PL/SQL block for IF, IF and else condition
c) Write a PL/SQL block for implementation of loops
d) Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
9) Exception Handling- Implement the following with respect to exception handling. 49
Raising Exceptions, User Defined Exceptions, Pre-Defined Exceptions
10) Write PL/SQL block for an application using exception handling Procedures 51
a) Write a PL/SQL Procedure using Positional Parameters
b) Write a PL/SQL Procedure using notational parameters
c) Write a PL/SQL Procedure for GCD Numbers
d) Write a PL/SQL Procedures for cursor implementation(explicit and implicit cursors)
11) Functions: 56
a) Write a PL/SQL block to implement factorial using functions
b) Write a PL/SQL function to search an address from the given database
12) Write a DBMS program to prepare Pl/SQL reports for an application using functions. 57
13) Triggers: 59
a) Write a Trigger to pop-up the DML operations
b) Write a Trigger to check the age valid or not Using Message Alert.
c) Create a Trigger to Raise appropriate error code and error message.
d) Create a Trigger on a table so that it will update another table while inserting values
14) Write a PL/SQL block for an application using cursors and all types of triggers. 61
create15) Write a PL/SQL block for transaction operations of a typical application using 63
package

Experiment-1

Execute all DDL, DML and DCL commands on sample tables.

First of all, let’s define DDL, DML, DCL, and TCL in DBMS.

DDL is Data Definition Language


DML is Data Manipulation Language
DCL is Data Control Language
TCL is Transaction Control Language
As you see from its name it allows the user to define, manipulate and control data and transactions in SQL language.

9 | Page
It’s four types of SQL sublanguages, that’s why it’s no sense to search for a difference between DDL vs DML or DCL vs TCL.

SQL commands list:

DDL Language Command List


CREATE
DROP
ALTER
RENAME
TRUNCATE
DML SELECT
INSERT
UPDATE
DELETE
DCL GRANT
REVOKE
TCL START TRANSACTION
COMMIT
ROLLBACK
Keep reading and I’ll explain in detail what DDL, DML, DCL, and TCL are with examples.

What is DDL in SQL?


DDL allows you to create SQL statements to make operations with database data structures (schemas, tables etc.).

These are SQL DDL commands list and examples:

CREATE
CREATE statement is used to create a new database, table, index or stored procedure.

Create database example:

CREATE DATABASE explain java;


CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL );

DROP
DROP statement allows you to remove database, table, index or stored procedure.

Drop database example:

DROP DATABASE explain java;

10 | Page
Drop table example:
CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL );

Alter table example:

ALTER TABLE user ADD COLUMN lastname VARCHAR(255) NOT NULL;


RENAME
The RENAME command is used to rename SQL tables.

Rename table example:

RENAME TABLE user TO student;


TRUNCATE
TRUNCATE operation is used to delete all table records.

Logically it’s the same as the DELETE command.

Differences between DELETE and TRUNCATE commands are:

TRUNCATE is really faster


TRUNCATE cannot be rolled back
TRUNCATE command does not invoke ON DELETE triggers
Example:

TRUNCATE student;
What is DML in SQL?
DML is a Data Manipulation Language, it’s used to build SQL queries to manipulate (select, insert, update, delete etc.) data in
the database.

This is DML commands list with examples:

SELECT
SELECT query is used to retrieve data from SQL tables.

Example:

SELECT * FROM student;


INSERT
INSERT command is used to add new rows into the eye database table.

Example:

INSERT INTO student (name, last name) VALUES ('Dmytro', 'Shvechikov');

11 | Page
UPDATE
UPDATE statement modifies records into the table.

Example:
CREATE TABLE user (
id INT(16) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL );

Example:

DELETE FROM student WHERE name = 'Dima';


What is DCL in SQL?
DCL a Data Control Language.

Its commands are responsible for access restrictions inside of the database.

Let’s take a look at DCL statements definitions.

GRANT
The GRANT command gives permissions to SQL user accounts.

For example, I want to grant all privileges to the ‘explain java’ database for user ‘dmytro@localhost’.

Let’s create a user first:

CREATE USER 'dmytro'@'localhost' IDENTIFIED BY '123';


Then I can grant all privileges using GRANT statement:

GRANT ALL PRIVILEGES ON explain java.* TO 'dmytro'@'localhost';


and we have to save changes using FLUSH command:

FLUSH PRIVILEGES;
REVOKE
A REVOKE statement is used to remove privileges from user accounts.

Example:

REVOKE ALL PRIVILEGES ON explain java.* FROM 'dmytro'@'localhost';


and save changes:

FLUSH PRIVILEGES;

Experiment-2

The * symbol multiples two numbers together.

12 | Page
SELECT 10 * 10;Implementation of different types of operators and built-in functions with suitable examples

Arithmetic operators

Arithmetic operators are used for


mathematical operations on numerical
data, such as adding or subtracting.
+ (Addition)
The + symbol adds two numbers together.

SELECT 10 + 10;
- (Subtraction)
The - symbol subtracts one number from another.

SELECT 10 - 10;
* (Multiplication)

/ (Division)
The / symbol divides one number by another.

SELECT 10 / 10;
% (Remainder/Modulus)
The % symbol (sometimes referred to as Modulus) returns the remainder of one number divided by another.

SELECT 10 % 10;

Just a quick reminder: a binary number in computing is a number made up of 0s and 1s.

& (Bitwise AND)


The & symbol (Bitwise AND) compares each individual bit in a value with its corresponding bit in the other value. In the
following example, we are using just single bits. Because the value of @BitOne is different to @BitTwo, a 0 is returned.

DECLARE @BitOne BIT = 1


DECLARE @BitTwo BIT = 0
SELECT @BitOne & @BitTwo;
But what if we make the value of both the same? In this instance, it would return a 1.

13 | Page
DECLARE @BitOne BIT = 1
DECLARE @BitTwo BIT = 1
SELECT @BitOne & @BitTwo;
Obviously this is just for variables that are type BIT. What would happen if we started using numbers instead? Take the
example below:

DECLARE @BitOne INT = 230


DECLARE @BitTwo INT = 210
SELECT @BitOne & @BitTwo;
The answer returned here would be 194.

You might be thinking, “How on earth is it 194?!” and that’s perfectly understandable. To explain why, we first need to
convert the two numbers into their binary form:

@BitOne (230) - 11100110


@BitTwo (210) - 11010010
Now, we have to go through each bit and compare (so the 1st bit in @BitOne and the 1st bit in @BitTwo). If both numbers are
1, we record a 1. If one or both are 0, then we record a 0:

@BitOne (230) - 11100110


@BitTwo (210) - 11010010
Result - 11000000
The binary we are left with is 11000000, which if you google is equal to a numeric value of 194.

Confused yet? Don’t worry! Bitwise operators can be confusing to understand, but they’re rarely used in practice.

&= (Bitwise AND Assignment)


The &= symbol (Bitwise AND Assignment) does the same as the Bitwise AND (&) operator but then sets the value of a
variable to the result that is returned.

| (Bitwise OR)
The | symbol (Bitwise OR) performs a bitwise logical OR operation between two values. Let’s revisit our example from
before:

DECLARE @BitOne INT = 230


DECLARE @BitTwo INT = 210
SELECT @BitOne | @BitTwo;
In this instance, we have to go through each bit again and compare, but this time if EITHER number is a 1, then we record a 1.
If both are 0, then we record a 0:

@BitOne (230) - 11100110


@BitTwo (210) - 11010010

Result - 11110110
The binary we are left with is 11110110, which equals a numeric value of 246.

14 | Page
|= (Bitwise OR Assignment)
The |= symbol (Bitwise OR Assignment) does the same as the Bitwise OR (|) operator but then sets the value of a variable to
the result that is returned.

^ (Bitwise exclusive OR)


The ^ symbol (Bitwise exclusive OR) performs a bitwise logical OR operation between two values.

DECLARE @BitOne INT = 230


DECLARE @BitTwo INT = 210
SELECT @BitOne ^ @BitTwo;
In this example, we compare each bit and return 1 if one, but NOT both bits are equal to 1.

@BitOne (230) - 11100110


@BitTwo (210) - 11010010
Result - 00110100
The binary we are left with is 00110100, which equals a numeric value of 34.

^= (Bitwise exclusive OR Assignment)


The ^= symbol (Bitwise exclusive OR Assignment) does the same as the Bitwise exclusive OR (^) operator but then sets the
value of a variable to the result that is returned.

Comparison operators
A comparison operator is used to compare two values and test whether they are the same.

= (Equal to)
The = symbol is used to filter results that equal a certain value. In the below example, this query will return all customers that
have an age of 20.

SELECT * FROM customers


WHERE age = 20;
!= (Not equal to)
The != symbol is used to filter results that do not equal a certain value. In the below example, this query will return all
customers that don't have an age of 20.

SELECT * FROM customers


WHERE age != 20;
> (Greater than)
The > symbol is used to filter results where a column’s value is greater than the queried value. In the below example, this
query will return all customers that have an age above 20.

SELECT * FROM customers


WHERE age > 20;
!> (Not greater than)
The !> symbol is used to filter results where a column’s value is not greater than the queried value. In the below example, this
query will return all customers that do not have an age above 20.

15 | Page
SELECT * FROM customers
WHERE age !> 20;
< (Less than)
The < symbol is used to filter results where a column’s value is less than the queried value. In the below example, this query
will return all customers that have an age below 20.

SELECT * FROM customers


WHERE age < 20;
!< (Not less than)
The !< symbol is used to filter results where a column’s value is not less than the queried value. In the below example, this
query will return all customers that do not have an age below 20.

SELECT * FROM customers


WHERE age !< 20;
>= (Greater than or equal to)
The >= symbol is used to filter results where a column’s value is greater than or equal to the queried value. In the below
example, this query will return all customers that have an age equal to or above 20.

SELECT * FROM customers


WHERE age >= 20;
<= (Less than or equal to)
The <= symbol is used to filter results where a column’s value is less than or equal to the queried value. In the below example,
this query will return all customers that have an age equal to or below 20.

SELECT * FROM customers


WHERE age <= 20;
<> (Not equal to)
The <> symbol performs the exact same operation as the != symbol and is used to filter results that do not equal a certain
value. You can use either, but <> is the SQL-92 standard.

SELECT * FROM customers


WHERE age <> 20;
Compound operators
Compound operators perform an operation on a variable and then set the result of the variable to the result of the operation.
Think of it as doing a = a (+,-,*,etc) b.

+= (Add equals)
The += operator will add a value to the original value and store the result in the original value. The below example sets a value
of 10, then adds 5 to the value and prints the result (15).

DECLARE @addValue int = 10


SET @addValue += 5
PRINT CAST(@addvalue AS VARCHAR);
This can also be used on strings. The below example will concatenate two strings together and print “dataquest”.

DECLARE @addString VARCHAR(50) = “data”

16 | Page
SET @addString += “quest”
PRINT @addString;
-= (Subtract equals)
The -= operator will subtract a value from the original value and store the result in the original value. The below example sets a
value of 10, then subtracts 5 from the value and prints the result (5).

DECLARE @addValue int = 10


SET @addValue -= 5
PRINT CAST(@addvalue AS VARCHAR);
*= (Multiply equals)
The *= operator will multiple a value by the original value and store the result in the original value. The below example sets a
value of 10, then multiplies it by 5 and prints the result (50).

DECLARE @addValue int = 10


SET @addValue *= 5
PRINT CAST(@addvalue AS VARCHAR);
/= (Divide equals)
The /= operator will divide a value by the original value and store the result in the original value. The below example sets a
value of 10, then divides it by 5 and prints the result (2).

DECLARE @addValue int = 10


SET @addValue /= 5
PRINT CAST(@addvalue AS VARCHAR);
%= (Modulo equals)
The %= operator will divide a value by the original value and store the remainder in the original value. The below example
sets a value of 25, then divides by 5 and prints the result (0).

DECLARE @addValue int = 10


SET @addValue %= 5
PRINT CAST(@addvalue AS VARCHAR);
Logical operaLogical operators are those that return true or false, such as the AND operator, which returns true when both
expressions are met.

ALL
The ALL operator returns TRUE if all of the subquery values meet the specified condition. In the below example, we are
filtering all users who have an age that is greater than the highest age of users in London.

SELECT first_name, last_name, age, location


FROM users
WHERE age > ALL (SELECT age FROM users WHERE location = ‘London’);
ANY/SOME
The ANY operator returns TRUE if any of the subquery values meet the specified condition. In the below example, we are
filtering all products which have any record in the orders table. The SOME operator achieves the same result.

SELECT product_name
FROM products

17 | Page
WHERE product_id > ANY (SELECT product_id FROM orders);
AND
The AND operator returns TRUE if all of the conditions separated by AND are true. In the below example, we are filtering
users that have an age of 20 and a location of London.

SELECT *
FROM users
WHERE age = 20 AND location = ‘London’;
BETWEEN
The BETWEEN operator filters your query to only return results that fit a specified range.

SELECT *
FROM users
WHERE age BETWEEN 20 AND 30;
EXISTS
The EXISTS operator is used to filter data by looking for the presence of any record in a subquery.

SELECT name
FROM customers
WHERE EXISTS
(SELECT order FROM ORDERS WHERE customer_id = 1);
IN
The IN operator includes multiple values set into the WHERE clause.

SELECT *
FROM users
WHERE first_name IN (‘Bob’, ‘Fred’, ‘Harry’);
LIKE
The LIKE operator searches for a specified pattern in a column. (For more information on how/why the % is used here, see the
section on the wildcard character operator).

SELECT *
FROM users
WHERE first_name LIKE ‘%Bob%’;
NOT
The NOT operator returns results if the condition or conditions are not true.

SELECT *
FROM users
WHERE first_name NOT IN (‘Bob’, ‘Fred’, ‘Harry’);
OR
The OR operator returns TRUE if any of the conditions separated by OR are true.In the below example, we are filtering users
that have an age of 20 or a location of London.

SELECT *
FROM users

18 | Page
WHERE age = 20 OR location = ‘London’;
IS NULL
The IS NULL operator is used to filter results with a value of NULL.

SELECT *
FROM users
WHERE age IS NULL;
String operators
String operators are primarily used for string concatenation (combining two or more strings together) and string pattern
matching.

+ (String concatenation)
The + operator can be used to combine two or more strings together. The below example would output ‘dataquest’.

SELECT ‘data’ + ‘quest’;


+= (String concatenation assignment)
The += is used to combine two or more strings and store the result in the original variable. The below example sets a variable
of ‘data’, then adds ‘quest’ to it, giving the original variable a value of ‘dataquest’.

DECLARE @strVar VARCHAR(50)


SET @strVar = ‘data’
SET @strVar += ‘quest’
PRINT @strVar;
% (Wildcard)
The % symbol - sometimes referred to as the wildcard character - is used to match any string of zero or more characters. The
wildcard can be used as either a prefix or a suffix. In the below example, the query would return any user with a first name that
starts with ‘dan’.

SELECT *
FROM users
WHERE first_name LIKE ‘dan%’;
[] (Character(s) matches)
The [] is used to match any character within the specific range or set that is specified between the square brackets. In the below
example, we are searching for any users that have a first name that begins with a d and a second character that is somewhere in
the range c to r.

SELECT *
FROM users
WHERE first_name LIKE ‘d[c-r]%’’;
[^] (Character(s) not to match)
The [^] is used to match any character that is not within the specific range or set that is specified between the square brackets.
In the below example, we are searching for any users that have a first name that begins with a d and a second character that is
not a.

SELECT *
FROM users

19 | Page
WHERE first_name LIKE ‘d[^a]%’’;
_ (Wildcard match one character)
The _ symbol - sometimes referred to as the underscore character - is used to match any single character in a string comparison
operation. In the below example, we are searching for any users that have a first that begins with a d and has a third character
that is n. The second character can be any letter.

SELECT *
FROM users
WHERE first_name LIKE ‘d_n%’;

Types of Built-in Functions


SQL Server supports numerous built-in functions. Some of these are specific to a particular set of functionality. For instance,
rowset functions can be used only with full-text search, XML strings, or linked servers. Similarly, math functions (not
surprisingly) are helpful mainly in applications that have to perform mathematical calculations.

Other functions can be used in a variety of situations. Following is a list of function types that should contain almost every
supported built-in function:

● Aggregate (SUM, AVG, MIN, MAX, and so on)

● System (CURRENT_USER, HOST_ID, ISNULL, NULLIF, and so on)

● System Statistical (@@CONNECTIONS, @@CPU_BUSY, and so on)

● Metadata (COL_NAME, DB_ID, DB_NAME, and so on)

● Configuration (@@DATEFIRST, @@LANGUAGE, and so on)

● Date (GETDATE, DATEADD, and so on)

● Math (COS, TAN, SQUARE, and so on)

● Text (PATINDEX, TEXTPTR, and so on)

● String (SUBSTRING, LEFT, CHARINDEX, and so on)

● Rowset (OPENQUERY, OPENXML, CONTAINS, and so on)

● Cursor (@@CURSOR_ROWS, @@FETCH_STATUS, and so on)

● Security (HAS_DBACCESS, SUSER_NAME, and so on)

20 | Page
Experiment-3

Implementation of different types of joins with suitable examples

SQL Join statement is used to combine data or rows from two or more tables based on a common field between
them. Different types of Joins are as follows:
● INNER JOIN

● LEFT JOIN
● RIGHT JOIN
● FULL JOIN

Consider the two tables below:


Student

StudentCourse

The simplest Join is INNER JOIN.


A. INNER JOIN
21 | Page
The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This keyword will create
the result-set by combining all rows from both the tables where the condition satisfies i.e value of the common field will be the
same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is the same as INNER JOIN.

Example Queries(INNER JOIN)


This query will show the names and age of students enrolled in different courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

B. LEFT JOIN

22 | Page
This join returns all the rows of the table on the left side of the join and matches rows for the table on the right side of the join.
For the rows for which there is no matching row on the right side, the result-set will contain null. LEFT JOIN is also known as
LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;
table1: First table.
table2: Second table
matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

Example Queries(LEFT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

C. RIGHT JOIN
23 | Page
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join and matching
rows for the table on the left side of the join. For the rows for which there is no matching row on the left side, the result-set
will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.

Example Queries(RIGHT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

24 | Page
D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set will contain all
the rows from both tables. For the rows for which there is no matching, the result-set will contain NULL values.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Example Queries(FULL JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID

25 | Page
FROM Student
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID

HARSH 1

PRATIK 2

RIYANKA 2

DEEP 3

SAPTARSHI 1

DHANRAJ NULL

ROHIT NULL

NIRAJ NULL

NULL 4

NULL 5

NULL 4

Experiment-4

26 | Page
Create views, partitions, Sequence, Indexes and locks for a particular DB

What is a database table partitioning?


Partitioning is the database process where very large tables are divided into multiple smaller parts. By splitting a large table
into smaller, individual tables, queries that access only a fraction of the data can run faster because there is less data to scan.
The main goal of partitioning is to aid in maintenance of large tables and to reduce the overall response time to read and load
data for particular SQL operations.
Vertical Partitioning on SQL Server tables
Vertical table partitioning is mostly used to increase SQL Server performance especially in cases where a query retrieves all
columns from a table that contains a number of very wide text or BLOB columns. In this case to reduce access times the
BLOB columns can be split to its own table. Another example is to restrict access to sensitive data e.g. passwords, salary
information etc. Vertical partitioning splits a table into two or more tables containing different columns:

An example of vertical partitioning


An example for vertical partitioning can be a large table with reports for employees containing basic information, such as
report name, id, number of reports and a large column with report description. Assuming that ~95% of users are searching on
the part of the report name, number, etc. and that only ~5% of requests are opening the reports description field and looking at
the description. Let’s assume that all those searches will lead to the clustered index scans and since the index scan reads all
rows in the table the cost of the query is proportional to the total number of rows in the table and our goal is to minimize the
number of IO operations and reduce the cost of the search.

Let’s see the example on the EmployeeReports table:

REATE TABLE EmployeeReports

eportID int IDENTITY (1,1) NOT NULL,


eportName varchar (100),
eportNumber varchar (20),
eportNumber varchar (20),
ONSTRAINT EReport_PK PRIMARY KEY CLUSTERED (ReportID)
ET @i = 1

EGIN TRAN
WHILE @i&lt;100000
EGIN

27 | Page
NSERT INTO EmployeeReports

eportName,
eportNumber,
eportDescription

ALUES

ReportName',
ONVERT (varchar (20), @i),
EPLICATE ('Report', 1000)

ET @i=@GOi+1
ND
OMMIT TRAN

If we run a SQL query to pull ReportID, ReportName, ReportNumber data from the EmployeeReports table the result set that a
scan count is 5 and represents a number of times that the table was accessed during the query, and that we had 113,288 logical
reads that represent the total number of page accesses needed to process the query:

SET STATISTICS IO ON
SET STATISTICS TIME ON
SELECT er.ReportID, er.ReportName, er.ReportNumber
FROM dbo.EmployeeReports er
WHERE er.ReportNumber LIKE '%33%'

28 | Page
SET STATISTICS IO OFF
SET STATISTICS TIME OFF

As indicated, every page is read from the data cache, whether or not it was necessary to bring that page from disk into the
cache for any given read. To reduce the cost of the query we will change the SQL Server database schema and split
the EmployeeReports table vertically.

Next we’ll create the ReportsDesc table and move the large ReportDescription column, and the ReportsData table and move all
data from the EmployeeReports table except the ReportDescription column:

CREATE TABLE ReportsDesc


( ReportID int FOREIGN KEY REFERENCES EmployeeReports (ReportID),
ReportDescription varchar(max)
CONSTRAINT PK_ReportDesc PRIMARY KEY CLUSTERED (ReportID)
)

CREATE TABLE ReportsData


(
ReportID int NOT NULL,
ReportName varchar (100),
ReportNumber varchar (20),

CONSTRAINT DReport_PK PRIMARY KEY CLUSTERED (ReportID)


)

29 | Page
INSERT INTO dbo.ReportsData
(
ReportID,
ReportName,
ReportNumber
)
SELECT er.ReportID,
er.ReportName,
er.ReportNumber
FROM dbo.EmployeeReports er

The same search query will now give different results:


SET STATISTICS IO ON
SET STATISTICS TIME ON
SELECT er.ReportID, er.ReportName, er.ReportNumber
FROM ReportsData er
WHERE er.ReportNumber LIKE '%33%'
SET STATISTICS IO OFF
SET STATISTICS TIME OFF

30 | Page
Vertical partitioning on SQL Server tables may not be the right method in every case. However, if you have, for example, a
table with a lot of data that is not accessed equally, tables with data you want to restrict access to, or scans that return a lot of
data, vertical partitioning can help.
Horizontal Partitioning on SQL Server tables
Horizontal partitioning divides a table into multiple tables that contain the same number of columns, but fewer rows. For
example, if a table contains a large number of rows that represent monthly reports it could be partitioned horizontally into
tables by years, with each table representing all monthly reports for a specific year. This way queries requiring data for a
specific year will only reference the appropriate table. Tables should be partitioned in a way that queries reference as few
tables as possible.

Tables are horizontally partitioned based on a column which will be used for partitioning and the ranges associated to each
partition. Partitioning column is usually a datetime column but all data types that are valid for use as index columns can be
used as a partitioning column, except a timestamp column. The ntext, text, image, xml, varchar(max), nvarchar(max), or
varbinary(max), Microsoft .NET Framework common language runtime (CLR) user-defined type, and alias data type columns
cannot be specified.
There are two different approaches we could use to accomplish table partitioning. The first is to create a new partitioned table
and then simply copy the data from your existing table into the new table and do a table rename. The second approach is to
partition an existing table by rebuilding or creating a clustered index on the table.

31 | Page
An example of horizontal partitioning with creating a new partitioned table
SQL Server 2005 introduced a built-in partitioning feature to horizontally partition a table with up to 1000 partitions in SQL
Server 2008, and 15000 partitions in SQL Server 2012, and the data placement is handled automatically by SQL Server. This
feature is available only in the Enterprise Edition of SQL Server.
To create a partitioned table for storing monthly reports we will first create additional filegroups. A filegroup is a logical
storage unit. Every database has a primary filegroup that contains the primary data file (.mdf). An additional, user-defined,
filegroup can be created to contain secondary files (.ndf). We will create 12 filegroups for every month:
1 ALTER DATABASE
PartitioningDB
2
ADD FILEGROUP January
3
GO
4
ALTER DATABASE
5 PartitioningDB
6 ADD FILEGROUP February
7 GO
8 ALTER DATABASE
PartitioningDB
9
ADD FILEGROUP March
10
GO
11
ALTER DATABASE
12
PartitioningDB
13
ADD FILEGROUP April
14
GO
15
ALTER DATABASE
16 PartitioningDB

17 ADD FILEGROUP May

18 GO

19 ALTER DATABASE
PartitioningDB
20
ADD FILEGROUP June
21
GO
22
ALTER DATABASE

32 | Page
PartitioningDB
ADD FILEGROUP July
GO
ALTER DATABASE
23 PartitioningDB
24 ADD FILEGROUP Avgust
25 GO
26 ALTER DATABASE
PartitioningDB
27
ADD FILEGROUP September
28
GO
29
ALTER DATABASE
30
PartitioningDB
31
ADD FILEGROUP October
32
GO
33
ALTER DATABASE
34 PartitioningDB

35 ADD FILEGROUP November

C36 GO
ALTER DATABASE
PartitioningDB
ADD FILEGROUP December
GO
To check created and available file groups in the current database run the following query:
SELECT name AS AvailableFilegroups
FROM sys.filegroups
WHERE type = 'FG'

33 | Page
Views
CREATING VIEWS
We can create View using CREATE VIEW statement. A View can be created from a single table or multiple tables. Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

view_name: Name for the View


table_name: Name of the table
condition: Condition to select rows
Examples:
Creating View from a single table:
● In this example we will create a View named DetailsView from the table StudentDetails. Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM StudentDetails
WHERE S_ID < 5;

● 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:

34 | Page
● In this example, we will create a view named StudentNames from the table StudentDetails. Query:
CREATE VIEW StudentNames AS
SELECT S_ID, NAME
FROM StudentDetails
ORDER BY NAME;

● If we now query the view as,


SELECT * FROM StudentNames;
Output:

● Creating View from multiple tables: 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:
CREATE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

● To display data of View MarksView:


SELECT * FROM MarksView;

● Output:

35 | Page
LISTING ALL VIEWS IN A DATABASE
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 (Using SHOW FULL TABLES):
use "database_name";
show full tables where table_type like "%VIEW";
Syntax (Using information_schema) :
select * from information_schema.views where table_schema = "database_name";

OR

select table_schema,table_name,view_definition from information_schema.views where table_schema = "database_name";

DELETING VIEWS
We have learned about creating a View, but what if a created View is not needed any more? Obviously we will want to delete
it. SQL allows us to delete an existing View. We can delete or drop a View using the DROP statement. Syntax:
DROP VIEW view_name;

view_name: Name of the View which we want to delete.


For example, if we want to delete the View MarksView, we can do this as:
DROP VIEW MarksView;
UPDATING VIEWS
There are certain conditions needed to be satisfied to update a view. If any one of these conditions is not met, then we will not
be allowed to update the view.
1. The SELECT statement which is used to create the view should not include GROUP BY clause or ORDER BY clause.
2. The SELECT statement should not have the DISTINCT keyword.
3. The View should have all NOT NULL values.
4. The view should not be created using nested queries or complex queries.
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.
● We can use the CREATE OR REPLACE VIEW statement to add or remove fields from a view. Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,column2,..

36 | Page
FROM table_name
WHERE condition;

● For example, if we want to update the view MarksView and add the field AGE to this View from StudentMarks Table, we
can do this as:
CREATE OR REPLACE VIEW MarksView AS
SELECT StudentDetails.NAME, StudentDetails.ADDRESS, StudentMarks.MARKS, StudentMarks.AGE
FROM StudentDetails, StudentMarks
WHERE StudentDetails.NAME = StudentMarks.NAME;

● If we fetch all the data from MarksView now as:


SELECT * FROM MarksView;

● Output:
● Inserting a row in a view: 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.
Syntax:
INSERT INTO view_name(column1, column2 , column3,..)
VALUES(value1, value2, value3..);

view_name: Name of the View


Example: 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”.
INSERT INTO DetailsView(NAME, ADDRESS)
VALUES("Suresh","Gurgaon");

● If we fetch all the data from DetailsView now as,


SELECT * FROM DetailsView;
Output:

37 | Page
● Deleting a row from a View: 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.
Syntax:
DELETE FROM view_name
WHERE condition;

view_name:Name of view from where we want to delete rows


condition: Condition to select rows
Example: In this example, we will delete the last row from the view DetailsView which we just added in the above example of
inserting rows.
DELETE FROM DetailsView
WHERE NAME="Suresh";

● If we fetch all the data from DetailsView now as,


SELECT * FROM DetailsView;
Output:

Sequences

Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to produce unique values
on demand.

38 | Page
● A sequence is a user defined schema bound object that generates a sequence of numeric values.
● Sequences are frequently used in many databases because many applications require each row in a table to contain a unique
value and sequences provide an easy way to generate them.
● The sequence of numeric values is generated in an ascending or descending order at defined intervals and can be
configured to restart when exceeds max_value.
Syntax:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;

sequence_name: Name of the sequence.

initial_value: starting value from where the sequence starts.


Initial_value should be greater than or equal
to minimum value and less than equal to maximum value.

increment_value: Value by which sequence will increment itself.


Increment_value can be positive or negative.

minimum_value: Minimum value of the sequence.


maximum_value: Maximum value of the sequence.

cycle: When sequence reaches its set_limit


It starts from the beginning.

nocycle: An exception will be thrown


if the sequence exceeds its max_value.
Example
Following is the sequence query creating sequence in ascending order.

● Example 1:
● CREATE SEQUENCE sequence_1

● start with 1

● increment by 1

● minvalue 0

39 | Page
● maxvalue 100

● cycle;

Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by 1 having
maximum value 100. Sequence will repeat itself from start value after exceeding 100.
● Example 2:
Following is the sequence query creating sequence in descending order.
● CREATE SEQUENCE sequence_2

● start with 100

● increment by -1

● minvalue 1

● maxvalue 100

● cycle;

Above query will create a sequence named sequence_2.Sequence will start from 100 and should be less than or equal to
maximum value and will be incremented by -1 having minimum value 1.
● Example to use sequence : create a table named students with columns as id and name.

● CREATE TABLE students

● (

● ID number(10),

● NAME char(20)

● );

Now insert values into table


INSERT into students VALUES(sequence_1.nextval,'Ramesh');
INSERT into students VALUES(sequence_1.nextval,'Suresh');
where sequence_1.nextval will insert id in id column in a sequence as defined in sequence_1.
Output:
______________________
| ID | NAME |
------------------------
| 1 | Ramesh |

40 | Page
| 2 | Suresh |
----------------------

Experiment-5

Implement different types of constraints on relations

A constraint is a rule that is used for optimization purposes.

Constraints can be categorized into five types:

● A NOT NULL constraint is a rule that prevents null values from being entered into one or more columns within a table.
● A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more
columns within a table. Unique and primary keys are the supported unique constraints. For example, a unique
constraint can be defined on the supplier identifier in the supplier table to ensure that the same supplier identifier is not
given to two suppliers.
● A primary key constraint is a column or combination of columns that has the same properties as a unique constraint.
You can use a primary key and foreign key constraints to define relationships between tables.
constraint (also referred to as a referential constraint or a referential integrity constraint) is a logical rule about values in one
mns in one or more tables. For example, a set of tables shares information about a corporation's suppliers. Occasionally, a
me changes. You can define a referential constraint that states the ID of the supplier in a table must match a supplier ID in the
mation. This constraint prevents insert, update, or delete operations that would otherwise result in missing supplier information.
e check constraint (also called a check constraint) sets restrictions on data that is added to a specific table. For example, you
e a table check constraint whenever salary data is added or updated in a table that contains personal information. For such
ions, the table check constraint can ensure that the salary level for an employee is at least $20 000.

An informational constraint is an attribute of a certain type of constraint, but the attribute is not enforced by the database
manager.

● NOT NULL constraints


NOT NULL constraints prevent null values from being entered into a column.OT
● Unique constraints
Unique constraints ensure that the values in a set of columns are unique and not null for all rows in the table. The
columns specified in a unique constraint must be defined as NOT NULL. The database manager uses a unique index to
enforce the uniqueness of the key during changes to the columns of the unique constraint.
● Primary key constraints
You can use primary key and foreign key constraints to define relationships between tables.
● (Table) Check constraints
A check constraint (also referred to as a table check constraint) is a database rule that specifies the values allowed in

41 | Page
one or more columns of every row of a table. Specifying check constraints is done through a restricted form of a search
condition.
● Foreign key (referential) constraints
Foreign key constraints (also known as referential constraints or referential integrity constraints) enable definition of
required relationships between and within tables.
● Informational constraints
An informational constraint is a constraint attribute that can be used by the SQL compiler to improve the access to
data. Informational constraints are not enforced by the database manager, and are not used for additional verification of
data; rather, they are used to improve query performance.

NOT NULL:

NOT NULL constraint makes sure that a column does not hold NULL value. When we don’t provide a value for a particular
column while inserting a record into a table, it takes a NULL value by default. By specifying

NULL constraint, we can be sure that a particular column(s) cannot have NULL values.

Example:

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (235),
PRIMARY KEY (ROLL_NO)
);
Read more about this constraint here.

UNIQUE:

UNIQUE Constraint enforces a column or set of columns to have unique values. If a column has a unique constraint, it means
that particular column cannot have duplicate values in a table.

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO)
);
Read more about it here.

42 | Page
createDEFAULT:

The DEFAULT constraint provides a default value to a column when there is no value provided while inserting a record into a
table.

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35) ,
PRIMARY KEY (ROLL_NO)
);
Read more: Default constraint create

CHECK:

This constraint is used for specifying a range of values for a particular column of a table. When this constraint is being set on a
column, it ensures that the specified column must have the value falling in the specified range.

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL CHECK(ROLL_NO >1000) ,
STU_NAME VARCHAR (35) NOT NULL,
STU_AGE INT NOT NULL,
EXAM_FEE INT DEFAULT 10000,
STU_ADDRESS VARCHAR (35) ,
PRIMARY KEY (ROLL_NO)
);
In the above example we have set the check constraint on the ROLL_NO column of the STUDENT table. Now, the
ROLL_NO field must have a value greater than 1000.

Key constraints:

KEY:

Primary key uniquely identifies each record in a table. It must have unique values and cannot contain nulls. In the below
example the ROLL_NO field is marked as primary key, that means the ROLL_NO field cannot have duplicate and null values.

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO)

43 | Page
);
FOREIGN KEY:

Foreign keys are the columns of a table that points to the primary key of another table. They act as a cross-reference between
tables.
Read more about it here.

Domain constraints:

Each table has a certain set of columns and each column allows the same type of data, based on its data type. The column does
not accept values of any other data type.
Domain constraints are user defined data type and we can define them like this:

Domain Constraint = data type + Constraints (NOT NULL / UNIQUE / PRIMARY KEY / FOREIGN KEY / CHECK /
DEFAULT)

Experiment-6

Implementation of subqueries and nested queries

A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow

● Subqueries must be enclosed within parentheses.


● A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the
subquery to compare its selected columns.
● An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP
BY command can be used to perform the same function as the ORDER BY in a subquery.
● Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.

● The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB.
● A subquery cannot be immediately enclosed in a set function.
● The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the
subquery.
intSubqueries with the SELECT Statement
Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows

44 | Page
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])
Example
Consider the CUSTOMERS table having the following records
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Now, let us check the following subquery with a SELECT statement.
SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY > 4500) ;
This would produce the following result.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
Subqueries with the INSERT Statement
Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to
insert into another table. The selected data in the subquery can be modified with any of the character, date or number
functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
45 | Page
[ WHERE VALUE OPERATOR ]
Example
Consider a table CUSTOMERS_BKP with a similar structure as CUSTOMERS table. Now to copy the complete
CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
Subqueries with the UPDATE Statement
The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be
updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following
example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal
to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
deSubqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.

46 | Page
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
Example
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following
example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Nested subqueries

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 returns intermediate results. SQL executes the
innermost subquery first, then the next level. See the following examples :

Example -1 : Nested subqueries

If we want to retrieve that unique job_id and there average salary from the employees table which unique job_id have a salary
is smaller than (the maximum of averages of min_salary of each unique job_id from the jobs table which job_id are in the list,
picking from (the job_history table which is within the department_id 50 and 100)) the following SQL statement can be used :

SQL Code:

dry)

FROM employees

47 | Page
GROUP BY job_id

HAVING AVG(salary)<

(SELECT MAX(AVG(min_salary))

FROSELECT job_i,AVG(salaM jobs

WHERE job_id IN

(SELECT job_id FROM job_history

WHERE department_id

BETWEEN 50 AND 100)

GROUP BY job_id);

Copy
The above code is executed in Oracle 11g Express Edition.

orCREATE

SELECT job_id,AVG(salary)

SELECT job_id,AVG(salary)

FROM employees

GROUP BY job_id

HAVING AVG(salary)<

(SELECT MAX(myavg) from (select job_id,AVG(min_salary) as myavg

FROM jobs

WHERE job_id IN

(SELECT job_id FROM job_history

WHERE department_id

BETWEEN 50 AND 100)

GROUP BY job_id) ss);

Copy

48 | Page
The above code is executed in PostgreSQL 9.3

Output:

JOB_ID AVG(SALARY)
---------- -----------
IT_PROG 5760
AC_ACCOUNT 8300
ST_MAN 7280
AD_ASST 4400
SH_CLERK 3215
FI_ACCOUNT 7920
PU_CLERK 2780
SA_REP 8350
MK_REP 6000
ST_CLERK 2785
HR_REP 6500

Experiment-7

INSERT INTO movie_theaterSET

(theater_id, date, time, movie_name, movie_genre, guest_total, ticket_cost)

VALUES

Implement Queries on Group By & Having Clauses, ALIAS, Sequence By, Order By

IN

(4, '2022-05-27', '10:00:00', 'The Bad Guys', 'Animation', 83, 18.00),

(5, '2022-05-28', '09:00:00', pushpa ', 'Action', 112, 8.00),

(6, '2022-05-28', '09:00:00', 'Downton Abbey A New Era', 'Drama', 137, 8.00),

(7, '202(1, '2022-05-27', '10:00:00', 'pushpa’, 'Action', 131, 18.00),aZZAzaw22recs23e5r3dzdxewqw21r43r4

(2, '2022-05-27', '10:00:00', 'Downton Abbey A New Era', 'Drama', 90, 18.00),

49 | Page
(3, '2022-05-27', '10:00:00', 'Men', 'Horror', 100, 18.00),

2-05-28', '09:00:00', 'Men', 'Horror', 25, 8.00),

(8, '2022-05-28', '09:00:00', 'The Bad Guys', 'Animation', 142, 8.00),

(9, '2022-05-28', '05:00:00', 'pushpa', 'Action', 150, 13.00),

(10, '2022-05-28', '05:00:00', 'Downton Abbey A New Era', 'Drama', 118, 13.00),

(11, '2022-05-28', '05:00:00', 'Men', 'Horror', 88, 13.00),

(12, '2022-05-28', '05:00:00', 'The Bad Guys', 'Animation', 130, 13.00);

SELECT column_1, AGGREGATE_FUNCTION(column_2) FROM table GROUP BY column_1;

SELECT * FROM movie_theater;

output:

+------------+------------+----------+-------------------------+-------------+-------------+-------------+

| theater_id | date af[ijkhphpotrhwhhihjh | time | movie_name | movie_genre | guest_total | ticket_cost |

+------------+------------+----------+-------------------------+-------------+-------------+-------------+

| 1 | 2022-05-27 | 10:00:00 | pushpa | Action | 131 | 18.00 |

| 2 | 2022-05-27 | 10:00:00 | Downton Abbey A New Era | Drama | 90 | 18.00 |

| 3 | 2022-05-27 | 10:00:00 | Men | Horror | 100 | 18.00 |

| 4 | 2022-05-27 | 10:00:00 | The Bad Guys | Animation | 83 | 18.00 |

| 5 | 2022-05-28 | 09:00:00 | pushpa | Action | 112 | 8.00 |

| 6 | 2022-05-28 | 09:00:00 | Downton Abbey A New Era | Drama | 137 | 8.00 |

| 7 | 2022-05-28 | 09:00:00 | Men | Horror | 25 | 8.00 |

| 8 | 2022-05-28 | 09:00:00 | The Bad Guys | Animation | 142 | 8.00 |

| 9 | 2022-05-28 | 05:00:00 | pushpa | Action | 150 | 13.00 |

50 | Page
| 10 | 2022-05-28 | 05:00:00 | Downton Abbey A New Era | Drama | 118 | 13.00 |

| 11 | 2022-05-28 | 05:00:00 | Men | Horror | 88 | 13.00 |

| 12 | 2022-05-28 | 05:00:00 | The Bad Guys | Animation | 130 | 13.00 |

+------------+------------+----------+-------------------------+-------------+-------------+-------------+

12 rows in set (0.00 sec)

Experiment-8
Control Structure
a. Write a PL/SQL block for Addition of Two Numbers
Declare
x number(5);

y number(5);
z number(7);

begin

-- Here we Assigning 10 into x


x:=10;

-- Assigning 20 into x declare


y:=20;

-- Assigning sum of x and y into z


z:=x+y;

-- Print the Result


dbms_output.put_line('Sum is '||z);
end;

output:
Sum is 30

b. Write a PL/SQL block for IF, IF and else condition

DECLARE

a number(3) := 100;

51 | Page
BEGIN

-- check the boolean condition using if statement

IF( a < 20 ) THEN

-- if condition is true then print the following

dbms_output.put_line('a is less than 20 ' );

ELSE

dbms_output.put_line('a is not less than 20 ' );

END IF;

dbms_output.put_line('value of a is : ' || a);

END;

Output:

a is not less than 20

value of a is : 100

PL/SQL procedure successfully completed.

c. Write a PL/SQL block for implementation of loops


/
Output:DECLARE

a number(2);

BEGIN

FOR a in 10 .. 20 LOOP

dbms_output.put_line('value of a: ' || a); set

END LOOP;

END;

52 | Page
/

value of a: 10

value of a: 11

value of a: 12 s

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

value of a: 20

PL/SQL procedure successfully completed.

d. Write a PL/SQL block for greatest of three numbers using IF and ELSEIF
nprevious chapters

DEset CLARE

c_id customers.id%type := 8;

c_name customerS.Name%type;

c_addr customers.address%type;

BEGIN

SELECT name, address INTO c_name, c_addr

FROM customers

WHERE id = c_id;

53 | Page
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);

DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION

WHEN no_data_found THEN

dbms_output.put_line('No such customer!');

WHEN others THEN

dbms_output.put_line('Error!');

END;

/umber(5)

declare x numbeYBHUJHY,ŚḌĒKW78Er(5);
z numbernumber(7);

begin

-- Here we Assigning 10 into x


x:=10;

-- Assigning 20 into x declarey:=20;

-- Assigning sum of x and y into z


z:=x+y;

-- Print the Result


db/

ms_output.put_line('Sum is '||z);
end;

54 | Page
Output:

Greatest number is 67

Exception Handling- Implement the following with respect to exception handling. Raising Exceptions, User Defined
Exceptions, Pre-Defined Exceptions

Syntax for Exception Handling

The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The def

DECLARE

........

WHEN others THEN

exception-handling-statements

END;

Example

Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the

When the above code is executed at the SQL prompt, it produces the following result

No such customer!

PL/SQL procedure successfully completed.

Experiment-10

Write PL/SQL block for an application using exception handling Procedures


a)Write a PL/SQL Procedure using Positional Parameters

55 | Page
DECLARE

a number;

b number;

c number;

PROCEDURE findMin(x IN number, y IN number, z OUT number) IS

BEGIN

IF x < y THEN

z:= x;

ELSE

z:= y;

END IF;

END;

BEGIN

a:= 23;

b:= 45;

findMin(a, b, c);

dbms_output.put_line(' Minimum of (23, 45) : ' || c);

END;

Output:

Minimum of (23, 45) : 23

PL/SQL procedure successfully completed

b. Write a PL/SQL Procedure using notational parameters

DECLARE

56 | Page
l_vc_dept VARCHAR2(30);

l_n_sal NUMBER;

BEGIN

l_n_sal:=func_emp(7815,'John','13-June-2011',l_vc_dept);

dbms_output.put_line('The Employee''s dept is '||l_vc_dept);

dbms_output.put_line('The Employee''s sal is '||l_n_sal);

END;

c. Write a PL/SQL Procedure for GCD Numbers

||' is '

||num1);DECLARE

-- declare variable num1, num2 and t

-- and these three variables data type are integer

num1 INTEGER;

num2 INTEGER;

t INTEGER;

BEGIN

num1 := 8;

num2 := 48;

WHILE MOD(num2, num1) != 0 LOOP

t := MOD(num2, num1);

num2 := num1;

57 | Page
num1 := t;

END LOOP;

dbms_output.Put_line('GCD of '

||num1

||' and '

||num2

END;

-- Program End

Output:

GCD of 8 and 48 is 8

Select * from customers;

+----+----------+-----+-----------+----------+

| ID | NAME | AGE | ADDRESS | SALARY |

+----+----------+-----+-----------+----------+

| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |

| 2 | Khilan | 25 | Delhi | 1500.00 |

| 3 | kaushik | 23 | Kota | 2000.00 |

| 4 | Chaitali | 25 | Mumbai | 6500.00 |

| 5 | Hardik | 27 | Bhopal | 8500.00 |

58 | Page
| 6 | Komal | 22 | MP | 4500.00 |

+----+----------+-----+-----------+----------+

DECLARE

total_rows number(2);

BEGIN

UPDATE customers

SET salary = salary + 500;

IF sql%notfound THEN

dbms_output.put_line('no customers selected');

ELSE IF sql%found THEN

total_rows := sql%rowcount;

dbms_output.put_line( total_rows || ' customers selected ');

END IF;

END;

Output:

6 customers selected

Explicit cursors:

DECLARE

c_id customers.id%type;

c_name customers.name%type; ```

c_addr customers.address%type;

59 | Page
CURSOR c_customers is

SELECT id, name, address FROM customers;

BEGIN

OPEN c_customers;

LOOP

FETCH c_customers into c_id, c_name, c_addr;

EXIT WHEN c_customers%notfound;

dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);

END LOOP;

CLOSE c_customers;

END;

Output:

1 Ramesh Ahmedabad

2 Khilan Delhi

3 kaushik Kota

4 Chaitali Mumbai

5 Hardik Bhopal

6 Komal MP

Experiment-11

Functions:

a)Write a PL/SQL block to implement factorial using functions

declare

-- it gives the final answer after computation

60 | Page
fac number :=1;

-- given number n

-- taking input from user

n number := &1;

-- start blockfac

begin

-- start while loop

while n > 0 loop

-- multiple with n and decrease n's value

fac:=n*fac;

n:=n-1;

end loop;

-- end loop

-- print result of fac

dbms_output.put_line(fac);

-- end the begin block

end;

Output:

120

Experiment-12
Write a PL/SQL function to search an address from the given database

SQL> select * from emp where deptno = 10;

61 | Page
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

---------- ---------- --------- ---------- -------- ---------- ---------- ----------

7782 CLARK MANAGER 7839 09.06.81 2450 10

7839 KING PRESIDENT 17.11.81 10000 10

7934 MILLER CLERK 7782 23.01.82 1300 10

SQL> create or replace function f_emp (par_empno in emp.empno%type)

2 return emp.job%type

3 is

4 retval emp.job%type;

5 begin

6 select e.job

7 into retval

8 from emp e

9 where e.empno = par_empno;

10

11 return retval;

12

13 exception

14 when no_data_found then

15 return 'No such employee';

16 end;

17 /

62 | Page
Function created.

SQL> select f_emp(7782) result from dual;

RESULT

---------------------------------------------------------------------------------------------

MANAGER

Experiment-13

To create a trigger we need to use the CREATE TRIGGER statement.

In this code section you will see the basic CREATE TRIGGER syntax.

CREATE TRIGGER trigger_name


ON { Table name or view name }
{ FOR | AFTER | INSTEAD OF }
{ [INSERT], [UPDATE] , [DELETE] }

Additionally the next table describes each of the arguments of the CREATE TRIGGER syntax.

Argument Description
Indicates when the trigger must fire. FOR or AFTER
occurs after the insert, delete or update occurs. INSTEAD
FOR | AFTER | INSTEAD OF
OF occurs instead of the insert, delete or update operation
from occurring.
[INSERT], [UPDATE], [DELETE The DML event (or list of events) that will cause the
] trigger to fire.

Let's create a sample table, so we can create our first trigger.

USE [SampleDB]

63 | Page
GO

INSERT INTO dbo.Employees


(
EmployeeName,
EmployeeAddress,
MonthSalary
)
VALUES
( 'Mark Smith',
'Ocean Dr 1234',
10000
),
( 'Joe Wright',
'Evergreen 1234',
10000
),
( 'John Doe',
'International Dr 1234',
10000
),
( 'Peter Rodriguez',
'74 Street 1234',
10000
);

In the code below you will see the most basic DML trigger we can make, which will return "Hello World". This trigger will
show a "Hello World!" line every time a row is added to the Employees table.

USE [SampleDB]
GO
CREATE TRIGGER [dbo].[TR_Employees] ON [dbo].[Employees]
FOR INSERT
AS
SELECT 'Hello World!'
GO

In order to test this trigger we need to insert some data into the Employees table. We can do so with the next script.

SELECT * FROM dbo.Employees


GO

64 | Page
INSERT INTO dbo.Employees ( EmployeeName , EmployeeAddress ,MonthSalary )
VALUES ( 'Paul Martinez' , '22 Street 4217', 4000)
GO

SELECT * FROM dbo.Employees


GO

On the next image you can see the execution of the previous script. Notice that when the INSERT statement executes it prints a
"Hello World!" message.

b. Write a Trigger to check the age valid or not Using Message Alert.

trigger DateofBirth on Account (before insert,before update) {


for(Account ac:trigger.new){
Date a = Date.today();
Date startDate = Date.valueOf(ac.birthdate__c);
Integer numberDaysDue = integer.valueOf(startDate.daysBetween(a));
Integer age = numberDaysDue/365;
if(age <= 18){
system.debug('Test ::' + age);
ac.addError('Age should be more than 18');
}
}
}

c. Create a Trigger to Raise appropriate error code and error message.

create or replace trigger deny_dec_pu before update of PU on ARTICLE


for each row
declare
erreur pu exception;
begin

*insert into error values ('Operation de MAJ',sysdate);*

-- this instruction is never executec why ?

if (:new.pu < :old.pu) then


raise erreur pu ;
end if;
exception
when erreur_pu then
Raise_application_error(-20100, 'rrrrrrrr', FALSE);

end;

65 | Page
Experiment-14

Write PL/SQL block for an application using cursors and all types of triggers.
DECLARE
CURSOR dpt_cur IS
SELECT d.department_id id,
department_name deptname,
city,
Nvl(first_name, '...') manager
FROM departments d

left outer join employees E


ON ( d.manager_id = e.employee_id )
join locations l USING(location_id)
ORDER BY 2;
emp_name employees.first_name%TYPE;
emp_max_salary employees.salary%TYPE;
BEGIN
FOR dept_all IN dpt_cur LOOP
SELECT Max(salary)
INTO emp_max_salary
FROM employees
WHERE department_id = dept_all.id;

IF emp_max_salary IS NULL THEN


emp_name := '...';
ELSE
SELECT first_name
INTO emp_name
FROM employees
WHERE department_id = dept_all.id
AND salary = emp_max_salary;
END IF;

dbms_output.Put_line(Rpad(dept_all.dptname, 20)
|| Rpad(dept_all.manager, 15)
|| Rpad(dept_all.city, 20)
|| Rpad(emp_name, 20));
END LOOP;

END;
/

Output:
SQL> /
66 | Page
Accounting Shelley Seattle Shelley
Administration Jennifer Seattle Jennifer
Benefits ... Seattle ...
Construction ... Seattle ...
Contracting ... Seattle ...
Control And Credit ... Seattle ...
Corporate Tax ... Seattle ...
Executive Steven Seattle Steven
Finance Nancy Seattle Nancy
Government Sales ... Seattle ...
Human Resources Susan London Susan
IT Alexander Southlake Alexander
IT Helpdesk ... Seattle ...
IT Support ... Seattle ...
Manufacturing ... Seattle ...
Marketing Michael Toronto Michael
NOC ... Seattle ...
Operations ... Seattle ...
Payroll ... Seattle ...
Public Relations Hermann Munich Hermann
Purchasing Den Seattle Den
Recruiting ... Seattle ...
Retail Sales ... Seattle ...
Sales John Oxford John
Shareholder Services... Seattle ...
Shipping Adam South San Francisco Adam
Treasury ... Seattle ...

PL/SQL procedure successfully completed.

Experiment-15

Write a PL/SQL block for transaction operations of a typical application using package

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;

67 | Page
/

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSE IF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/

Output:
Old salary: 20000
New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000
Old salary: 30000
New salary: 35000
Salary difference: 5000
6 customers updated

68 | Page
69 | Page

You might also like