0% found this document useful (0 votes)
1 views

DBMS - Module 4

The document provides an introduction to SQL, detailing its role in managing database operations such as data manipulation, definition, and control. It outlines the various types of SQL commands including DDL, DML, DCL, and TCL, along with their respective tasks and components of a DBMS architecture. Additionally, it covers concepts such as views, integrity constraints, cursors, subqueries, and stored procedures, emphasizing their importance in database management and operations.

Uploaded by

manimalasaha257
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)
1 views

DBMS - Module 4

The document provides an introduction to SQL, detailing its role in managing database operations such as data manipulation, definition, and control. It outlines the various types of SQL commands including DDL, DML, DCL, and TCL, along with their respective tasks and components of a DBMS architecture. Additionally, it covers concepts such as views, integrity constraints, cursors, subqueries, and stored procedures, emphasizing their importance in database management and operations.

Uploaded by

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

Introduction to SQL

Introduction
SQL (Structured Query Language) is used to perform operations on the records stored in the database, such
as updating records, inserting records, deleting records, creating and modifying database tables, views, etc.
SQL is not a database system, but it is a query language.

DBMS Languages
A DBMS has appropriate languages and interfaces to express database queries and updates. Database
Language can be used to read, store and update the data in the database.

B
HU
egulo just dekhbi
prev yr eseche (ddl,dcl,dml,tcl)

DDL (Data Definition Language)


DDL is used to define database structure or pattern. It is a set of SQL commands used to create, modify and
delete database structure but not data. It is used to create schema, tables, indexes, constraints etc in the

ER
database. These commands are normally not used by general users, accessing the database via an
application. These are normally used by the DBA to a limited extent. DDL updates a special set of tables called
the data dictionary or data directory.
RE
Tasks under DDL

CREATE It creates objects in the database

ALTER It alters the structure of the database


CA

DROP It deletes objects from the database.

TRUNCATE It removes all records from a table including all spaces allocated for the records.

COMMENT It adds comments to the data dictionary.

RENAME It renames an object.


H

DML (Data Modification Language)


It is a set of SQL commands used to create, modify and delete data in a database but not database structure.
UT

It is used for accessing and manipulating data in a database. It handles user requests. DML statements are
used to manage data within schema objects.

Tasks under DML


YO

SELECT It retrieves data from a database.

INSERT It inserts data into a table.

UPDATE It updates existing data within a table.

DELETE It deletes all records from the table.

MERGE It performs UPSERT operations such as insert and update operations.

CALL It is used to call a structured query language or a Java program.

LOCK TABLE It controls concurrency.


DCL (Data Control Language)
DCL is used to control privileges in databases. It is a set of SQL statements that controls access to data and
to the database. To perform any operation in a database such as creating a table, sequences or viewing we
need privileges.

Privileges are of two types:


●​ System: Creating a session, table etc are all types of system privilege.
●​ Object: Any command or query to work on tables comes under object privilege.

Tasks under DCL

GRANT It gives user access privilege to a database.

REVOKE It takes back permissions from the user.

B
TCL (Transaction Control Language)

HU
TCL is used to run the changes made by the DML statement TCL can be grouped into a logical transaction.

Tasks under TCL

COMMIT It saves the transaction on the database

ROLLBACK It restores the database to its original state since the last commit.

ER
RE
CA

Components of DBMS
A database system is partitioned into modules that deals with each of the responsibilities of the overall
system.
H
UT
YO
DBMS Architecture is divided into four parts.
●​ DBMS Users
●​ Query Processor
●​ Storage Processor
●​ Disk Storage

DBMS Users
Database users are categorized based upon their interaction with the database. Mainly there are four types of
users: Naive User, Application Programmer, Sophisticated User, Database Administrator.

Naive/ End User: End users are the unsophisticated users who don’t have the knowledge of DBMS but they
frequently use the database applications in their daily life to get the desired results.
Example – Railway ticket booking users are naive users, clerks in any bank are naive users because they do
not have any DBMS knowledge but they still use the database to perform their given tasks.

B
Application Programmer: Application programmers are the back end computer professionals who write the

HU
code for an application program. These programs could be written in any programming language such as C,
C++, .Net, Java.

Sophisticated Users: Sophisticated users can be engineers, scientists, business analysts, who are familiar
with the database. They can develop their own database application according to their requirement. They
don’t write the code but they interact with the database by writing SQL queries directly through the query
processor.

