0% found this document useful (0 votes)
44 views79 pages

Database Management System Overview

This document is a practical file for a Database Management System course, detailing SQL concepts and commands. It covers definitions of data, information, and databases, along with advantages and disadvantages of DBMS, types of SQL commands, and practical exercises for creating and manipulating database tables. Additionally, it provides instructions for using Oracle Live SQL and creating an account on the platform.

Uploaded by

navreetkaur3011
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)
44 views79 pages

Database Management System Overview

This document is a practical file for a Database Management System course, detailing SQL concepts and commands. It covers definitions of data, information, and databases, along with advantages and disadvantages of DBMS, types of SQL commands, and practical exercises for creating and manipulating database tables. Additionally, it provides instructions for using Oracle Live SQL and creating an account on the platform.

Uploaded by

navreetkaur3011
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

Practical File

Of
Database Management System

Submitted to: Submitted by:


Prof. Kamalpreet Kaur Navreet Kaur
Roll no. : 2300426
Semester : 5th

Department Of Computer Science And Engineering

Baba Banda Singh Bahadur Engineering College


Fatehgarh sahib
INDEX

[Link] Task Remarks


Practical - 1

Introduction to SQL and Steps to create an account on Oracle live SQL.


Basic Definitions:

Data:
Data refers to raw, unorganized facts, numbers, symbols, or observations that by themselves
have no specific meaning. It can exist in various forms such as text, numbers, images, audio,
or video. Only after processing and interpretation does data become meaningful.
Example: “1500,” “Blue,” and “Delhi” — individually, these values have no direct meaning
until combined and contextualized.

Information:
Information is the result of processing, organizing, and structuring data in a way that adds
context, relevance, and meaning, making it useful for decision-making. Information provides

answers to “who,” “what,” “where,” and “when” questions.

Example: “The warehouse in Delhi has 1500 blue chairs in stock” — here, the raw data has
been processed to convey clear meaning.

Database:
A database is an organized and structured collection of data, stored electronically in a
computer system, designed to be easily accessed, managed, and updated. Modern databases
are typically managed by Database Management Systems (DBMS), which allow multiple
users to store, retrieve, and manipulate data efficiently. Data in a database is arranged in
tables consisting of rows (records) and columns (fields). SQL (Structured Query Language)
is the most widely used language for interacting with relational databases.
Examples:

1. University Management System for storing student enrollment, grades, and attendance.
2. E-commerce Platform Database for managing product catalogs, customer details, and
orders.
3. Hospital Management System for maintaining patient records, appointments, and
treatment history.
DBMS (Database Management System): A Database Management System (DBMS) is
software used to create, manage, and operate databases. It provides an interface for performing
tasks such as creating databases, storing and updating data, creating tables, and executing
queries. Examples include MySQL, Oracle, PostgreSQL, and SQL Server. DBMS ensures
security, consistency, and efficient management of data, even in multi-user environments.

Advantages of DBMS:

1. Elimination of Redundancy:
In traditional file systems, duplicate data often exists in multiple locations, wasting storage
space. DBMS integrates all data into a single database, reducing duplication.
2. High-Level Security:
DBMS ensures that only authorized users can access the database through secure
credentials, protecting sensitive information.
3. Data Integrity;
It unifies multiple data sources into a single repository, reducing duplication and
maintaining consistency.
4. Consistency Control:
Centralized storage ensures that updates are reflected across the system, reducing
inconsistencies.
5. Data Sharing:
Authorized users can share and access data according to assigned permissions. The
database administrator (DBA) can control and manage user rights.
6. Access Restriction:
Unauthorized access is prevented through authentication and authorization mechanisms.

Disadvantages of DBMS:

1. Complexity
DBMS systems are sophisticated, requiring skilled database designers, developers, and
administrators to ensure optimal use. Poor design decisions can lead to serious operational
issues.
2. Large Size:
Advanced DBMS software requires significant storage space due to its extensive
functionalities.
3. Performance Overhead:
The additional features and security layers can result in slower performance compared to
simpler file-based systems.
4. High Impact of Failure:
Since the DBMS is a central component, its failure can halt operations for all users and
applications.
5. Cost
DBMS solutions can be expensive to purchase and maintain, with additional costs for
licenses, training, and annual maintenance.

RDBMS (Relational Database Management System):

A Relational Database Management System is an advanced form of DBMS that stores and
manages data in the form of structured tables (rows and columns). It enables efficient storage,
retrieval, and management of related data by using relationships between tables. Popular
examples include MySQL, Oracle Database, PostgreSQL, MS SQL Server, and IBM DB2.

SQL (Structured Query Language):

SQL is a standardized language used to interact with and manage relational databases. It allows
users to create, modify, retrieve, and manipulate data stored in tables. SQL is recognized as an
ANSI (American National Standards Institute) standard, though different RDBMS systems
implement their own dialects:

