Database Management System Practical File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 43

lOMoARcPSD|25077524

Database Management system Practical File

Database Management Systems (I. K. Gujral Punjab Technical University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Malik Kamran ([email protected])
lOMoARcPSD|25077524

PRACTICAL
file

Department: Computer Science and Engineering

Subject : Database Management System Lab

Subject Code: BTCS


-505-18

Semester :5th

Submitted to: Submitted by:

Mr. Jagjit Singh Shahrukh

1804125

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

TABLE OF CONTENTS

S. No. Experiment Date Signature


1 Introduction to SQL and installation of
SQL Server/Oracle.

2 Data Types, Creating Tables, Retrieval


of Rows using Select Statement,
Conditional Retrieval of Rows, Alter
and Drop Statements.
3 Working with null values, matching a
Pattern from a Table, Ordering a result
of a query, Aggregate Functions,
Grouping the result of a Query, Update
and Delete statement.
4 Set operations, Nested Queries, Joins,
sequences.

5 Views, Indexes, Database Security and


Privileges: Grant and Revoke
Commands, Commit and Rollback
Commands.
6 PL/SQL Architecture, Assignments and
Expressions, Writing PL/SQL Code,
Referencing Non-SQL parameters.
7 Stored Procedures and Exceptional
Handling.

8 Triggers and Cursor Management in


PL/SQL.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

EXPERIMENT-1

Introduction to SQL and installation of SQL Server/Oracle.

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, Sybase, Informix, Postgres and SQL Server use SQL as their standard
database language.

What Can SQL do?

• SQL can execute queries against a database


• SQL can retrieve data from a database
• SQL can insert records in a database
• SQL can update records in a database
• SQL can delete records from a database
• SQL can create new databases
• SQL can create new tables in a database
• SQL can create stored procedures in a database
• SQL can create views in a database
• SQL can set permissions on tables, procedures, and views

Installation of SQL Server


To install SQL Server, you need to download it from the Microsoft.com website

Once the download completes, you double-click the file SQLServer2017-SSEI-Dev.exe to


launch the installer.

1. The installer asks you to select the installation type, choose the Custom installation type
allows you to step through the SQL Server installation wizard and select the features that you
want to install.
2. Specify the folder for storing the installation files that the installer will download, then click
the Install button.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

3. The installer starts downloading the install package for a while.

4. Once the download completes, open the folder that stores the install package and double-
click the SETUP.exe file.

5. The following window displays; select the installation option on the left.

6. Click the first link to launch a wizard to install SQL Server 2017.

7. Specify the edition that you want to install, select Developer edition and click the Next
button.

8. Select the “I accept the license terms.” and click the Next button.

9. Check the “Use Microsoft Update to check for updates (recommended)” to get the security
other important updates for the SQL Server and click the Next button.

10. The installation checks for the prerequisites before installation. If no error found, click the
Next button.

11. Select the features that you want to install. For now, you just need the Database Engine
Services, just check the checkbox and click the Next button to continue.

12. Specify the name and install ID for the instance of the SQL Server and click the Next button.

13. Specify the service account and collation configuration. Just use the default configuration
and click the Next button.

14. Specify the database engine security mode. First, choose Mixed Mode. Next, enter the
password for the SQL Server system administrator (sa) account. Then, re-enter the same
password to confirm it. After that, click the Add Current User button. Finally, click the Next
button.

15. Verify the SQL Server 2017 features to be installed:

16. The installer starts the installation process


17. Once it completes, the following window displays. Click the OK button.

18. Click the Close button to complete the installation

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

EXPERIMENT-2

Data Types, Creating Tables, Retrieval of Rows using Select Statement, Conditional

Retrieval of Rows, Alter and Drop Statements.

SQL data types can be broadly divided into following categories.

1. Numeric data types such as int, tinyint, bigint, float, real etc.
2. Date and Time data types such as Date, Time, Datetime etc.
3. Character and String data types such as char, varchar, text etc.
4. Unicode character string data types, for example nchar, nvarchar, ntext etc.
5. Binary data types such as binary, varbinary etc.
6. Miscellaneous data types – clob, blob, xml, cursor, table etc.

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,
....
);

For example:-

CREATE TABLE Persons (

Person ID int,

First Name varchar(255),

Last Name varchar(255),


City varchar(255)

);

OUTPUT:-

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Person ID First Name Last Name City

1 Rahul Chauhan Gurgaon

2 Sanjay Mishra Shimla