ER
Database Administrator: DBA is a person who defines the schema and also controls three levels of
database. The DBA creates the new account id and password for users. DBA is also responsible for the
security of the database. Only authorized users are allowed to access/modify the database. DBA monitors the
recovery and backup, repairs the damage caused by hardware and software failures and provides technical
RE
support. DBA has a special account called DBA account/ Superuser account.

Query Processor
It interprets the request received from and users via an application program into instructions. It also executes
CA

the user requests. Components of query processor include

DDL Interpreter: It processes the DDL into a set of tables containing metadata.

DML Compiler: It processes the DML statements into low level instructions so that they can be executed. It
also optimizes the DML queries.
H

Embedded DML Pre-Compiler: DML statements which are embedded in an application program must be
converted into routine calls by the Embedded DML Pre-compiler.
UT

Query Processor Engines: The query evaluation engine evaluates the SQL commands used to access the
database contents before returning the result of the query.

Storage Manager
YO

Storage Manager also known as Database Control system is a program that provides an interface between the
data stored in the database and the queries received. It executes the DCL queries and also maintains the
consistency and integrity of the database. Following are the components of Storage Manager:

Transaction Manager: It ensures the integrity and consistency of the database before and after transactions
and that concurrent transactions proceed without a conflict.

Authorization Manager: It verifies the user is valid and authenticated for the specific query or request.

File Manager: All the files and data structure of the database are managed by this component.

Buffer Manager: It is responsible for transfer of data between secondary storage and main memory. It also
manages the cache memory.
Recovery Manager: It ensures that the database remains in a consistent state in the event of failures. It
also controls the various backup and recovery operations.

Scheduler: It synchronizes concurrent tasks performed by various users at the same time. It controls the
relative order in which operations to a transaction are executed.

Command Processor: It is responsible for processing the queries passed by the authorization control
module.

Disk Storage
It contains the following components.

Data Files: This component stores the data in the files.

B
Data Dictionary: It contains information about the structure of any database object. It includes the name of
tables, properties, length of properties and number of rows in each table. It also contains association between

HU
database transactions and data items that belong to them, various relationships between database
transactions and their associated data items, query frequency, Constraints on data, information on physical
database design.

Indices: It provides fast and efficient access to data items.

DBMS Table and its Structure


ER
In DBMS the table is called an association and the row in it is the tuple. The tables are the database objects
that can carry the information logically because it is organized in a row and column format. Each row in the
table can store unique information. Each column can store the fields/attributes with records; the Database
management system allows users to create a table, drop, and delete a table. We can also rename the table,
RE
and the DBMS table has its structured format, column names, data type, and size.

View in SQL
A view in SQL is a saved SQL query that acts as a virtual table. It can fetch data from one or more tables and
CA

present it in a customized format, allowing developers to:


●​ Simplify Complex Queries: Encapsulate complex joins and conditions into a single object.
●​ Enhance Security: Restrict access to specific columns or rows.
●​ Present Data Flexibly: Provide tailored data views for different users.

Integrity Constraints
H

Integrity constraints are a set of rules. It is used to maintain the quality of information. These constraints
ensure that the data insertion,updation and other processes have to be performed in such a way that data
UT

integrity is not affected.


YO

Domain Constraint
Domain constraint can be defined as the definition of a valid set of values of an attribute. The datatype of the
domain includes string, character, integer, time and date etc. The value of the attribute must be available in
the corresponding domain.
Entity Integrity Constraint
The entity integrity constraint states that primary key value can not be null. This is because the primary key
value is used to identify rows in a relation and if the primary key has a null value then these rows cannot be
identified. A table can contain a null value other than the primary key field

B
HU
Referential Integrity Constraints
ER
A referential integrity constraint is specified between two tables. It states if a foreign key in table 1 refers to
the primary key in table 2 then every value of the foreign key must be null or be available in table 2.
RE
CA
H
UT

Key Constraints
YO

Keys are the entity set that is used to identify an entity within its entity set uniquely. An entity set can have
multiple keys, but out of which one key can be the primary key. A primary key contains unique values in the
relational table.
Assertion in SQL
Assertions are used to specify additional types of constraints that are outside the scope of built-in relational
model constraints (primary and unique key constraints, referential constraints etc.).