1. T-SQLMicrosoft SQL Server


2. PL/SQL – Oracle Database
3. JET SQL – Microsoft Access

Uses of SQL:

1. Enables access to data stored in relational databases.


2. Allows defining, describing, and manipulating data.
3. Supports embedding SQL in other programming languages through modules, libraries, and
precompilers.
4. Facilitates creation and deletion of databases and tables.
5. Supports creation of views, stored procedures, and functions.
Key Capabilities of SQL:

1. Execute queries against a database.


2. Retrieve specific data from tables.
3. Insert new records into a database.
4. Update existing records.
5. Delete records from a database.
6. Create new databases and tables.
7. Define and manage stored procedures.
8. Create and manage views.

Types of SQL:

Fig 1.1
1. Data Definition Language (DDL) :
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:

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


CREATE TABLE TABLE_NAME (COLUMN_NAME
DATATYPES[,....]); Example:
CREATE TABLE EMPLOYEE (Name VARCHAR2(20), Email
VARCHAR2(100), DOB DATE);
2. DROP: It is used to delete both the structure and record stored in the table. Syntax:
DROP TABLE table_name; Example:
DROP TABLE EMPLOYEE;
3. 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:

1. To add a new column in the table


ALTER TABLE table_name ADD column_name COLUMN-definition;
2. To modify existing column in the table:
ALTER TABLE table_name MODIFY(column_definitions....); Example:

ALTER TABLE STU_DETAILS ADD(ADDRESS


VARCHAR2(20)); ALTER TABLE STU_DETAILS MODIFY (NAME
VARCHAR2(20));

4. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table. Syntax:
TRUNCATE TABLE table_name; Example:
TRUNCATE TABLE EMPLOYEE;

2. 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:
1. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of a
table. Syntax: INSERT INTO TABLE_NAME (col1, col2, col3,.... col N) VALUES
(value1, value2, value3, .... valueN); Or
INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, .... valueN); Example:
INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");
2. UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION] For example: UPDATE students
SET User_Name = 'Sonoo' WHERE
Student_Id = '3'
3. DELETE: It is used to remove one or more row from a table.
Syntax:
DELETE FROM table_name [WHERE condition]; For example:
DELETE FROM javatpoint WHERE
Author="Sonoo";

3. Data Control Language:

DCL commands are used to grant and take back authority from any database user. Here are
some commands that come under DCL:

1. Grant: It is used to give user access privileges to a database.


Example:GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER,
ANOTHER_USER;
2. Revoke: It is used to take back permissions from the user.
Example: REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language :

TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only. These operations are automatically committed in the database that's why they cannot be
used while creating tables or dropping them. Here are some commands that come under TCL:

1. Commit: Commit command is used to save all the transactions to the database.
Syntax: COMMIT; Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25; COMMIT;
2. Rollback: Rollback command is used to undo transactions that have not already been saved
to the database.
Syntax: ROLLBACK; Example:
DELETE FROM CUSTOMERS
WHERE AGE = 25;
ROLLBACK;
SAVEPOINT: It is used to roll the transaction back to a certain point without rolling back
the entire transaction.
Syntax: SAVEPOINT SAVEPOINT_NAME;

5. Data Query Language :

DQL is used to fetch the data from the [Link] uses only one command:
SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause. Syntax:
SELECT expressions
FROM TABLES WHERE conditions; For example:
SELECT emp_name
FROM employee
WHERE age > 20;

Oracle live SQL:


Oracle recently introduced a new generation online SQL tool, called Live SQL. Live
SQL is a kind of search engine for database developers but also a great free learning
tool for those of you who want to learn and code SQL on an Oracle Database. Oracle
Live SQL is a web-based tool that allows you to access an Oracle database without
installing any software on your own computer.

Latest Oracle version: Oracle Database 19c

Oracle Database 19c was released back in January 2019 on Oracle Live SQL and is the
final release of the Oracle Database 12c product family. Oracle Database 19c comes
with four years of premium support and a minimum of three extended support.

Steps to create an account on Oracle Live SQL:

Step 1: Search Oracle Live SQL in web browser and click on [Link]
Fig 1.2
Step 2: Click on start coding now.

Fig 1.3

Fig. 1.4
Step 3: If user don’t have any account and click on create account

Step 4: Fill all the details

Step 5: After filling details click on create account.


Fig 1.5

Step 6: After creating account user got a verification e mail.

Fig 1.6
Step 7: Now user is able to code in Orcale Live SQL.
Now :

Go to [Link] start coding now oracle account sign in


and click on sign in

( Here username is user’s e mail id (that user fill during oracle account creation) and password
: that user enter during oracle account creation )

Fig 1.7
Fig 1.8
Practical – 2
Used of CREATE, ALTER, RENAME and DROP statement in the database tables
(relations).