3 Deepak Sharma Hyderabad

The SQL SELECT Statement

The SELECT statement is used to select data from a database.

The data returned is stored in a result table, called the result-set.

SELECT Syntax:-
SELECT column1, column2, ...
FROM table_name;

For example:-

SELECT PersonID, First Name, City FROM Persons;

OUTPUT:-

Person ID First Name City

1 Rahul Gurgaon

2 Sanjay Shimla

3 Deepak Hyderabad

Conditional retrieval of rows :-

SYNTAX:-

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SELECT *FROM table_name

WHERE CONDITION;

For example:-

SELECT *FROM Persons WHERE First Name = Rahul;

OUTPUT:-

Person ID First Name Last Name City

1 Rahul Chauhan Gurgaon

Alter statement:-

This statement is used to add extra column to the table.

Syntax:-

ALTER TABLE table_name

ADD column_name datatype;

For example:-

ALTER TABLE Persons

ADD Gender varchar;

OUTPUT:-

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Person ID First Name Last Name City Gender

1 Rahul Chauhan Gurgaon

2 Sanjay Mishra Shimla

3 Deepak Sharma Hyderabad

DROP STATEMENT:-

This statement is used to drop/delete a column from the table.

Syntax:-

ALTER TABLE table_name

DROP column_name datatype;

For example:-

ALTER TABLE Persons

DROP COLUMN Gender;


OUTPUT:-

Person ID First Name Last Name City

1 Rahul Chauhan Gurgaon

2 Sanjay Mishra Shimla

3 Deepak Sharma Hyderabad

EXPERIMENT-3

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Working with null values, matching a Pattern from a Table, Ordering a result of a
query, Aggregate Functions, Grouping the result of a Query, Update and Delete
statement.

What is a NULL Value?


A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without adding a value
to this field. Then, the field will be saved with a NULL value.

Note: A NULL value is different form a zero value or a field that contains spaces. A field with a NULL
value is one that has been left blank during record creation!

Consider the example:-

Person ID First Name Last Name City Pin Code

1 Rahul Chauhan Gurgaon

2 Sanjay Mishra Shimla 171201

3 Deepak Sharma Hyderabad

IS NULL SYNTAX:-

SELECT column_names
FROM table_name
WHERE column_name IS NULL;

For example:-SELECT Person ID , First Name FROM Persons WHERE First Name IS NOT NULL;
OUTPUT:-

Person ID First Name

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

1 Rahul

2 Sanjay

3 Deepak

IS NOT NULL SYNTAX:-

SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

For example:-
SELECT First Name, Pin Code
FROM Persons
WHERE Pin Code IS NULL;

OUTPUT:-

Person ID First Name Last Name City Pin Code

1 Rahul Chauhan Gurgaon

3 Deepak Sharma Hyderabad

Matching Patterns From a Table:- In SQL, we sometimes need to filter our result set based on some pattern
matching techniques. SQL has a standard pattern matching technique using the 'LIKE' operator. But, it
also supports the regular expression pattern matching for better functionality.

Generally, the REGEXP_LIKE (column_name, 'regex') function is used for pattern matching in SQL.

SQL also supports some operators that work similar to this function, these are: 'REGEXP' and 'RLIKE'

operator. So in this blog, we will learn about all those functions and operators that provide pattern matching

functionality in SQL.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Some of the commonly used wildcard characters in MySQL are as follows:

• '%' represents zero or more characters.


• '_' represents exactly 1 character.

Like operation syntax:-

FROM table WHERE table.column LIKE 'wildcard_characters';

For example:-
SELECT * FROM Persons

WHERE First Name LIKE 'R%';

OUTPUT:-

Person ID First Name Last Name City Pin Code

1 Rahul Chauhan Gurgaon

ORDERING THE QUERY RESULT:-

The SQL ORDER BY clause is used to sort the data in ascending or descending order,
based on one or more columns. Some databases sort the query results in an ascending order
by default.

Syntax:-
The basic syntax of the ORDER BY clause which would be used to sort the result in an
ascending or descending order is as follows –

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

CONSIDER THE TABLE 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 Chaitalli 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 MP 4500.00

7 Muffy 24 Indore 10000.00

For example:-

SELECT * FORM CUSTOMERS


ORDER BY NAME, SALARY;

Output:-

ID NAME AGE ADDRESS SALARY

4 Chaitalli 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

3 Kaushik 23 Kota 2000.00

2 Khilan 25 Delhi 1500.00

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