Trigger in SQL
A Trigger in Structured Query Language is a set of procedural statements which are executed automatically
when there is any response to certain events on the particular table in the database. Triggers are used to
protect the data integrity in the database.

Cursor in SQL
In SQL, a cursor is a temporary workstation that is allocated by the database server during the execution of a
statement. It is a database object that allows users to access data of one row at a time. The cursor in SQL is

B
the same as the looping technique of other programming languages. The collection of tuples held by the
cursor is known as the active set.

HU
Implicit Cursor
An implicit cursor is a type of cursor that is automatically created and managed by the database system itself.
When you execute a DML (Data Manipulation Language) statement such as INSERT, UPDATE, or DELETE, or a
SELECT statement that returns only one row, the database system automatically creates an implicit cursor to
handle the operation.

Explicit Cursor ER
An explicit cursor is a user-defined cursor that allows you to manually control the retrieval of rows from a
result set. Unlike implicit cursors, which are automatically managed by the database system, explicit cursors
RE
require you to explicitly declare, open, fetch rows, and close them. Explicit cursors are useful when you need
to process a result set containing multiple rows and perform operations on each row individually. They provide
more control and flexibility compared to implicit cursors.

Life Cycle of Cursor


CA

The life cycle of the cursor is described into the following five stages:

1.​ Declare a Cursor


2.​ Open Cursor
3.​ Fetch Data from Cursor
4.​ Close Cursor Connection
5.​ Deallocate cursor
H

1. Declare a Cursor:
UT

Syntax: DECLARE Cursor_Name CURSOR FOR Select_Statement;


In this syntax, the name and data type of the cursor have to be specified just after the DECLARE keyword.
After that, we have to write the SELECT statement, which defines the result set for the cursor.

2. Open Cursor:
YO

Syntax: OPEN Cursor_Name;


It opens the cursor for storing the data retrieved from the result set.

3. Fetch Cursor:

It fetches the rows for performing the insertion, deletion, and updation operations on the currently active
tuple in the cursor. six options that are used in syntax for fetching data from the cursor:

●​ FIRST: This option allows the system to access only the first record from the cursor table.
Syntax: FETCH FIRST FROM Cursor_Name;

●​ LAST: This option allows the system to access only the last record from the cursor table.
Syntax: FETCH LAST FROM Cursor_Name;
●​ NEXT: This method allows the system to access the data in the forward direction from the cursor
table. It is the default option.
Syntax: FETCH NEXT FROM Cursor_Name;

●​ PRIOR: This method allows the system to access the data in the backward direction from the cursor
table.
Syntax: FETCH PRIOR FROM Cursor_Name;

●​ ABSOLUTE n: This method allows the system to access the data of the exact nth row from the cursor
table.
Syntax: FETCH ABSOLUTE n FROM Cursor_Name;

●​ RELATIVE n: This method allows the system to access the data in both incremental and decremental
processes.
Syntax: FETCH RELATIVE n FROM Cursor_Name;

B
4. Close Cursor:

HU
It is the fourth stage in the process of the cursor. When we complete the work with the cursor, we have to
close the cursor in this stage.
Syntax: CLOSE Cursor_Name;

5. Deallocate Cursor:

It is the last and fifth stage of the cursor life cycle. In this part, we have to erase the definition of the cursor

ER
and discharge all the system resources combined with the cursor.

Subqueries
RE
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.
CA

●​ You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like
=, <, >, >=, <=, IN, BETWEEN, etc.
●​ 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.
●​ Subqueries are on the right side of the comparison operator.
●​ A subquery is enclosed in parentheses.
●​ In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to
H

perform the same function as ORDER BY command.


UT

Subqueries with the Select Statement


Syntax:

SELECT column_name
YO

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

Subqueries with the Insert Statement


Syntax:

INSERT INTO table_name (column1, column2, column3....)


SELECT *
FROM table_name
WHERE VALUE OPERATOR
Subqueries with the Update Statement
Syntax:

UPDATE table
SET column_name = new_value
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME
FROM TABLE_NAME
WHERE condition);

Subqueries with the Delete Statement


Syntax:

DELETE FROM TABLE_NAME

B
WHERE VALUE OPERATOR
(SELECT COLUMN_NAME

HU
FROM TABLE_NAME
WHERE condition);

Stored Procedure in SQL Server