Data Definition Language (DDL):

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.

1. CREATE a table :
It is use to create a new table in a database where you can store data in rows and columns.

Syntax:

CREATE TABLE table_name( column_name datatype, column_name2 datatype…..,


column_name n datatype));

INPUT:

OUTPUT:

2. ALTER a table:
It is used to modify the structure of an existing table without deleting it.

Syntax:

1. To add a new column in the table ALTER TABLE table_name ADD column_name
COLUMN-definition;

2. To modify existing column in the table: ALTER TABLE table_name


MODIFY(column_definitions....);
INPUT:

OUTPUT:

3. DROP statement in a table:


It is used to completely delete a table and all of its data from the databases.

Syntax:

DROP TABLE table_name;

INPUT:
OUTPUT:

4. RENAME a table:
RENAME in table means changing the name of the entire table or name of a column inside a
table.

Syntax:

RENAME old_table _name To new_table_name ;

INPUT:

OUTPUT:
Practical-3
Use of INSERT INTO, DELETE and UPDATE statement in database
tables.
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.
INSERT INTO:
This statement used to add new rows (records) of data into a table within a relational database.
Syntax:
INSERT INTO TABLE_NAME VALUES (value1, value2, value3, ....valueN);
Input:

Output:

DELETE: It is used to remove one or more row from a table.


Syntax:
DELETE FROM table_name [WHERE condition];
Input:
Output:

UPDATE: This command is used to update or modify the value of a column in the table.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN]
[WHERE CONDITION] ;
Input:

Output:
Practical - 4

Use of Simple select statement, select distinct, where and order by.

SELECT Statement:
The SELECT statement is used to select data from a database. It is used to retrieve data from
one or more tables in a database.
Syntax:
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, ... are the field names of the table you want to select data from.
The table_name represents the name of the table you want to select data from.
Example:
Input:

Output:

Select ALL columns:


If you want to return all columns, without specifying every column name, you can use the
SELECT *
Syntax:
SELECT * FROM table_name;
Example:
Input:

Output:

SELECT DISTINCT Statement:


The SELECT DISTINCT statement is used to return only distinct (different) values.
Syntax:
SELECT DISTINCT column1, column2,…
FROM table_name;
Example:

Output:
SELECT Example Without DISTINCT:
If you omit the DISTINCT keyword, the SQL statement returns the "Last name" value from all
the records of the "STUDENT" table.
Syntax:
SELECT LNAME FROM Student;
Example:
Input:

Output:

WHERE Clause:
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;
Example:
Input:
Output:

SQL ORDER BY:


The ORDER BY keyword is used to sort the result-set in ascending or descending order.
SELECT column1, column2,…
FROM table_name
ORDER BY column1, column2,….ASC|DESC;
Example:
Input:

Output:

DESC:
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.
Syntax:
SELECT * FROM table_name
ORDER BY column_name DESC;
Example:
Input:

Output:

Order Alphabetically:
For string values the ORDER BY keyword will order alphabetically.
Syntax:
SELECT * FROM table_name
ORDER BY column_name;
Example:
Input:
Output:

Alphabetically DESC:
To sort the table reverse alphabetically, use the DESC keyword:
Syntax:
SELECT * FROM table_name
ORDER BY column_name DESC;
Example:
Input:

Output:

ORDER BY Several Columns:


The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some
rows have the same Country, it orders them by CustomerName.
Syntax: SELECT * FROM Customers ORDER BY Country, CustomerName;
Example:
Input:
Output:

Using Both ASC and DESC:


Syntax:SELECT * FROM table_name ORDER BY column_name,… DESC;
Example:
Input:

Output:
Operators used in the WHERE clause:

1. Equal (=):
Syntax:
SELECT * FROM table_name
WHERE column_name = value;
Example:
Input:

Output:

2. Less than (<) and Greater than(>):


Syntax:
Less than (<): SELECT * FROM table_name WHERE column_name < value;
Greater than(>): SELECT * FROM table_name WHERE column_name > value;
Example:
Input:
Output:

3. Greater than or equal to (>=) and less than or equal to (<=):


Syntax:
Greater than or equal to (>=):
SELECT * FROM table_name
WHERE column_name >= value;
Less than or equal to (<=):
SELECT * FROM table_name
WHERE column_name <= value;
Example:
Input:

Output:
4. Not equal to (< >):
Syntax:
SELECT * FROM table_name
WHERE column_name < > value;
Example:
Input:

Output:

5. Between, Like and In:


Syntax:
Between:
SELECT * FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Like:
SELECT * FROM table_name
WHERE column_name LIKE pattern;
In:
SELECT * FROM table_name
WHERE column_name IN (value1, value2, value3, …..);
Example:
Input:

Output:

