0% found this document useful (0 votes)
65 views44 pages

SQL Lab File (1-10) - Tushar-21scse2030128

This lab manual document provides information about an experiment on SQL. It includes: 1) Details about the faculty, academic year, semester, subject code, student name and enrollment number. 2) An introduction to SQL, databases, tables, records, DDL, DML and some basic SQL commands like SELECT, INSERT, UPDATE, DELETE. 3) An example of creating a database table and writing SQL queries to retrieve data from the table. 4) Descriptions of SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY and examples of how to implement them.
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)
65 views44 pages

SQL Lab File (1-10) - Tushar-21scse2030128

This lab manual document provides information about an experiment on SQL. It includes: 1) Details about the faculty, academic year, semester, subject code, student name and enrollment number. 2) An introduction to SQL, databases, tables, records, DDL, DML and some basic SQL commands like SELECT, INSERT, UPDATE, DELETE. 3) An example of creating a database table and writing SQL queries to retrieve data from the table. 4) Descriptions of SQL constraints like NOT NULL, UNIQUE, PRIMARY KEY and examples of how to implement them.
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/ 44

Lab Manual

Name of the Faculty: Dr T Poongodi

Academic year 2021-23


Semester 1
Section 2
Subject code MCAS1141
Student Name Tushar Bhartiya
Enrolment Number 21SCSE2030128
`
Date: 21th October 2021

EXPERIMENT 1:

SQL(Structured Query Language)


 SQL is stands for Structured Query Language.
 SQL is a standard language for accessing and manipulating databases.
 SQL is used to perform operations on the records stored in the database, such
as updating records, inserting records, deleting records, creating and
modifying database tables, views, etc.

 It allows the data professionals and users to retrieve the data from the
relational database management systems.
 It also helps in creating the view, stored procedure, and functions in the
relational database.

Here are two types of SQL :-

1. DDL (Data Definition Language)


2. DML (Data Manipulation Language)

Database
 A database is a systematic collection of data.
 They support electronic storage and manipulation of data.
 Databases make data management easy.

Table
Table is a collection of data, organized in terms of rows and columns.

Record
A record is a data structure that can hold data items of diff erent kinds. Records

consist of diff erent fi elds, similar to a row of a database table.


DDL(Data Definition Language )  

 A data definition language (DDL) is a computer language used to create


and modify the structure of database objects in a database.

 DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
 All the command of DDL are auto-committed that means it permanently save
all the changes in the database.

Here are some commands that come under DDL:

o CREATE
o ALTER
o DROP

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

Syntax:-

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

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax:-

DROP TABLE table_name;  

c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.

Syntax:-
ALTER TABLE table_name ADD column_name COLUMN-definition;    

DML(Data Manipulation Language)


 DML commands are used to modify the database. It is responsible for all form
of changes in the database.
 The command of DML is not auto-committed that means it can't permanently
save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

o SELECT
o INSERT
o UPDATE
o DELETE

a. SELECT: Command to fetch data or values from the database.

Syntax:-

Select * FROM table_name

b. INSERT: It creates a record in the existing table.

Syntax:-

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

c. UPDATE: It modifies the existing record of the table.

Syntax:-
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE CON
DITION]

d. DELETE: It deletes the records in the table and even delete the
complete table.

Syntax:-

DELETE FROM table_name [WHERE condition];  

Q1. Creation of a database and writing SQL queries to retrieve information from the
database.

create table students(

Roll int,

Name varchar(30),

Address varchar(30),

City varchar(30));

insert into students values(1,'Ishika','Ramna Road','Gaya');

insert into students values(2,'Sarika','Police Line','Gaya');

insert into students values(3,'Rahul','Bypass Road','Gaya');

insert into students values(4,'Kamalkant','Manpur Road','Gaya');

insert into students values(5,'Ritu','Delha','Gaya');

select * from students;

ALTER TABLE students

ADD surname;

UPDATE students

SET surname= 'Singh' WHERE Roll=2;


UPDATE students

SET surname= 'Gupta' WHERE Roll=1;

UPDATE students

SET surname= 'Kumar' WHERE Roll=3;

UPDATE students

SET surname= 'Prakash' WHERE Roll=4;

UPDATE students

SET surname= 'Ranjan' WHERE Roll=5;

select * from students;

DELETE from students WHERE Name='Ritu';

select * from students;


Date: 11th November 2021

EXPERIMENT 2(a):
1. SELECT DISTINCT:- It is used to return only distinct (different) values.

Syntax:-

SELECT DISTINCT column1,  column2, ...FROM table_name;

2. WHERE :- The WHERE clause is used to filter records. It is used to extract


only those records that fulfill a specified condition.

Syntax:-

SELECT column1,  column2, ...FROM table_name WHERE condition;

3. AND :- The AND operator displays a record if all the conditions separated


by AND are TRUE.

Syntax:-

SELECT  column1, column2,...FROM  table_name WHERE condition AND


condition2 AND condition3...;

4. OR :- The OR operator displays a record if any of the conditions


separated by OR is TRUE.

Syntax:-
SELECT column1, column2,..FROM  table_name WHERE condition1 OR
u condition2 OR condition3.. ;

5. ORDER BY:- The ORDER BY keyword is used to sort the result-set in


ascending or descending order.

Syntax:-

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


column2,... ASC|DESC;
6. MIN():- The MIN() function returns the smallest value of the selected
column.

Syntax:-

SELECT MIN(column_name)FROM table_name WHERE condition;

7. MAX():- The MAX() function returns the largest value of the selected


column.

Syntax:-

SELECT MAX(column_name) FROM table_name WHERE condition;

8. COUNT:- The COUNT() function returns the number of rows that matches


a specified criterion.

Syntax:-

SELECT COUNT(column_name)FROM table_name WHERE condition;

9. AVG():- The AVG() function returns the average value of a numeric


column. 

Syntax:-

SELECT AVG(column_name) FROM table_name WHERE condition;

10. SUM():- The SUM() function returns the total sum of a numeric column. 

Syntax:-

SELECT SUM(column_name) FROM table_name WHERE condition;

Q. Use All code

create table customer (cust_id integer(10),name varchar(30), City


varchar(45), Country varchar(45),Price integer(10));

insert into customer values(34,"Arun","Gaya","India",4587);

insert into customer values(24,"Gopal","Gaya","India",324);


insert into customer values(65,"Manoj","Delhi","India",888);

insert into customer values(55,"Arvind","Delhi","India",999);

insert into customer values(21,"Rajesh","Jodhpur","India",8765);

select * from customer;

select Country FROM customer;

select name FROM customer;

select DISTINCT City FROM customer;

select * from customer WHERE City='Gaya';

select * from customer WHERE Country='India' AND City='Delhi';

select * from customer WHERE City='Gaya' AND City='Delhi';

select * from customer WHERE NOT City='Delhi';

select MIN(Price) AS SmallestPrice FROM customer;

select MAX(Price) AS LargestPrice FROM customer;

select COUNT(cust_id) FROM customer;

select AVG(Price) FROM customer;

select SUM(Price) FROM customer;

OUTPUT:-
Date: 18th November 2021

EXPERIMENT 2(b):

SQL Constraints
 SQL constraints are used to specify rules for the
data in a table.
 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 constraint and the data
action, the action is aborted.
 The following constraints are commonly used in
SQL:

 NOT NULL - Ensures that a column cannot have a


NULL
 UNIQUE - Ensures that all values in a column are
different
 PRIMARY KEY - A combination of a NOT
NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy
links between tables
 CHECK - Ensures that the values in a column
satisfies a specific condition
 DEFAULT - Sets a default value for a column if no
value is specified
 CREATE INDEX - Used to create and retrieve data
from the database very quickly

NOT NULL Constraint


 By default, the columns are able to hold NULL values.
  A NOT NULL constraint in SQL is used to prevent inserting NULL
values into the specified column, considering it as a not accepted
value for that column. 

Example:-
CREATE TABLE student (
    ID int NOT NULL,
    FirstName varchar(80) NOT NULL,
    LastName varchar(80) NOT NULL,
    Age int );

SQL UNIQUE Constraint
The UNIQUE constraint in SQL is used to ensure that no duplicate values
will be inserted into a specific column or combination of columns that
are participating in the UNIQUE constraint and not part of the PRIMARY
KEY.

Example:-
create table person(Id int NOT NULL, FirstName varchar(124),
LastName varchar(124), Age int, UNIQUE(Id));

insert into person values (2,'Astha','Sharma',22);

insert into person values (2,'Aditi','Sharma',21);

insert into person values (3,'Ayushi','Sharma',15);

select * from person;

SQL  PRIMARY KEY  Constraint


 The PRIMARY KEY constraint uniquely identifies each
record in a table.
 Primary keys must contain UNIQUE values, and
cannot contain NULL values.
 A table can have only ONE primary key; and in the
table, this primary key can consist of single or
multiple columns (fields).

Example:-
CREATE TABLE Peoples (
    PersonID int NOT NULL,
    PersonName varchar(43) NOT NULL,
    Age int,

PRIMARY KEY(PersonID));

SQL FOREIGN KEY  Constraint


 The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
 A FOREIGN KEY is a field (or collection of fields) in one table, that refers
to the PRIMARY KEY in another table.
 The table with the foreign key is called the child table, and the table
with the primary key is called the referenced or parent table.

Example:-
CREATE TABLE Orders (
    OrderID int NOT NULL,
    OrderNumber int NOT NULL,

PersonID int,

PRIMARY KEY(OrderID),

FOREIGN KEY(PersonID) REFERENCES Peoples(PersonID));


SQL  CHECK  Constraint
 The CHECK constraint is used to limit the value
range that can be placed in a column.
 If you define a CHECK constraint on a column it will
allow only certain values for this column.
 If you define a CHECK constraint on a table it can
limit the values in certain columns based on values
in other columns in the row.

Example:-
CREATE TABLE Children (
    ID int NOT NULL,
    FirstName varchar(54),
    LastName varchar(54) NOT NULL,
    Age int CHECK (Age>=18));

SQL DEFAULT  Constraint


 The DEFAULT constraint is used to set a default
value for a column.
 The default value will be added to all new records,
if no other value is specified.

Example:-
CREATE TABLE Women (
    ID int NOT NULL,
    LastName varchar(54) NOT NULL,
    FirstName varchar(65),
    Age int,
    City varchar(54) DEFAULT 'Rajgir');

SQL  CREATE INDEX 


Statement
 The CREATE INDEX statement is used to create indexes in tables.
 Indexes are used to retrieve data from the database more quickly than
otherwise. The users cannot see the indexes, they are just used to
speed up searches/queries.

Example:-

CREATE INDEX p_name ON Children(LastName);


Date: 2nd December 2021

EXPERIMENT -3:

Q. Creating an Employee database to set various


constraint.

a.) Personal

b.) Official
---------------------------------------------------------------

a.) Personal:-
Table Created:-

Describe Table:-
Insert Table:-

Output:-
b.) Official:-

Table Created:-

Describe Table:-

Insert Table:-
Output:-
Date: 9thDecember 2021

EXPERIMENT -4
Q. Creating of:-

1. Views

2. Sequences

3. Savepoint

1.Views
 A view contains rows and columns, just like a real table. The fields in a
view are fields from one or more real tables in the database.
 You can add SQL statements and functions to a view and present the
data as if the data were coming from one single table.
 A view is created with the CREATE VIEW statement. 

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

Examples:-
OUTPUT:-

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

 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 provides 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 ;
Where:-
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 beginning.

nocycle: An exception will be thrown


if sequence exceeds its max_value.

Examples:-

OUTPUT:-
TRANSACTIONS

 Transactions group a set of tasks into a single execution unit.

 Transactions are units or sequences of work accomplished in a logical


order, whether in a manual fashion by a user or automatically by some
sort of a database program.

 If any of the tasks fail, the transaction fails. Therefore, a transaction


has only two results: success or failure.

Transaction Control
The following commands are used to control transactions.
 COMMIT − to save the changes.
 ROLLBACK − to roll back the changes.
 SAVEPOINT − creates points within the groups of transactions in which to
ROLLBACK.
 SET TRANSACTION − Places a name on a transaction.

Savepoint
 Savepoint is a command in SQL that is used with the rollback
command.
 It is a command in Transaction Control Language that is used to
mark the transaction in a table.
 Savepoint is helpful when we want to roll back only a small part of
a table and not the whole table. In simple words, we can say
savepoint is a bookmark in SQL.
 If you made a transaction in a table, you could mark the
transaction as a certain name, and later on, if you want to roll back
to that point, you can do it easily by using the transaction's name.

Syntax
SAVEPOINT SAVEPOINT_NAME;
Examples:-

ROLLBACK
 The ROLLBACK command is the transactional command used to undo
transactions that have not already been saved to the database. 
 This command can only be used to undo transactions since the last COMMIT
or ROLLBACK command was issued.

Syntax
ROLLBACK TO SAVEPOINT_NAME;

Examples:-

Date: 5thJanuary 2022


EXPERIMENT -5

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both tables
 LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
 RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
 FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table

SQL INNER JOIN


The INNER JOIN keyword selects records that have matching values in both
tables.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL INNER JOIN Example

SQL RIGHT JOIN


The RIGHT JOIN keyword returns all records from the right table (table2),
and the matching records from the left table (table1). The result is 0 records
from the left side, if there is no match.

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

SQL RIGHT JOIN Example

Note: The RIGHT JOIN keyword returns all records from the right table


(Employees), even if there are no matches in the left table (Orders).
SQL LEFT JOIN
The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records from the right table (table2). The result is 0 records from
the right side, if there is no match.

LEFT JOIN Syntax


SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.

SQL LEFT JOIN Example


SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.

Tip: FULL OUTER JOIN and FULL JOIN are the same.

FULL OUTER JOIN Syntax


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Note: FULL OUTER JOIN can potentially return very large result-sets!

SQL OUTER JOIN Example


Date: 11thJanuary 2022

EXPERIMENT -6

PL/SQL
 Print Hello with PL/SQL

1. set serveroutput on
2. SQL> declare
3. a varchar2(20):='Hello World';
4. begin
5. dbms_output.put_line(a);
6. end;
7. /

Hello World
 Print Welcome with PL/SQL
1. SQL> declare
2. b varchar2(20):='Welcome';
3. begin
4. dbms_output.put_line(b);
5. end;
6. /

Welcome

 Addition of Two number with PL/SQL

declare
2 x integer:=10;
3 y integer:=20;
4 c integer;
5 f number(4,2);
6 begin
7 c:=x+y;
8 dbms_output.put_line('Value of c:'||c);
9 f:=25.0/3.0;
10 dbms_output.put_line('Value of f:'||f);
11 end;
12 /
Value of c:30
Value of f:8.33

 Find Area, Circumference, Diameter with PL/SQL

SQL> declare

2 --constant declaration

3 pi constant number:=3.141592654;

4 --other declaration

5 radius number(5,2);

6 dia number(5,2);

7 circumference number(9,2);

8 area number(12,2);

9 begin
10 --processing

11 radius:=8.5;

12 dia:=radius*2;

13 circumference:=2.0*pi*radius;

14 area:=pi*radius*radius;

15 --output

16 dbms_output.put_line('Radius:'||radius);

17 dbms_output.put_line('Diameter:'||dia);

18 dbms_output.put_line('Circumference:'||circumference);

19 dbms_output.put_line('Area:'||area);

20 end;

21 /

Radius:8.5

Diameter:17

Circumference:53.41

Area:226.98
Date: 12thJanuary 2022

EXPERIMENT -7
Q. Write PL/SQL block to satisfy some condition by
accepting input from the user?

1. Use the select into statement of SQL to assign values to PL/SQL variables.

2. For each item in the select list, there must be a corresponding, type – compatible variable
in the into list

Program

Table Created:-

Table:-
Program Executed:-
Date: 19thJanuary 2022

EXPERIMENT -8

Write a PL/SQL block that handles all types of exceptions.

Algorithm:

Step 1: Start
Step 2: Declare variables a, b and c
Step 3: Declare two exceptions as exp1 and exp2
Step 4: Perform the operations using If else
Step 5: Print the output according to the exception
Step 6: Stop.

Executed Program:

1.
2.

3.

Date: 27thJanuary 2022


EXPERIMENT -9

Write a PL/SQL procedure to find the maximum of two values.

Date: 27thJanuary 2022


EXPERIMENT -10(a)

Tittle: Write a PL/SQL code to display the salary difference of


customer details using Trigger concept.

Aim: Using trigger method to calculate the salary difference.

Algorithm:
Step 1: Start
Step 2: Create table customer8 with variables c_id, c_name,
age, address, and salary
Step 3: Insert the values into customer8 table
Step 4: Display the customer8 table using select command
Step 5: Create trigger
Step 6: Declare variable
Step 7: Store the difference of new salary and old salary of
customers in variable
Step 8: Print the old salary, new salary and salary difference
Step 9: Insert the new value into customer5 table
Step 10: Update the salary of the customer in the table
Step 11: Display the customer8 table again using select
command
Step 12: Stop.

Executed Program:
Result: Using Trigger the salary difference of the employee has
been successfully calculated.
Date: 27thJanuary 2022

EXPERIMENT -10(b)

Write a PL/SQL code to create a function.


1) Write a PL/SQL function to find the maximum of two values
2) Write a PL/SQL function to find the factorial of a number using recursive function

1.
2.
THANK YOU

You might also like