A stored procedure is a group of one or more pre-compiled SQL statements into a logical unit. It is stored as
an object inside the database server. It is a subroutine or a subprogram in the common computing language

ER
that has been created and stored in the database. Each procedure in SQL Server always contains a name,
parameter lists, and Transact-SQL statements. The SQL Database Server stores the stored procedures as
named objects. We can invoke the procedures by using triggers, other procedures, and applications built
using languages such as Java, Python, PHP, etc. It can support almost all relational database systems.
RE
Features of Stored Procedures in SQL Server —

●​ Reduced Traffic: A stored procedure reduces network traffic between the application and the
database server, resulting in increased performance. It is because instead of sending several SQL
statements, the application only needs to send the name of the stored procedure and its parameters.
CA

●​ Stronger Security: The procedure is always secure because it manages which processes and
activities we can perform. It removes the need for permissions to be granted at the database object
level and simplifies the security layers.

●​ Reusable: Stored procedures are reusable. It reduces code inconsistency, prevents unnecessary
rewrites of the same code, and makes the code transparent to all applications or users.
H

●​ Easy Maintenance: The procedures are easier to maintain without restarting or deploying the
application.
UT

●​ Improved Performance: Stored Procedure increases the application performance. Once we create
the stored procedures and compile them the first time, it creates an execution plan reused for
subsequent executions. The procedure is usually processed quicker because the query processor does
YO

not have to create a new plan.

User-defined Stored Procedures


Database developers or database administrators build user-defined stored procedures. These procedures
provide one or more SQL statements for selecting, updating, or removing data from database tables. A stored
procedure specified by the user accepts input parameters and returns output parameters. DDL and DML
commands are used together in a user-defined procedure.
We can further divide this procedure into two types —

T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular types of SQL Server
procedures. It takes parameters and returns them. These procedures handle INSERT, UPDATE, and DELETE
statements with or without parameters and output row data.
CLR Stored Procedures: The SQL Server procedures are a group of SQL commands, and the CLR indicates
the common language runtime. CLR stored procedures are made up of the CLR and a stored procedure, which
is written in a CLR-based language like VB.NET or C#. CLR procedures are .Net objects that run in the SQL
Server database's memory.

System Stored Procedures


The server's administrative tasks depend primarily on system stored procedures. When SQL Server is
installed, it creates system procedures. The system stored procedures prevent the administrator from
querying or modifying the system and database catalog tables directly. Developers often ignore system stored
procedures.

SQL Server Stored Procedures Syntax


The following are the basic syntax to create stored procedures in SQL Server:

B
CREATE PROCEDURE [schema_name].procedure_name

HU
@parameter_name data_type,
....
parameter_name data_type
AS
BEGIN
-- SQL statements
-- SELECT, INSERT, UPDATE, or DELETE statement
END

Parameters in Stored Procedures ER


Schema_name: It is the name of your database or schema. By default, a procedure is associated with the
current database, but we can also create it into another database by specifying the DB name.
RE
Procedure_Name: It represents the name of your stored procedure that should be meaningful names so
that you can identify them quickly. It cannot be the system reserved keywords.
CA

Parameter_Name: It represents the number of parameters. It may be zero or more based upon the user
requirements. We must ensure that we use the appropriate data type. For example, @Name VARCHAR(50).

SET NOCOUNT ON in Stored Procedure: In some cases, we use the SET NOCOUNT ON statement in the
stored procedure. This statement prevents the message that displays the number of rows affected by SQL
queries from being shown. NOCOUNT denotes that the count is turned off. It means that if SET NOCOUNT ON
is set, no message would appear indicating the number of rows affected.
H

Executing a Stored Procedure


UT

We can use the EXEC command to call/execute stored procedures in SQL Server. The following syntax
illustrates the execution of a stored procedure:

EXEC procedure_name;
Or,
YO

EXECUTE procedure_name;

If we are using the SSMS, we need to use the below steps to execute stored procedures:

●​ Navigate to the Programmability -> Stored Procedures.


●​ Next, select the Stored Procedure menu and expand it. You will see the available stored procedures.
●​ Right-click on the stored procedure you want to execute and choose the Execute Stored Procedure
●​ The Execute Procedure window will appear. If the procedure has any parameters, we must assign/pass
them before clicking OK to execute it. If no parameters are defined, click OK to run the procedure.

You might also like