6. AND Operator:
The WHERE clause can contain one or many AND operators. The AND operator is used
to filter records based on more than one condition.
Syntax:
SELECT column1, column2, …. FROM table_name WHERE condition1 AND condition2
AND condition3 ….;
Example:
Input:
Output:

7. OR Operator:
The WHERE clause can contain one or more OR operators. The OR operator is used to
filter records based on more than one condition.
Syntax:
SELECT column1, column2, …. FROM table_name WHERE condition1 OR condition2
OR condition3, ….;
Example:
Input:

Output:

8. Combining AND and OR:


Syntax:
SELECT * FROM table_name
WHERE column_name= 'value' AND (column_name LIKE 'pattern' OR column_name
LIKE ‘pattern’);
Example:
Input:
Output:

9. NOT Operator:
The NOT operator is used in combination with other operators to give the opposite result,
also called the negative result.
Syntax:
SELECT column1, column2, ... FROM table_name WHERE NOT condition;
Example:
Input:

Output:
10. NOT LIKE , NOT BETWEEN and NOT IN:
Example:
Input:

Output:

11. NOT GREATER THAN and LESS THAN:


Example:
Input:

Output:
Practical – 5

Working with Null Values, Matching a Pattern from a Table, Ordering the Result of a
Query, Aggregate Functions, Grouping the result of a query, Update and Delete Statements.

NULL Values:

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. It is not possible to test for Null Values with comparison operators,
such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL:

The IS NULL operator is used to test for empty values.

Syntax:

SELECT column_names
FROM table_name
WHERE column_name IS NULL;
Example:

Input:

Output:

IS NOT NULL:

The IS NULL operator is also used to test for empty values. Syntax:
SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Example:

Input:

Output:

UPDATE :

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

Syntax:

UPDATE table_name
SET column1 = value1, column2 = value2, …
WHERE condition;
Example:

Input:

Output:
DELETE:

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

Syntax:

DELETE FROM table_name WHERE condition;

Example:

Input:

Output:

Aggregate Functions:

An aggregate function is a function that performs a calculation on a set of values, and returns a
single value. Aggregate functions are often used with the GROUP BY clause of the SELECT
statement. The GROUP BY clause splits the result-set into groups of values and the aggregate
function can be used to return a single value for each group. Aggregate functions ignore null values
(except for COUNT(*)).

The most commonly used SQL aggregate functions are:

 MIN() - returns the smallest value within the selected column


 MAX() - returns the largest value within the selected column
 COUNT() - returns the number of rows in a set
 SUM() - returns the total sum of a numerical column
 AVG() - returns the average value of a numerical column

MIN() Function:

The MIN() function returns the smallest value of the selected column.

Syntax:

SELECT MIN(column_name)
FROM table_name
WHERE condition;
Example:

Input:

Output:

MAX() Function:

The MAX() function returns the largest value of the selected column.

Syntax:

SELECT MAX(column_name)
FROM table_name
WHERE condition;
Example:

Input:
Output:

Set Column Name (Alias):

When you use MIN() or MAX(), the returned column will not have a descriptive name. To give
the column a descriptive name, use the AS keyword.

Example:

Input:

Output:

MIN() with GROUP BY:

The MIN() function and the GROUP BY clause, to return the smallest Student roll number for
each category of Postal code

Example:
Input:

Output:

COUNT() Function:

The COUNT() function returns the number of rows that matches a specified criterion.

Syntax:

SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Input:

Output:

Specify Column:
We can specify a column name instead of the asterix symbol (*). If we specify a column name
instead of (*), NULL values will not be counted.

Example:

Input:

Output:

Add a WHERE Clause:

Input:

Output:

Ignore Duplicates:

We can ignore duplicates by using the DISTINCT keyword in the COUNT() function.
If DISTINCT is specified, rows with the same value for the specified column will be counted as
one.
Input:

Output:

SQL SUM() Function:

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

Syntax:

SELECT SUM(column_name)
FROM table_name
WHERE condition;
Example:

Input:

Output:
AVG() Function:

The AVG() function returns the average value of a numeric column.

Syntax:

SELECT AVG(column_name)
FROM table_name
WHERE condition;
Example:

Input:

Output:
Practical – 6

Set Operators, Nested queries, joins, Sequences.


SQL Operators:

1. Arithmetic Operators
Following are the arithmetic operators used in SQL:

Operator Description
Addition
+
Subtraction
-
Multiplication
*
Division
/
Modulo
%
ADD Operator:
Input:

Output:

SUBTRACT Operator:
Input:
Output:

MULTIPLY Operator:
Input:

Output:

DIVIDE Operator:
Input:

Output:
MODULO Operator:
Input:

Output:

2. Bitwise Operators
Following are the Bitwise operators used in SQL:

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

Input:
Output:

3. Comparison Operators

Operator Description

= Equals to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not Equal to

Input:
Output:

4. Compound Operators
Following are the compound operators used in SQL:

Operator Description

