DBMSFileSWAYAM
DBMSFileSWAYAM
0|Page
INDEX
5. 14
Creating relationship between the databases
6. 17
Study of PL/SQL block
7. 21
Write a PL/SQL block to satisfy some conditions by
accepting input from the user
8. 31
Write a PL/SQL block that handles all types of exceptions
9. 38
Creation of Procedures
10. 40
Creation of database triggers and functions
11.
Mini project
1|Page
Experiment-1
Aim:
Syntax:
Create Database {Database Name};
“Show Databases” statement is used to show all the databases in SQL
Server.
Syntax:
Show Databases;
2|Page
Creation of Table:
Constraints can be specified when the table is created with the “Create
Table” statement, or after the table is created with the “Alter Table”
statement.
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: 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.
Index: Used to create and retrieve data from the database very quickly.
Syntax:
Create Table {Table Name}(
Column_1 datatype constraint,
Column_2 datatype constraint,
Column_3 datatype constraint,
.....);
Example:
Create Table cse(
Roll_Number integer primary key,
Full_Name varchar(50) Not NUll,
Phone_Number integer Unique
);
“Show Table” Statement is used to get a list of all the tables in the database
selected.
Syntax:
Show Tables;
3|Page
Experiment 2
Aim:
4|Page
Deleting a record from table:
“Delete From” is for delete a record. It is used with “where” which is used
to specify the conditon where we want to delete the record.
Syntax:
Delete from {table name} where {condition};
Example:
Delete from cse where Roll_Number = 12348;
Altering a Table:
Unlike other command up until now this command do not affect records
but it affects the table itself.
“Alter” is used to change the structure of the table.
Adding a new column:
Used to add a new column in an existing table.
Syntax:
Alter Table {table name}
Add column {column_name datatype};
Example:
Alter table cse add column percentage integer;
Modify a column:
used to modify a column
Syntax:
Alter table {Table_name} Modify column datatype;
Example:
Alter table cse modify Full_Name varchar(100);
Updating a record:
“Update” and “set” statement are used to update records along with the
“where” statement.
Syntax:
Update {table_name} set {column} = {new value}
where {condition};
Example:
Update cse set Full_Name = “Xyz”
where Roll_number = 12348;
6|Page
Experiment 3
Aim:
Creation of a view:
Create view {view_name} as
select {column_1}, {column_2}...
from {table_name}
where {condition};
This query help in creatinf a view (i.e., a virrtual table based on result set
of SQL statement it contains rows & columns just like a table) of a table.
Deletion of a view:
Drop view {view_name};
Updating Views:
Update {view_name} set {column_name} = {new vaue}
where {condition};
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.
The select statement which is usd to create the view should not include
group by clause or order by clause.
The select statement should not have the distinct keyword.
The view should have all not null values.
The view should not be created using nested quesries or complex
queries.
The view should be created from single table. If the view is created
using multiple tables than we will not be allowed to update the view.
Synonyms:
Synonyms are used to create alternate names for tables, views, sequences,
etc.
Creating a synonym:
Create synonym {syn_name} for {object_name};
This query creates a synonym for any object i.e., any table, view, etc.
Droping a synonym:
Drop synonym {syn_name};
This query is used to delete a synonym.
Sequence:
Sequence is used to generate a sequence of numbers. The value generated
can have a maximum of 38 digits.
The minimum information required to generate numbers using a sequence
are:
• The starting number {s}
• The maximum number {m}
• The increment value {n}
Creating a sequence:
Create sequence {seq_name} increment by {n}
Start with {s} maxvalue {m} {cache/ nocache};
This query creates a sequence which increment by value n and starts with s
with maximum value of m.
Modifying a Sequence:
Modification of a sequence does not allow us to change the “start with”
option. Similarly, the maximum value cannot be set to a number less than
the current number.
Alter sequence {seq_name} increment by {n}
Start with {s} maxvalue {m} {cache/ nocache};
Drop a Sequence:
A sequence can dropped:
Drop sequence {sqn_name};
9|Page
Index:
Index is used for faster retrieval of rows from a table. It can be used
implicitly or explicitly.
Creating a Index:
Create index {in_name} on {table_name}(column_1, column_2...);
This query is used to create index on one or more columns.
Rebuilding an index:
Alter index {in_name} Rebuild;
When a table goes through changes, it is advisable to rebuild indexes based
on the table.
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.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.
Creating a savepoint:
To create a savepoint we first have to start our transaction with begin/start.
Start Transaction;
Savepoint {sp_name};
Deleting a savepoint:
There is no syntax to delete a savepoint. A savepoint gets automatically
deleted when we commit or rollback the trasaction.
10 | P a g e
Experiment-4
Aim:
Creating an Employee database to set various constraints.
Description:
Constraints are the rules that we can apply on the type of data in a table.
That is, we can specify the limit on the type of data that can be stored in a
particular column in a table using constraints.
The available constraints in SQL are:
NOT NULL: This constraint tells that we cannot store a null value in a
column. That is, if a column is specified as NOT NULL then we will not be
able to store null in this particular column any more.
UNIQUE: This constraint when specified with a column, tells that all the
values in the column must be unique. That is, the values in any row of a
column must not be repeated.
PRIMARY KEY: A primary key is a field which can uniquely identify
each row in a table. And this constraint is used to specify a field in a table
as primary key.
FOREIGN KEY: A Foreign key is a field which can uniquely identify
each row in a another table. And this constraint is used to specify a field as
Foreign key.
CHECK: This constraint helps to validate the values of a column to meet a
particular condition. That is, it helps to ensure that the value stored in a
column meets a specific condition.
DEFAULT: This constraint specifies a default value for the column when
no value is specified by the user.
11 | P a g e
l_name varchar (20) not null,
age integer not null check(age>22),
d_code integer (5),
foreign key (d_code) references department(d_code),
salary_pm integer
);
12 | P a g e
Experiment – 5
Aim:
Creating relationship between the databases.
Description:
In sql, we can create a relationsip by creating a foreign key constraint.
More, specifically we have a parent table and a child table. The parent
contains the primary key and the child table contains the foreign key that
references to the primary key of the parent table.
When we use SQL to create a relationship, we can create the relationship at
the time we create the table, or we can create it later by altering the table.
Create a Relationship When Creating the Table:
Here’s an example of creating a relationship within your “Create Table”
statement at the time you create the table.
Syntax:
Create table Parent_Table(
P_column_1 datatype primary key,
P_column_2 datatype
P_column_3 datatype
);
Create table Child_Table(
C_Column_1 datatype primary key,
C_Column_2 datatype
C_column_3 datatype constraint Parent_Child
foreign key (C_Column_3)
References Parent_Table (P_Column_1)
);
Here we created two tables; one called “Parent_Table” and the other called
“Child Table”.
Add a Relationship to an Existing Table:
You can also add a relationship to an existing table, simply by using the
“Alter Table” statement. For Example, let say we didn’t create a foreign
key in the table in previous example of Parent_child relationship and we
want to create a relationship now, after we have created the tables.
16 | P a g e
Syntax:
Alter Table Child_Table
Add Constraint Parent_Child
Foreign Key(C_Column_3)
References Parent_Table(P_Column_1);
Note: SQLite Doesn’t support adding foreign keys with the Alter Table
Statement.
Example:
Create table employee (
e_id integer (9) primary key,
f_name varchar (20) not null,
m_name varchar (20) default “n/a”,
l_name varchar (20) not null,
age integer not null check(age>22),
d_code integer (5),
foreign key (d_code) references department(d_code),
salary_pm integer
);
What this actually means is that, if someone was to try to delete or update a
record in the “Primary Key”, an error would occur and the change would
be rolled back. This is SQL Server’s way of preventing any changes that
could break the referential integrity of your system.
Basically, the reason you create a relationship in the first place is to enforce
referential integrity.
However, you do have some options with how you want SQL Server to
deal with these situations.
Specifically, you can use any of the following values:
No Action: An error is raised and the delete/update action on the row
in the parent table is rolled back.
Cascade: Corresponding rows are deleted from/ updated in the
referencing table if that row is deleted from/updated in the parent
table.
Set Null: All the values that make up the foreign key are set to “Null”
if the corresponding row in the parent table is deleted or updated.
This requires that the foreign key columns are nullable.
Set Default: All the values that make up the foreign key are set to
their default values if the corresponding row in the parent table is
deleted or updated. For this constraint to execute, all foreign key
columns must have default definitions. If a column is nullable, and
there is no explicit default value set, “Null” becomes the implicit
default value of the column.
19 | P a g e
Experimnt-6
Aim:
Study of PL/SQL block.
Description:
PL/SQL:
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword
BEGIN and ends with END. This is a mandatory section and is the section
where the program logic is written to perform any task. The programmatic
constructs like loops, conditional statement and SQL statements from the
part of execution section.
20 | P a g e
Exception Section
The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be
handled in this section, so that the PL/SQL Blocks terminates gracefully. If
the PL/SQL Block contains exceptions that cannot be handled, the Block
terminates abruptly with errors. Every statement in the above three sections
must end with a semicolon ; . PL/SQL blocks can be nested within other
PL/SQL blocks. Comments can be used to document code.
1. Anonymous
[DECLARE]
22 | P a g e
BEGIN
--statements
[EXCEPTION]
END;
2. Procedure
PROCEDURE name
IS
BEGIN
--statements
[EXCEPTION]
END;
3. Function
PROCEDURE name
FUNCTION name
RETURN datatype
IS
BEGIN
--statements
RETURN value;
[EXCEPTION]
END;
Result:
23 | P a g e
Experiment-7
Aim:
Description:
PL/SQL Control Structure provides conditional tests, loops, flow control
and branches that let to produce well-structured programs.
Syntax:
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/ SQL General Syntax:
SQL> declare
<variable declaration>;
begin
<executable statement >;
end;
PL/ SQL General Syntax for if Condition:
SQL> declare
<variable declaration>;
begin
if(condition) then
<executable statement >;
24 | P a g e
end;
PL/ SQL General Syntax for If and Else Condition:
SQL> declare
<variable declaration>;
begin
if (test condition) then
<statements>;
else
<statements>;
end if;
end;
PL/ SQL General Syntax for Nested if Condition:
SQL> declare
<variable declaration>;
begin
if (test condition) then
<statements>;
else if (test condition) then
<statements>;
else
<statements>;
end if;
end;
PL/ SQL General syntax for Looping statement:
SQL> declare
<variable declaration>;
begin
26 | P a g e
loop
<statement>;
end loop;
<executable statement>;
end;
PL/ SQL General Syntax For Looping Statement:
SQL> declare
<variable declaration>;
begin
while <condition>
loop
<statement>;
end loop;
<executable statement>;
end;
PL/SQL Coding for addition of two numbers:
PROCEDURE:
Step 1: Start
Step 2: Initialize the necessary variables.
Step 3: Develop the set of statements with the essential
operational parameters.
Step 4: Specify the Individual operation to be carried out.
Step 5: Execute the statements.
Step 6: Stop.
PROGRAM:
SQL> set serveroutput on
SQL> declare
27 | P a g e
a number;
b number;
c number;
begin
a: =&a;
b: =&b;
c: =a+b;
dbms_output.put_line ('sum of' ||a|| 'and '||b||' is '||c);
end;
/
Input:
Enter value for a: 23
old: a:=&a;
new: a:=23;
Enter value for b: 12
old: b:=&b;
new: b:=12;
Output:
Result:
Thus a PL/SQL block to satisfy some conditions by accepting input from
the user was created using oracle.
38 | P a g e
Experiment-8
Aim:
Program:
ZERO_DIVIDE EXCEPTION
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE(1 / 0);
END;
/
Output:
BEGIN
DBMS_OUTPUT.PUT_LINE(1 / 0);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Division by zero');
END;
/
43 | P a g e
Division by zero:
INVALID_NUMBER EXCEPTION
BEGIN
INSERT INTO employees(DEPARTMENT_ID)VALUES('101x');
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('Conversion of string to number
failed');
end;
/
Output:
Other Exceptions
BEGIN
DBMS_OUTPUT.PUT_LINE(1 / 0);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An exception occurred');
END;
/
Output:
Program:
(The following example illustrates the programmer-defined exceptions. Get
the salary of an employee and check it with the job’s salary range. If the
salary is below the range, an exception BELOW_SALARY_RANGE is
raised. If the salary is above the range, exception
ABOVE_SALARY_RANGE is raised)
SET SERVEROUTPUT ON SIZE 100000;
DECLARE
-- define exceptions
BELOW_SALARY_RANGE EXCEPTION;
ABOVE_SALARY_RANGE EXCEPTION;
-- salary variables
n_salary employees.salary%TYPE;
n_min_salary employees.salary%TYPE;
n_max_salary employees.salary%TYPE;
-- input employee id
n_emp_id employees.employee_id%TYPE := &emp_id;
BEGIN
SELECT salary, min_salary max_salary INTO n_salary,
n_min_salary, n_max_salary
FROM employees
INNER JOIN jobs ON jobs.job_id = employees.job_id
WHERE employee_id = n_emp_id;
45 | P a g e
IF n_salary < n_min_salary THEN
RAISE BELOW_SALARY_RANGE;
ELSIF n_salary > n_max_salary THEN
RAISE ABOVE_SALARY_RANGE;
END IF;
dbms_output.put_line('Employee ' || n_emp_id ||' has salary $' ||
n_salary );
EXCEPTION WHEN BELOW_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id || ' has salary
below the salary range');
WHEN ABOVE_SALARY_RANGE THEN
dbms_output.put_line('Employee ' || n_emp_id || ' has salary
above the salary range');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Employee ' ||n_emp_id || ' not
found');
END;
/
Result:
Thus a PL/SQL block that handles all type of exceptions was written,
executed and verified successfully.
47 | P a g e
Experiment-9
Aim:
Creation of Procedures.
Description:
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block
which performs one or more specific tasks. It is just like procedures in
other programming languages.
The procedure contains a header and a body.
Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
How to pass parameters in procedure:
When you want to create a procedure or function, you have to define
parameters .There is three ways to pass parameters in procedure:
IN parameters:The IN parameter can be referenced by the procedure or
function. The value of the parameter cannot be overwritten by the
procedure or the function.
OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten by
the procedure or function.
INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten by
the procedure or function.
Creation of Procredure:
Create {or Replace} Procedure {procedure_name} (parameter,
parameter .... )
IS
{decalaration_section}
BEGIN
executable_section
48 | P a g e
{EXCEPTION
exception section}
END {procedure_name};
/
Example:
Table:
create table user(id integer(10) primary key,name varchar2(100));
Procedure:
create procedure insert_user (id in number, name in varchar2)
is
begin
insert into user values(id,name);
end;
/
Deleting a procedure:
Drop procedure {procedure_name};
This syntax deletes the procedure.
Example:
Drop procedure insert_user;
49 | P a g e
Experiment-10
Aim:
52 | P a g e