6 Komal 22 MP 4500.00

7 Muffy 24 Indore 10000.00

1 Ramesh 32 Ahmedabad 2000.00

AGGREGATE FUNCTIONS:-

An aggregate function performs a calculation on a set of values, and returns a single value.

Except for COUNT(*), aggregate functions ignore null values. Aggregate functions are

often used with the GROUP BY clause of the SELECT statement.

Use aggregate functions as expressions only in the following situations:-

• The select list of a SELECT statement (either a subquery or an outer query).  A HAVING
clause.

Transact-SQL provides the following aggregate functions:

• AVG – calculates the average of a set of values.


• COUNT – counts rows in a specified table or view.
• MIN – gets the minimum value in a set of values.
• MAX – gets the maximum value in a set of values.  SUM – calculates the sum of values.

Consider the table 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 Chaitalli 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

6 Komal 22 MP 4500.00

7 Muffy 24 Indore 10000.00

FOR EXAMPLE:-

SELECT AVG(`AGE`) FROM `CUSTOMERS`;

OUTPUT:-

AVG(‘ AGE ’)

25.42

For example:-

SELECT SUM(`SALARY`) FROM `CUSTOMERS`;

OUTPUT:-

SUM( ‘SALARY ’)

35000.00

The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some
functions. i.e if a particular column has same values in different rows then it will arrange these rows in a
group.

Important Points:
• GROUP BY clause is used with the SELECT statement.
• In the query, GROUP BY clause is placed after the WHERE clause.
• In the query, GROUP BY clause is placed before ORDER BY clause if used any.

SYNTAX:-

SELECT column1, function_name(column2)

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

FROM table_name

WHERE condition

GROUP BY column, column2


Function_name: Name of the function used, for example, SUM(), AVG().

Table_name: Name of table.

Condition: Condition used.

Consider the table EMPLOYEE:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

3 ASHISH 1500 19

4 HARSH 3500 19

5 ASHISH 1500 19

FOR EXAMPLE:-

Example:

 Group By single column: Group By single column means, to place all the rows with same value of
only that particular column in one group. Consider the query as shown below:

SELECT NAME, SUM( SALARY ) FROM EMPLOYEE

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

GROUP BY NAME;

OUTPUT:-

NAME SALARY

ASHISH 3000

DHANRAJ 3000

HARSH 5500

UPDATE AND DELETE STATEMENT:-

The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause
with the UPDATE query to update the selected rows, otherwise all the rows would be affected.

The basic syntax of the UPDATE query with a WHERE clause is as follows –
Syntax:-
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

Consider the table EMPLOYEE:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

3 ASHISH 1500 19

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

4 HARSH 3500 19

5 ASHISH 1500 19

For example:-
UPDATE EMPLOYEE

SET SALARY = 4000

WHERE SL NO.=4

OUTPUT:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

3 ASHISH 1500 19

4 HARSH 4000 19

5 ASHISH 1500 19

The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records
would be deleted.

Syntax:-

DELETE FROM table_name


WHERE [condition];

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

For example:-

DELETE FROM EMPLOYEE

WHERE SL NO. =5;

OUTPUT:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

3 ASHISH 1500 19

4 HARSH 4000 19

EXPERIMENT-4
Set operations, Nested Queries, Joins, sequences.

The SQL Set operation is used to combine the two or more SQL SELECT statements.

Types of Set Operation


1. Union
2. UnionAll
3. Intersect
4. Minus

1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT queries.
o In the union operation, all the number of datatype and columns must be same in both the tables on which UNION
operation is being applied.
o The union operation eliminates the duplicate rows from its resultset.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SELECT column_name FROM table1


UNION
SELECT column_name FROM table2;

FOR EXAMPLE:-

The first table:

ID NAME

1 JACK

2 HARRY

3 JACKSON

The second table:-


NAME
ID
3 JACKSON

4 STEPHAN

5 DAVID

The query will be:-

SELECT * FROM First


UNION SELECT * FROM
Second;

OUTPUT:-

NAME
ID
1 JACK

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

2 HARRY

3 JACKSON

4 STEPHAN

5 DAVID

2. Union All
Union All operation is equal to the Union operation. It returns the set without removing duplication and sorting the data.
Syntax:-

SELECT column_name FROM table1


UNION ALL
SELECT column_name FROM table2;

For example:-

SELECT * FROM First


UNION ALL
SELECT * FROM Second;

OUTPUT:-

ID NAME

1 JACK

2 HARRY