+= Add equals

-= Subtract equals

*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals

^= Bitwise exclusive equals

|*= Bitwise OR equals


Input:

Output:

5. Logical Operators
Following are the logical operators used in SQL:

Operator Description

All TRUE if all of the subquery values meet the condition

AND TRUE if all the conditions separated by AND is TRUE

ANY TRUE if any of the subquery values meet the condition

BETWEEN TRUE if the operand is within the range of comparisons

EXISTS TRUE if the subquery returns one or more records

IN TRUE if the operand is equal to one of a list of expressions

LIKE TRUE if the operand matches a pattern


NOT Displays a record if the condition(s) is NOT TRUE

OR TRUE if any of the conditions separated by OR is TRUE

SOME TRUE if any of the subquery values meet the condition

Input:
Output:
SQL Nested Queries:
A nested query (or subquery) is an SQL query placed inside another query to make the overall
operation more structured and readable. The inner query executes first and its result is then used
by the outer query. Subqueries can appear in the SELECT, FROM or WHERE clauses, making
them useful for tasks such as filtering, aggregation and retrieving data based on the results of
another query. They are helpful for breaking down complex SQL operations into smaller,
structured steps that are easier to read and maintain.
There are two primary types of nested queries in SQL:
1. Independent Nested Queries
In an independent nested query, the execution of the inner query is independent of the outer
query. The inner query runs first and its result is used directly by the outer query. Operators
like IN, NOT IN, ANY and ALL are commonly used with independent nested query.
Example:
Input:

Output:

2. Correlated Nested Queries


In correlated nested queries, the inner query depends on the outer query for its execution.
For each row processed by the outer query, the inner query is executed. This means the inner
query references columns from the outer query. The EXISTS keyword is often used with
correlated queries.
Example:
Input:
Output:

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Types of SQL JOINs:
1. INNER JOIN: Returns records that have matching values in both tables

Syntax:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example:
Input:
Output:

2. LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from
the right table

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

3. RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched records
from the left table
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Input:

Output:

4. FULL (OUTER) JOIN: Returns all records when there is a match in either left or right table
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
Example:
Input:

Output:

Self join
self join is a regular join, but the table is joined with itself.
Syntax:
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Example:
Input:

Output:
Practical-7
Views, Indexes, Database Security and Privileges: Grant and Revoke
Commands, Commit and Rollback Commands.
Views in SQL
A view in SQL is a saved SQL query that acts as a virtual table. Unlike regular tables, views do
not store data themselves. Instead, they dynamically generate data by executing the SQL query
defined in the view each time it is accessed.
It can fetch data from one or more tables and present it in a customized format, allowing
developers to:
1. Simplify Complex Queries: Encapsulate complex joins and conditions into a single object.
2. Enhance Security: Restrict access to specific columns or rows.
3. Present Data Flexibly: Provide tailored data views for different users.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;
Example:
Input:
Output:

Indexes in SQL:
Indexes in SQL are special data structures that improve speed of data retrieval operations. They
work like a quick lookup table for the database instead of scanning the entire table row by row,
database can use the index to directly locate the required rows.
1. Creating an Index
There are 3 main ways to create an index in SQL. Let’s look at them one by one.
1.1. Single Column Indexes
A single-column index is created on just one column. It’s the most basic type of index and helps
speed up queries when you frequently search, filter or sort by that column.
Syntax:
CREATE INDEX index ON TABLE column;
1.2. Multi Column Indexes
A multi-column index is created on two or more columns. It improves performance when queries
filter or join based on multiple columns together.
Syntax:
CREATE INDEX index ON TABLE (column1, column2,.....);
1.3. Unique Indexes
A unique index ensures that all values in a column (or combination of columns) are unique
preventing duplicates and maintaining data integrity.
Syntax:
CREATE UNIQUE INDEX index_name ON table_name (column_name);
Example:
Input:
Output:

2. Removing an Index
Indexes take up storage and add overhead on write operations (INSERT, UPDATE, DELETE).
If an index is no longer needed, it can be removed.
Syntax:
DROP INDEX index_name;
3. Altering an Index
If an index requires adjustments, such as reorganizing or rebuilding, it can be altered without
affecting the data. This is useful for optimizing index performance as tables grow larger.
Syntax:
ALTER INDEX IndexName ON TableName REBUILD;
4. Confirming and Viewing Indexes
We can view all the indexes in a database to understand which ones are in use and confirm their
structure. In SQL, the following query helps us see the indexes for a given table:
Syntax:
SHOW INDEXES FROM table_name;
5. Renaming an Index
In some cases, renaming an index might be necessary for clarity or consistency. While SQL does
not directly support renaming indexes, we can use a combination of commands to achieve this.
Syntax:
EXEC sp_rename 'old_index_name', 'new_index_name', 'INDEX';
1. GRANT:
The GRANT command is part of Data Control Language (DCL) and is used to provide specific
privileges or permissions to users or roles on database objects (e.g., tables, views, procedures).
Example:
GRANT SELECT, INSERT ON Employees TO JohnDoe;
This example grants SELECT and INSERT privileges on the Employees table to the user JohnDoe.
2. REVOKE:
The REVOKE command is also part of DCL and is used to remove privileges that were previously
granted to users or roles.
Example:
REVOKE INSERT ON Employees FROM JohnDoe;
This example revokes the INSERT privilege on the Employees table from the user JohnDoe.
3. COMMIT:
The COMMIT command is part of Transaction Control Language (TCL) and is used to
permanently save all changes made during the current transaction. Once a transaction is
committed, the changes become a permanent part of the database and cannot be undone by
a ROLLBACK command.
Example:
INSERT INTO Products (ProductID, ProductName) VALUES (101, 'Widget');
COMMIT;
This example inserts a new row into the Products table and then permanently saves that change.
4. ROLLBACK:
The ROLLBACK command is also part of TCL and is used to undo all changes made during the
current transaction since the last COMMIT or the beginning of the transaction. This is useful for
reverting to a previous state if an error occurs or if the changes are not desired.
Example:
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 123;
ROLLBACK;
This example updates an account balance and then, assuming an issue, undoes that change,
restoring the balance to its state before the UPDATE statement. ROLLBACK can also be used
with SAVEPOINT to revert to a specific point within a transaction.
Practical- 8

PL/SQL Archietecture , Assignments and expressions, Writing PL/SQL Code, Referencing


Non- SQL parameters.

The PL/SQL runtime system is a technology and not an independent product. This technology
is actually like an engine that exhibits PL/SQL blocks, subprograms like functions and
procedures. This engine can be installed in an Oracle Server or in application development tools
such as Oracle Form Builder, Oracle Reports Builder etc.

PL/SQL can reside in two environments -


1. The Oracle Server
2. The Oracle tools
These two environments are independent of each other. In either environment, the PL/SQL
engine accepts any valid PL/SQL block as input. The PL/SQL engine executes the procedural
part of the statements and sends the SQL statement executer in the Oracle Server. A single
transfer is required to send the block from the application to the Oracle Server, thus improving
performance, especially in a Client-Server network. PL/SQL code can also be stored in the
Oracle server as subprograms that can be referenced by any number of applications connected
to the database.

Advantages of PL/SQL :
 PL/SQL provides better performance.
 PL/SQL has high Productivity.
 It supports Object-Oriented Programming concepts.
 It has Scalability and Manageability.
 PL/SQL supports various Web Application Development tools.

Disadvantages of PL/SQL :
 PL/SQL requires high memory.
 Lacks of functionality debugging in stored procedures.

Basic syntax of PL/SQL:

PL/SQL which is a block structured language, this means that the PL/SQL programs are divided
and written in logical blocks of code. Each block consists of three sub-parts:

1. Declarations

This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.

2. Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a mandatory section.
It consists of the executable PL/SQL statements of the program. It should have at least one
executable line of code, which may be just a NULL command to indicate that nothing should be
executed.

3. Exception Handling

This section starts with the keyword EXCEPTION. This optional section contains exception(s)
that handle errors in the program.

Syntax:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

Example:

Input:
Output:

PL/SQL Identifiers

PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words.
The identifiers consist of a letter optionally followed by more letters, numerals, dollar signs,
underscores, and number signs and should not exceed 30 characters.

PL/SQL Comments

Program comments are explanatory statements that can be included in the PL/SQL code that you
write and helps anyone reading its source code. All programming languages allow some form of
comments. The PL/SQL supports single-line and multi-line comments. All characters available
inside any comment are ignored by the PL/SQL compiler. The PL/SQL single-line comments
start with the delimiter -- (double hyphen) and multi-line comments are enclosed by /* and */.

Example:

Input:

Output:
Variable Declaration in PL/SQL

PL/SQL variables must be declared in the declaration section or in a package as a global


variable. When you declare a variable, PL/SQL allocates memory for the variable's value and
the storage location is identified by the variable name.

Syntax:

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Initializing Variables in PL/SQL

Whenever you declare a variable, PL/SQL assigns it a default value of NULL. If you want to
initialize a variable with a value other than the NULL value, you can do so during the
declaration, using either of the following −

1. The DEFAULT keyword


2. The assignment operator

Example:

Input:

Output:

Variable Scope in PL/SQL

PL/SQL allows the nesting of blocks, i.e., each program block may contain another inner block.
If a variable is declared within an inner block, it is not accessible to the outer block. However, if
a variable is declared and accessible to an outer block, it is also accessible to all nested inner
blocks. There are two types of variable scope −

1. Local variables − Variables declared in an inner block and not accessible to outer blocks.

2. Global variables − Variables declared in the outermost block or a package.

