0% found this document useful (0 votes)
34 views25 pages

Saksham Chaudhary DBMS Prscticle File

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

Saksham Chaudhary DBMS Prscticle File

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

ST.

ANDREWS INSTITUTE
OF TECHNOLOGY & MANAGEMENT
Gurgaon Delhi (NCR)
Approved by AICTE, Govt. of India,
New Delhi Affiliated to Maharshi
Dayanand University
‘A’ Grade State University, accredited by NAAC

Department

Computer Science (Artificial Intelligence & Machine


Learning)

Subject Name: Database Management System


Subject Code: PCC-CSE-250G

Submitted To: Submitted by:

Mrs. Ritika NAME: Saksham chaudhary

(Assistant. professor) University Reg No: 2012191234


Faculty sign.: ROLL NO : 207006
TABLE OF CONTENTS

S.NO TITLE DATE REMARK

1. Introduction to Sql 12/04/22

2. Implementation of DDL 19/04/22


commands of SQL with
suitable examples.
- CREATE, ALTER, DROP
TABLE
3. Implementation of DML 19/04/22
commands of SQL with
suitable examples.
- INSERT, UPDATE, DELETE
4. Implementation of different types 26/04/22
of Joins - Inner join - Outer join -
Natural join etc.

5. Create an employee database for 03/05/22


the implementation of different
types of constraints.

6. Creation of views, Synonyms, 10/05/22


Sequence, Indexes and
Save point.
7. Study of PL/SQL BLOCK 17/05/22

8. Write a PL/SQL block to satisfy 24/05/22


some conditions by accepting
input from user.
9. Write a PL/SQL block to handle all 31/05/22
types of exceptions.

10. Creation of Procedures. 07/06/22

11. Creation of database triggers and 14/06/22


functions.
EXPERIMENT 1 : STRUCTURED QUERY LANGUAGE

SQL is a language to operate databases; it includes database creation, deletion, fetching rows,
modifying rows, etc. SQL is an ANSI (American National Standards Institute) standard language, but
there are many different versions of the SQL language. What is SQL?

SQL is Structured Query Language, which is a computer language for storing, manipulating and
retrieving data stored in a relational database.