3 JACKSON

3 JACKSON

4 STEPHAN

5 DAVID

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same. o
It has no duplicates and it arranges the data in ascending order by default.

Syntax:-

SELECT column_name FROM table1


INTERSECT SELECT column_name
FROM table2;
For example:-
SELECT * FROM First
INTERSECT
SELECT * FROM Second

OUTPUT:-

ID NAME

3 JACKSON

4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display the rows which are present in the first
query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.

Syntax:

SELECT column_name FROM table1


MINUS SELECT column_name
FROM table2;

For example:-
SELECT * FROM First
MINUS SELECT * FROM
Second;

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

OUPUT:-

ID NAME

1 JACK

2 HARRY

Nested Query :-
A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule: A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.

o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like =, <, >, >=,
<=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner query is known as
a subquery.
o Subqueries are on the right side of the comparison operator. o A subquery is enclosed in parentheses.

o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform the same
function as ORDER BY command.

SQL subqueries are most frequently used with the Select statement.

Syntax:-

SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );

Consider the table EMPLOYEE:-


ID NAME AGE SALARY

1 JOHN 20 2000

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

2 STEPHAN 26 1500

3 DAVID 27 2000

4 ALINA 29 6500

5 KATHRIN 34 8500

The subquery with a SELECT statement will be:

SELECT *
FROM EMPLOYEE
WHERE ID IN (SELECT ID
FROM EMPLOYEE
WHERE SALARY > 4500);
OUTPUT:

ID NAME AGE SALARY

4 ALINA 29 6500

5 KATHRIN 34 8500

JOINS:-

As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to combine two or
more tables".

The SQL JOIN clause takes records from two or more tables in a database and combines it together.
ANSI standard SQL defines five types of JOIN :

1. inner join,
2. left outer join,
3. right outer join, 4. full outer join, and
5. cross join.

STAFF TABLE:-

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

ID STAFF_NAME STAFF_AGE STAFF_ADDRESS PACKAGE

1 ARYAN 22 MUMBAI 18000

2 SUSHIL 32 DELHI 20000

3 MONTY 25 MOHALI 22000

4 AMIT 20 ALLAHABAD 12000

PAYMENT TABLE:-
PAY_ID DATE STAFF_ID AMOUNT

101 30/12/09 1 3000

102 22/02/10 3 2500

103 23/02/10 4 3500

SELECT STAFF_ID, STAFF_NAME, STAFF_AGE, AMOUNT

FROM STAFF s, PAYMENT p


WHERE s.ID =p.STAFF_ID;

OUTPUT:-
STAFF-ID NAME STAFF_AGE AMOUNT

3 MONTY 25 2500

1 ARYAN 22 3000

4 AMIT 25 3500

SQL FULL JOIN


SQL full outer join is used to combine the result of both left and right outer join and returns all rows