Example:

Input:

Output:

PL/SQL Constants and Literals:

Declaring a Constant

A constant is declared using the CONSTANT keyword. It requires an initial value and does not
allow that value to be changed.

Example:

Input:
Output:
PL/SQL Literals

A literal is an explicit numeric, character, string, or Boolean value not represented by an


identifier. For example, TRUE, 786, NULL, 'tutorialspoint' are all literals of type Boolean,
number, or string. PL/SQL, literals are case-sensitive.

Example:

Input;

Output:

Operators in PL/SQL:

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulation. PL/SQL language is rich in built-in operators and provides the following types of
operators:

 Arithmetic operators
 Relational operators
 Comparison operators
 Logical operators
 String operators

Conditions in PL/SQL:

Decision-making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be [Link] is the general form of a typical conditional (i.e., decision
making) structure found in most of the programming languages:
Loops in PL/SQL:

There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. Programming languages provide various control structures that
allow for more complicated execution paths. A loop statement allows us to execute a statement or
group of statements multiple times and following is the general form of a loop statement in most
of the programming languages:

Exceptions in PL/SQL:

An exception is an error condition during a program execution. PL/SQL supports programmers


to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition. There are two types of exceptions:

1. System-defined exceptions

2. User-defined exceptions

Syntax for Exception Handling:


The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others THEN

Example:

Input:

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

Example:

Input:

Ouput:

Cursor in PL/SQL:

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. You can name a cursor so that it could be referred to in a program
to fetch and process the rows returned by the SQL statement, one at a time. There are two types of
cursors −

1. Implicit cursors
2. Explicit cursors
Implicit cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and
the information in [Link] a DML statement (INSERT, UPDATE and DELETE) is issued, an
implicit cursor is associated with this statement. For INSERT operations, the cursor holds the data
that needs to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows
that would be affected. In PL/SQL, you can refer to the most recent implicit cursor as the SQL
cursor, which always has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and
%ROWCOUNT. The SQL cursor has additional attributes, %BULK_ROWCOUNT and
%BULK_EXCEPTIONS, designed for use with the FORALL statement.
Example:
Input:

Output:

Explicit Cursors :
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is:
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
 Declaring the cursor for initializing the memory
 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory
1. Declaring the Cursor:
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example:

2. Opening the Cursor:


Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined cursor
as follows:

3. Fetching the Cursor:


Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows:

4. Closing the Cursor:


Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows:

Example:

Input:
Output:

Records in PL/SQL:

A record is a data structure that can hold data items of different kinds. Records consist of different
fields, similar to a row of a database table. PL/SQL can handle the following types of records:

 Table-based
 Cursor-based records
 User-defined records

Table-Based Records

The %ROWTYPE attribute enables a programmer to create table-based and cursor based records.
The following example illustrates the concept of table-based records.
Input:
Output:

Cursor-Based Records

The following example illustrates the concept of cursor-based records. We will be using the
CUSTOMERS table we had created and used in the previous chapters:

Input:

Output:
User-Defined Records

PL/SQL provides a user-defined record type that allows you to define the different record
structures. These records consist of different fields. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

Triggers in PL/SQL:
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.
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).

Benefits of Triggers:
Triggers can be written for the following purposes :
 Generating some derived column values automatically
 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Creating Triggers:
The syntax for creating a trigger is :
Example:
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values.
Input:

Output:

Common questions

Powered by AI

COMMIT and ROLLBACK are both part of Transaction Control Language (TCL) used to manage changes made by DML commands like INSERT, DELETE, and UPDATE. COMMIT permanently saves all the transactions to the database, meaning that the changes cannot be undone . On the other hand, ROLLBACK undoes all changes made in the current transaction since the last COMMIT or to the beginning of a transaction. This means that if a ROLLBACK is executed after a set of DML operations, none of those changes are saved permanently, which is useful for error handling or when changes are not desired . Thus, while both commands manage transactions, COMMIT finalizes the changes, and ROLLBACK reverts them.

PL/SQL offers several advantages over standard SQL for certain database operations. It provides better performance and productivity with its support for procedural logic, allowing for more complex operations and control structures such as IF and LOOP statements . PL/SQL also supports scalability and manageability through block structures and stored procedures, which promote code reusability and encapsulation . Additionally, it supports Object-Oriented Programming concepts and various web application development tools, enhancing its integration capabilities with other technologies . However, it requires higher memory and lacks some debugging functionalities in stored procedures, which are some trade-offs to consider . These capabilities make PL/SQL suitable for applications requiring complex data manipulation and transaction control beyond the capabilities of standard SQL.