SQL is the standard language for Relational Database System. All the Relational Database
Management Systems (RDMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their
standard database language.

Also, they are using different dialects, such as −

• MS SQL Server using T-SQL,


• Oracle using PL/SQL,
• MS Access version of SQL is called JET SQL (native format) etc.

Why SQL?

SQL is widely popular because it offers the following advantages −

1. Allows users to access data in the relational database management systems.


2. Allows users to describe the data.
3. Allows users to define the data in a database and manipulate that data.
4. Allows to embed within other languages using SQL modules, libraries & precompiles.
5. Allows users to create and drop databases and tables.
6. Allows user to create view, stored procedure, functions in a database.
7. Allows users to set permissions on table, procedure and views.

SQL Commands

The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE,
DELETE and DROP. These commands can be classified into the following groups based on their
nature –
DDL - Data Definition Language

Sno COMMAND AND DESCRIPTION


1. CREATE
Creates a new table, a view of a table, or other object in the
database.
2. ALTER
Modifies an existing database object, such as a table.

3. DROP
Deletes an entire table, a view of a table or other objects in the
database.

DML - Data Manipulation Language

S.NO COMMAND AND DESCRIPTION

1. SELECT
Retrieves certain records from one or more tables.

2. INSERT
Creates a record.

3. UPDATE
Modifies records.

4. DELETE
Deletes records.

EXPERIMENT: 2
AIM- Introduction to the software environment and implement the different DDL
commands of SQL with suitable examples. - Create Table - Alter Table - Drop table.

1. CREATE TABLE COMMAND :


The CREATE TABLE statement is used to create a new table in a database.

Syntax

CREATE TABLE table_name


(
column1 datatype, column2 datatype, column3 datatype,
.... );

2. ALTER TABLE COMMAND

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.

(i) ALTER TABLE – ADD

ADD is used to add columns into the existing table.


Syntax
ALTER TABLE table_name
ADD column_name datatype;
(ii) ALTER TABLE – DROP

DROP COLUMN is used to drop column in a table. Deleting the unwanted columns
from the table

Syntax

ALTER TABLE table_name


DROP COLUMN column_name;

(iii) ALTER TABLE – MODIFY

It is used to modify the existing columns in a table.


Syntax

ALTER TABLE table_name


MODIFY column_name datatype;
3. DROP TABLE COMMAND

The DROP TABLE command is used to drop an existing table in a database. Syntax

DROP TABLE table_name;

4. RENAMETABLE COMMAND

The RENAME TABLE command is used to rename an existing table.


Syntax

RENAME TABLE old_table_name TO new_table_name ;


EXPERIMENT 3

AIM - Implementation of DML commands of SQL with suitable examples. - INSERT -


UPDATE – DELETE
1. INSERT INTO COMMAND

The INSERT INTO statement is used to insert new record in a table.


Syntax :

INSERT INTO table_name


VALUES (value1, value2, value3….), (value1, value2, value3...);

2. UPDATE COMMAND

The UPDATE statement is used to modify the existing records in table. Syntax

UPDATE table_name
SET column1=value1, column2=value2…

;
WHERE condition

3. DELETE COMMAND

The DELETE statement is used to delete existing record in a table.


Syntax
DELETE FROM table_name WHERE condition ;
EXPERIMENT 4

AIM – Implementation of different types of joins – Inner join – Outer join – Natural join
etc.
Program :
A SQL Join statement is used to combine data or rows from two or more tables based
on a common field between them.

TABLE 1

TABLE 2

1. INNER JOIN

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

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
2. OUTER JOIN

(i) LEFT OUTER JOIN

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

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

(ii) RIGHT OUTER JOIN


The RIGHT JOIN keyword returns all records from the right table (table2), and the
matched records from the left table (table1). The result is NULL from the left side,
when there is no match.
Syntax

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

The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
Syntax
SELECT * FROM A
LEFT JOIN B
ON A.key =B.key
UNION
SELECT * FROM A
RIGHT JOIN B
ON A.key =B.key ;

3. NATURAL JOIN
The MySQL NATURAL JOIN is structured in such a way that, columns with the same
name of associate tables will appear once only.
Syntax

SELECT * FROM table1


NATURAL JOIN table2
WHERE table1.column_name=table2.column_name

4. SELF JOIN
A self-join is a join in which a table is joined with itself (which is also called Unary
relationships), especially when the table has a FOREIGN KEY which references its
own PRIMARY KEY. To join a table it means that each row on the table is combined
with itself and with every other row of the table.

Syntax :
SELECT a.column_name, b.column_name...
FROM table1 a
INNER JOIN table1 b
ON a.column1=b.column2;

5. EQUI JOIN: SQL EQUI JOIN performs a JOIN against equality or matching
column(s) values of the associated tables. An equal sign (=) is used as comparison
operator in the where clause to refer equality.

Syntax:

SELECT column_list
FROM table1, table2....
WHERE table1.column_name = table2.column_name;
EXPERIMENT: 5
AIM - Create an employee database for the implementation of
different types of 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.
Constraints can be column level or table level. Column level constraints apply to a
column, and table level constraints apply to the whole table.

The following constraints are commonly used in SQL:

• NOT NULL - Ensures that a column cannot have a NULL value


• 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 - Uniquely identifies a row/record in another table
• CHECK - Ensures that all values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column when no value is specified

1. NOT NULL CONSTRAINT


Syntax
CREATE TABLE table_name

( Column1 datatype NOT NULL,

Column2 datatype NOT NULL

create table employee( eid


integer NOT NULL, ename
varchar(20) NOT NULL,
gender varchar(20) NOT NULL
)
2. UNIQUE CONSTRAINT
Syntax
CREATE TABLE table_name

( Column1 dataype NOT NULL,

Column2 datatype NOT NULL,

UNIQUE (Column1)

);

create table employee( eid


integer NOT NULL, ename
varchar(20) NOT NULL,
gender varchar(20)
NOT NULL UNIQUE(eid)
)

3. PRIMARY KEYCONSTRAINT
Syntax
CREATE TABLE table_name

( Column1 datatype NOT NULL

PRIMARY KEY,

Column2 datatype NOT NULL );

create table employee( eid integer


NOT NULL PRIMARY KEY, ename
varchar(20) NOT NULL, gender
varchar(20) NOT NULL
)

4. FOREIGN KEY CONSTRAINT


Syntax

CREATE TABLE table1_name

Colm1 datatype NOT NULL,

Colm2 datatype NOT NULL,


PRIMARY KEY(Colm2) FOREIGN KEY(colm1)

REFERENCES

Table2_name(colm1)

);

create table employee( eid integer NOT


NULL PRIMARY KEY, ename varchar(20)
NOT NULL, gender varchar(20) NOT NULL
did integer NOT NULL,
PRIMARY KEY (did) references departement (did)
)
create table departement( did
integer NOT NULL, Dname
varchar(20),
PRIMARY KEY (did) )

5. CHECK CONSTRAINT
Syntax
CREATE TABLE table_name

( Column1 dataype NOT NULL,

Column2 datatype NOT NULL, CHECK(condition)

);

create table employee( eid integer


NOT NULL, enmae varchar(20) NOT
NULL, gender varchar(20) NOT
NULL, age INTEGER NOT NULL,
CHECK (age >= 18)

6. Default CONSTRAINT :

Syntax :

CREATE TABLE able_name

Column1 datatype NOT NULL column2

datatype NOT NULL

Col3 datatype DEFAULT ‘default view’ create table employee ( eid integer NOT NULL, ename
varchar(20) NOT NULL, gender varchar(20) NOT NULL, age INTEGER NOT NULL, city
varchar(30) DEFAULT 'DELHI'
Experiment No : 6

AIM - Creation of views, Synonyms, Sequence, Indexes and Save


point.

1. Views
In SQL, a view is a virtual table based on the result-set of an SQL statement.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.

Syntax:

create view view_name as select column1,


column2,... From table_name
Where condition

2. SYNONYM
Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for a
table, view, sequence, procedure, stored function, package, materialized view, Java class schema
object, user define object type, or another synonym.
Synonyms provide both data independence and location transparency. Synonyms permit
applications to function without modification regardless of which user owns the table or view and
regardless of which database holds the table or view. However, synonyms are not a substitute for privileges
on database objects. Appropriate privileges must be granted to a user before the user can use the synonym.

CREATE SYNONYM emp2


FOR employees

3. SEQUENCE
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 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

CREATE SEQUENCE sequence_name

START WITH initial_value

INCREMENT BY increment_value

MINVALUE minimum value

MAXVALUE maximum value

CYCLE NOCYCLE ;

4. SQL INDEXES
An index is a schema object. It is used by server to speed up the retrival of rows by using pointer. It can be
reduce disk i/o by using a rapid path method to locate data quickly. An index helps to speed up select
queries and where clauses, but it slows down data input, with the update and insert statements.

Syntax

CREATE INDEX index


ON TABLE column;

When indexes should be created-

• A column contains a wide range of values.


• A column does not contain a large number of null values.
• One or more columns are frequently used together in a where clause or a join condition.

When should indexed be avoided-

• The table is small.


• The columns are not often used as a condition in the query. The column is updated frequently.
5. SAVEPOINT
Creates points within the groups of transactions in which to ROLLBACK.

A SAVEPOINT is a point in a transaction in which you can roll the transaction back to a certain
point without rolling back the entire transaction.
EXPERIMENT-7

AIM- Study of PL/SQL BLOCK.

PL/SQL Introduction
PL/SQL is a block structured language that enables developers to combine the power of SQL with
procedural statements. All the statements of a block are passed to oracle engine all at once which
increases processing speed and decreases the traffic.

Disadvantages of SQL:

• SQL doesn’t provide the programmers with a technique of condition checking, looping and
branching.
• SQL statements are passed to Oracle engine one at a time which increases traffic and decreases
speed.
Features of PL/SQL:

1. PL/SQL is basically a procedural language, which provides the functionality of decision making,
iteration and many more features of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which
are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as
exception handling block.
Differences between SQL and PL/SQL:

SQL PL/SQL

SQL is a single query that is used to PL/SQL is a block of codes that used to write
perform DML and DDL operations. the entire program blocks/ procedure/ function,
etc.
It is declarative, that defines what
needs to be done, rather than how PL/SQL is procedural that defines how the
things need to be done. things needs to be done.

Execute as a single statement. Execute as a whole block.

Mainly used to manipulate data. Mainly used to create an application.

It is an extension of SQL, so it can contain


Cannot contain PL/SQL code in it. SQL inside it.
Structure of PL/SQL Block:

PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural
language that is more powerful than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are
made up of blocks, which can be nested within each other.

Typically, each block performs a logical action in the program. A block has the following structure:

• Execution section starts with BEGIN and ends with END keyword. This is a mandatory
section and here the program logic is written to perform any task like loops and
conditional statements. It supports all DML commands, DDL commands and SQL*PLUS
built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any exceptions can
be handled in this section.
EXPERIMENT 8
AIM - Write a PL/SQL block to satisfy some conditions by accepting input from user.

There come situations in real life when we need to make some decisions and based on these decisions,
we decide what we should do next. Similar situations arise in programming also where we need to make
some decisions and based on these decisions we will execute the next block of code. Decision-making
statements in programming languages decide the direction of flow of program execution. Decision-making
statements available in pl/SQL are:

1. if then statement
2. if then else statements
3. nested if-then statements
• IF THEN STATEMENT
o Syntax

o If Condition then o --do something END if;

• IF THEN ELSE STATEMENT


o Syntax

o If(condition) then
o --executes this block if o --
condition is true o Else
o --executes this block if o --
condition is false
• NESTED IF THEN STATEMENT
o Syntax
o If (condition) then
o --executes when condition1 is true
o If(condition) then
o --executes when conditio2 is true o
END if; o END if;
EXPERIMENT 9
AIM - Write a PL/SQL block to handle all types of exceptions.
An exception is an error which disrupts the normal flow of program instructions. PL/SQL provides
us the exception block which raises the exception thus helping the programmer to find out the
fault and resolve it.

There are two types of exceptions defined in PL/SQL

1. User defined exception.


2. System defined exceptions.

System defined exceptions:

Syntax to write an exception


WHEN exception THEN
statement;
DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2
THEN statement2;
[WHEN others THEN]
/* default exception handling code */
END;

These exceptions are predefined in PL/SQL which get raised WHEN certain database rule is violated.
System-defined exceptions are further divided into two categories:

1. Named system exceptions.


2. Unnamed system exceptions.
• Named system exceptions: They have a predefined name by the system like
ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc. the list is quite big.
1. NO_DATA_FOUND:
It is raised WHEN a SELECT INTO statement returns no

rows. 2. TOO_MANY_ROWS:
It is raised WHEN a SELECT INTO statement returns more than

one row. 3. VALUE_ERROR:

This error is raised WHEN a statement is executed that resulted in an arithmetic, numeric,
string, conversion, or constraint error. This error mainly results from programmer error or
invalid data input.

• USERDEFINED EXPECTATION;
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or
the procedure.

• Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when
a SELECT INTO statement returns

no rows. The following table lists few of the important pre-defined exceptions –

ACCESS_INTO_ 06530 -6530 It is raised when a null object is


NULL automatically assigned a value
CASE_NOT_FO 06592 -6592 It is raised when none of the
UND choices in the WHEN clause of a
CASE statement is selected, and
there is no
ELSE clause.
COLLECTION_I 06531 -6531 It is raised when a program attempts
S_NULL to apply collection methods other
than
EXISTS to an uninitialized nested
table or array, or the program
attempts to

EXCEPTION ORACLE SQLCODE DESCRIPTION


ERROR

assign values to the elements of an


uninitialized nested table or array.
DUP_VAL_ON_I 00001 -1 It is raised when duplicate values are
NDEX attempted to be stored in a column with
unique index.
INVALID_CURSOR 01001 -1001 It is raised when attempts are made to
make a cursor operation that is not
allowed, such as closing an unopened
cursor
INVALID_NUM BER 01722 -1722 It is raised when the conversion of a
character string into a number fails
because the string does not represent a
valid number.
LOGIN_DENIED 01017 -1017 It is raised when a program attempts to
log on to the database with an invalid
username or password.
EXPERIMNET 10
Aim: Creation of procedures.

Procedures these subprograms do not return a value directly; mainly used to


perform an action.
Creating a Procedure A procedure is created with the CREATE OR
REPLACE
PROCEDURE statement. The simplified syntax for the CREATE OR
REPLACE PROCEDURE statement is as follows

Syntax:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, …])]
{IS | AS}
BEGIN
END procedure_name;
Where,
Procedure-name specifies the name of the procedure. [OR REPLACE]
option allows the modification of an existing procedure.

The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from
outside and OUT represents the parameter that will be used to
return a value outside of the procedure. Procedure-body contains
the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
EXPERIMENT 11
Aim: Creation of database triggers and functions.

Triggers
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to
any of the following events
• A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE).
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP,
or SHUTDOWN).

Triggers can be defined on the table, view, schema, or database with which
the event is associated.
Creating Triggers

Syntax:
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an
existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be
executed. The
INSTEAD OF
clause is used for creating trigger on a view. 30
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will
be executed for each row being affected. Otherwise the trigger will execute
just once when the SQL statement is executed, which is called a table level
trigger.
WHEN (condition) − This provides a condition for rows for which the trigger wouldfire.
This clause is valid only for row-level triggers.

Functions:
A function is same as a procedure except that it returns a value. Therefore, all
the discussions of the previous chapter are true for functions too.

Creating a Function
A standalone function is created using the CREATE
FUNCTION statement.
The simplified syntax for the CREATE OR REPLACE
PROCEDURE statement is as follows − CREATE [OR
REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
<function_body>
END [function_name];
Where,
Function-name specifies the name of the function. 31 [OR
REPLACE] option allows the modification of an existing
function

You might also like