(don't care its matched or unmatched) from the both participating tables.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

TABLE A:-
A M

1 m

2 n

4 o

TABLE B:-

A N

2 p

3 q

5 r

FOR EXAMPLE:-

SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;

OUTPUT:-

A M A N

2 n 2 p

1 m - -

4 o - -

- - 3 q

- - 5 r

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SEQUENCES:-

Sequences are frequently used in 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 simplest way in MySQL to use sequences is to define a column as AUTO_INCREMENT and
leave the rest to SQL to take care.

FOR EXAMPLE:-

CREATE TABLE INSECT (

Id INT UNSIGNED NOT NULL AUTO_INCREMENT,


PRIMARY KEY (id) Name

VARCHAR(30) NOT NULL, date

DATE NOT NULL, origin

VARCHAR(30) NOT NULL

);

INSERT INTO INSECT (id, name, date, origin) VALUES

(NULL, ‘HOUSEFLY’, ‘2001-09-10’,’KITCHEN’),

(NULL, ‘MILLIPEDE’, ‘2001-09-10’, ‘DRIVEWAY’ );

OUTPUT:-

ID NAME DATE ORIGIN

1 HOUSEFLY 2001-09-10 KITCHEN

2 MILLEPEDE 2001-09-10 DRIVEWAY

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

EXPERIMENT-5

Views, Indexes, Database Security and Privileges: Grant and Revoke Commands,
Commit and Rollback Commands.

SQL CREATE VIEW Statement


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.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data were
coming from one single table.

CREATE VIEW Syntax


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

Consider the table STUDENT:-

S ID CLASS

1 11

2 12

3 11

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

4 12

For Example :-
CREATE View class 11 as

SELECT * FROM STUDENT

WHERE CLASS=11;

SQL Index
o Indexes are special lookup tables. It is used to retrieve data from the database very fast.
o An Index is used to speed up select queries and where clauses. But it shows down the data input with
insert and update statements. Indexes can be created or dropped without affecting the data.
o An index in a database is just like an index in the back of a book.
o For example: When you reference all pages in a book that discusses a certain topic, you first have to
refer to the index, which alphabetically lists all the topics and then referred to one or more specific
page numbers.

1. Create Index statement


It is used to create an index on a table. It allows duplicate value.

Syntax:-

CREATE INDEX index_name


ON table_name (column1, column2, ...);

CREATE INDEX idx_name


ON Persons (LastName, FirstName);

2. Unique Index statement


It is used to create a unique index on a table. It does not allow duplicate value.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Syntax:-

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Example:-

CREATE UNIQUE INDEX websites_idx


ON websites (site_name);

3. Drop Index Statement


It is used to delete an index in a table.

Syntax:-

DROP INDEX index_name;

For Example:-

DROP INDEX websites_idx;

GRANT Statement:-
The grant statement enables system administrators to assign privileges and roles to the MySQL user
accounts so that they can use the assigned permission on the database whenever required.

Syntax:-

GRANT privilege_name(s)
ON object
TO user_account_name;
MySQL Revoke Privilege
MySQL provides REVOKE statements to remove privileges from a user account.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

REVOKE Statement:-
The revoke statement enables system administrators to revoke privileges and roles to the MySQL user
accounts so that they cannot use the assigned permission on the database in the past.

Syntax:-

The following are the basic syntax of using the REVOKE statement:

REVOKE privilege_name(s)
ON object
FROM user_account_name;

The commands are used to control the transactions, these commands are given below-

o COMMIT- It is used to save the changes. o ROLLBACK-


ROLLBACK is used to roll back the changes.

COMMIT Command
It is also known as Transactional Command. The command is used by the database to save changes.

Syntax:

COMMIT;

For example:-

Consider the table EMPLOYEE:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

3 ASHISH 1500 19

4 HARSH 4000 19

Begin Tran
DELETE FROM EMPLOYEES
WHERE AGE = 29 COMMIT

OUTPUT:-

SL NO. NAME SALARY AGE

1 HARSH 2000 19

3 ASHISH 1500 19

4 HARSH 4000 19

ROLLBACK Command:
The ROLLBACK command is the transactional command used to undo transactions that have not already
been saved to the database. Rollback command is used to undo the set of transactions.

Syntax:

ROLLBACK

For example:-
Begin Tran
DELETE FROM EMPLOYEES
WHERE AGE = 29; ROLLBACK

OUTPUT:-

The delete operations have no effect on the result of the table.

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SL NO. NAME SALARY AGE

1 HARSH 2000 19

2 DHANRAJ 3000 29

3 ASHISH 1500 19

4 HARSH 4000 19

EXPERIMENT-6

PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL Code,


Referencing Non-SQL parameters.

PL/SQL Architecture
The PL/SQL is a case insensitive, a robust procedural extension of the SQL. The SQL
allows its statements to be directly included in the PL/SQL blocks and still looks like a
single language together as they are tightly coupled with each other as there are no APIs
needed to bind them together unlike other programming languages.

PLSQL Block Structure


The structure of a PL/SQL block consists of the below four primary sections.

1. Header
2. Declaration
3. Execution
4. Exception

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

PL/SQL assignments and expressions:-


Write a program that declares an integer variable called num, assigns a value to it, and computes and
inserts into the tempp table the value of the variable itself, its square, and its cube.

For example:-
CREATE TABLE tempp ( item number, square number, CUBE number );

TABLE created.

DECLARE num number:=&num;


BEGIN

INSERT INTO tempp VALUES(num,

num*num,

num*num*num);

END;

Enter value FOR num: 5

SELECT * FROM tempp;

OUTPUT:-

ITEM SQUARE CUBE

5 25 125

PL/SQL CODE:-
DECLARE
VAR1 NUMBER;
VAR2 NUMBER;

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

BEGIN
VAR1:=200;
VAR2:=1;
WHILE (VAR2<=5)
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
VAR2:=VAR2+1;
END LOOP;
END;

OUTPUT:-

200
400
600
800
1000

Parameters Modes:-
IN mode- Default; Passes a constant value from the calling environment to the procedure

Create or replace procedure raise_salary

(p_id IN employees.emp_id%type)

IS

Begin

Update employees set

salary=salary*0.10

where emp_id=p_id

End raise_salary;

OUT Mode- Passes a value from procedure to the calling environment

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

DECLARE

emp_num NUMBER(6) := 120;

bonus NUMBER(6) := 50;

emp_last_name VARCHAR2(25); PROCEDURE

raise_salary (emp_id IN NUMBER, amount IN

NUMBER,

emp_name OUT VARCHAR2) IS

BEGIN

UPDATE employees SET salary = salary

+ amount WHERE employee_id = emp_id;

SELECT last_name INTO emp_name

FROM employees

WHERE employee_id = emp_id;

END raise_salary;

BEGIN

raise_salary(emp_num, bonus, emp_last_name);

DBMS_OUTPUT.PUT_LINE

('Salary was updated for: ' || emp_last_name);

END;

IN OUT Mode- Passes a constant value from the calling environment to the procedure and a
possibly different value from procedure to the calling environment using the same parameter.

CREATE OR REPLACE PROCEDURE SWAP_TEST AS

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

A NUMBER := 3;

B NUMBER := 8;

PROCEDURE MY_SWAP(X IN OUT NUMBER,Y IN OUT NUMBER) AS

T NUMBER;

BEGIN
T := X;

X := Y;

Y := T;

END MY_SWAP;

BEGIN

12 MY_SWAP(A,B);

13 DBMS_OUTPUT.PUT_LINE('A = ' || TO_CHAR(A));

14 DBMS_OUTPUT.PUT_LINE('B = ' || TO_CHAR(B));

15 END;

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

EXPERIMENT-7

Stored Procedures and Exceptional Handling.

Stored Procedures
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task.

This is similar to a procedure in other programming languages.

SYNTAX:-

CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]


IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
For example:-

CREATE OR REPLACE PROCEDURE employer_details


IS
CURSOR emp_cur IS
SELECT first_name, last_name, salary FROM emp_tbl; emp_rec
emp_cur%rowtype;
BEGIN
FOR emp_rec in sales_cur
LOOP
dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
|| ' ' ||emp_cur.salary);
END LOOP;
END;

Exception Handling in PL/SQL


Last Updated: 28-04-2018

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

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.

Syntax :-
WHEN exception THEN
Statement;
Consider the table STUDENT :-

ID NAME MARKS
1 AKSHAY 100
2 PRAVEEN 97
3 JESSIE 99
For example:-

DECLARE

temp varchar(20);

BEGIN
SELECT ID into temp from STUDENT where NAME='RAHUL';

exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR:');
dbms_output.put_line('there is no name as');
dbms_output.put_line(' RAHUL in STUDENT table');
end;

OUTPUT:-

ERROR: There is no name as RAHUL in STUDENT table

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

EXPERIMENT-8

Triggers and Cursor Management in PL/SQL.

TRIGGERS:-

Triggers are stored programs, which are automatically executed or fired when some events

occur.

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

CREATING TRIGGERS:-

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

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

Exception-handling-statements

END;

CONSIDER THE TABLE 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 Chaitalli 25 Mumbai 6500.00

5 Hardik 27 Bhopal 8500.00

6 Komal 22 MP 4500.00

FOR EXAMPLE:-

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;

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

OUTPUT:-
Trigger created.

INSERT INTO CUSTOMERS (ID, NAME, AGE,A DDRESS, SALARY)


VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

RESULT:-
Old salary:
New salary: 7500
Salary difference:

CURSORS:-
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds
the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the
active set.

There are two types of cursors −

• Implicit cursors
• Explicit cursors

For example:-

DECLARE
total_rows number(2);
BEGIN
UPDATE CUSTOMERS

Downloaded by Malik Kamran ([email protected])


lOMoARcPSD|25077524

SET SALARY = SALARY+ 500;


IF sql%notfound THEN

dbms_output.put_line('no customers selected');


ELSIF sql%found THEN total_rows := sql
%rowcount;

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


END IF;
END;

OUTPUT:-

ID NAME AGE ADDRESS SALARY

1 Ramesh 32 Ahmedabad 2500.00

2 Khilan 25 Delhi 2000.00

3 Kaushik 23 Kota 2500.00

4 Chaitalli 25 Mumbai 7000.00

5 Hardik 27 Bhopal 9000.00

6 Komal 22 MP 5000.00

Downloaded by Malik Kamran ([email protected])

You might also like