PL/SQL handles exceptions using an EXCEPTION block, which allows developers to define how an application should respond to different types of runtime errors or unusual conditions during program execution. Exceptions in PL/SQL are of two types: system-defined exceptions, which are predefined by PL/SQL, and user-defined exceptions, which developers can define based on specific needs . The exception handling capability in PL/SQL provides significant benefits to developers by enabling them to implement robust error management and maintain application stability. It allows for graceful error handling, resource cleanup, and providing meaningful error messages to users. The syntax for handling exceptions in PL/SQL involves declaring exceptions in the declaration section and handling them in the EXCEPTION block using structured commands like WHEN exception_name THEN . This structured approach to error management helps prevent disruptions in applications and ensures a more logical flow of program execution.

The SELECT and SELECT DISTINCT commands in SQL are used for different purposes in data retrieval. The SELECT command is used to retrieve data from one or more columns in a table, potentially returning duplicate records if multiple records share the same values in the retrieved columns . In contrast, SELECT DISTINCT is used to return only unique, non-duplicate values from the selected columns, filtering out any repeated data . SELECT is typically used when all entries need to be reviewed, including duplicates, whereas SELECT DISTINCT is valuable when unique entries are needed, such as identifying different categories or distinct values within a dataset.

A RENAME operation on a table differs from altering its structure because it involves changing the name of the entire table or columns, thereby updating the identifier rather than changing the structural characteristics or contents of the table. The syntax for renaming a table is RENAME old_table_name TO new_table_name . This does not affect the rows, columns, or data within the table. In contrast, altering the structure of a table, such as adding or modifying columns, involves using the ALTER TABLE command with syntax like ALTER TABLE table_name ADD column_name COLUMN-definition or MODIFY(column_definitions). These operations directly impact the schema of the table, either by adding new data fields or altering existing ones, allowing for significant changes in how data is stored and handled without changing the table’s name.

The ALTER TABLE command can be employed in several ways to manage the structure of a database table. It can be used to add a new column to a table using the syntax ALTER TABLE table_name ADD column_name COLUMN-definition . Additionally, it can modify existing column definitions with the syntax ALTER TABLE table_name MODIFY(column_definitions) to change the characteristics of an existing column . Furthermore, ALTER TABLE can also be used to drop a column from a table or rename an existing table or its columns . These functionalities make ALTER TABLE versatile in adjusting the schema without recreating the table.

The ROLLBACK command, when used with SAVEPOINT, is particularly useful in scenarios where a transaction involves multiple steps or operations, and there is a requirement to undo some of the operations without affecting the entire transaction. SAVEPOINT allows you to set a point within a transaction to which you can revert if needed, thus offering a finer control over which parts of the transaction are rolled back. For example, if an error occurs while processing a part of a transaction after a SAVEPOINT was set, you can use ROLLBACK TO SAVEPOINT_NAME to undo only the operations completed after that SAVEPOINT, while retaining the changes made before it . This is particularly useful in complex transactions where only part of the transaction should be reversed due to issues or changes in requirements.

The GRANT and REVOKE commands in SQL are integral to managing database user privileges. GRANT is used to provide users or user roles with specific permissions on database objects like tables, allowing for operations such as SELECT, INSERT, UPDATE, etc. . For instance, GRANT SELECT, INSERT ON Employees TO JohnDoe grants JohnDoe the ability to query and insert data into the Employees table. Conversely, REVOKE removes these permissions, reversing any granted accesses. For example, REVOKE INSERT ON Employees FROM JohnDoe would withdraw JohnDoe’s ability to insert data into the Employees table . These commands are crucial for enforcing security and controlling access within a database, enabling administrators to define who can interact with what data and at what level.

In PL/SQL, variable scope defines the visibility and accessibility of a variable within the code blocks, meaning where and how a variable can be accessed during program execution. There are two primary types of variable scope in PL/SQL: local scope and global scope . Local variables are those declared within a specific block and are only accessible within that block or its inner blocks, but not beyond. Global variables are defined in the outermost block or within a package, making them accessible to all nested inner blocks. This scoping mechanism is crucial for preventing unintended data manipulation by controlling the access and modification rights of data within different parts of the program, effectively managing data integrity and program modularity. Nested blocks provide encapsulation, where an inner block can access variables declared in an outer block, but not vice-versa.

DELETE and TRUNCATE are both SQL commands used for removing data from a table, but they operate differently and are used in different scenarios. DELETE is a Data Manipulation Language (DML) command that removes specific rows from a table based on a WHERE condition. It is transactional, meaning that changes can be rolled back if not committed, allowing for fine-grained control over which records are removed . In contrast, TRUNCATE is a Data Definition Language (DDL) command that removes all rows from a table, effectively resetting it but does not allow for row-by-row filtering. It is usually faster than DELETE as it does not generate individual row deletions and does not support ROLLBACK, making it suitable for quickly emptying a table when a specific backup is not needed . Therefore, DELETE is preferred when conditional data removal is needed, and TRUNCATE is ideal for quickly clearing a table.

You might also like