0% found this document useful (0 votes)
33 views47 pages

DBMS Unit - 2

The document discusses relational database concepts including the relational model, domains, constraints, keys, and SQL. It defines relations, tuples, attributes, and describes primary keys, foreign keys, unique constraints, and default constraints. It also provides SQL examples to illustrate domain and key constraints.

Uploaded by

Visitcommercial
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)
33 views47 pages

DBMS Unit - 2

The document discusses relational database concepts including the relational model, domains, constraints, keys, and SQL. It defines relations, tuples, attributes, and describes primary keys, foreign keys, unique constraints, and default constraints. It also provides SQL examples to illustrate domain and key constraints.

Uploaded by

Visitcommercial
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/ 47

DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

UNIT 2

Relational data Model and Language: Relational Data Model Concepts, Integrity Constraints,
Entity Integrity, Referential Integrity, Keys Constraints, Domain Constraints, Relational Algebra,
Relational Calculus, Tuple and Domain Calculus. Introduction to SQL: Characteristics of SQL,
Advantage of SQL. SQL Data Type and Literals. Types of SQL Commands. SQL Operators and their
Procedure. Tables, Views and Indexes. Queries and Sub Queries. Aggregate Functions. Insert, Update
and Delete Operations, Joins, Unions, Intersection, Minus, Cursors, Triggers, Procedures in
SQL/PL SQL

Introduction
Relational Model was proposed by E.F Codd to model data in the form of relations or tables. After
designing the conceptual model of database using ER diagram, we need to convert the conceptual
model in the relational model which can be implemented using any RDBMS (Relational Data Base
Management System) like SQL, MY SQL etc.

The relational model is very simple and elegant; a database is a collection of one or more relations,
where each relation is a table with rows and columns.
This simple tabular representation enables even new users to understand the contents of a
database, and it permits the use of simple, high-level languages to query the data.

2.1 Relational Model


Relational Model represents how date is stored in relational databases.
A Relational database stores data in the form of relations (tables).
Consider a relation STUDENT with attributes ROLL_NO, NAME, ADDRESS, PHONE and AGE as
shown in table.
ROLL_NO NAME ADDRESS PHONE AGE
1 Nishma Hyderabad 9455123451 28
2 Sai Guntur 9652431843 27
3 Swetha Nellore 9156253131 26
Attribute: Attributes are the properties that define a relation.
Ex: ROLL_NO, NAME
Tuple: Each row in a relation is known as tuple.
Ex:
1 Nishma Hyderabad 9455123451 28
Degree: The number of attributes in the relation is known as degree.
Ex: The degree of the given STUDENT table is 5.
Column: Column represent the set of values for a particular attribute.
The column ROLL_NO is extracted from the relation STUDENT.
Ex:

ROLL_NO
1
Null values: The value which is not known or unavailable is called NULL VALUE. It is represented
by blank space.
Cardinality: The number of tuples are present in the relation is called as its cardinality.
Ex: The Cardinality of the STUDENT table is 3.
2
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

2.2 Concept Of Domain


The domain of a database is the set of all allowable values (or) attributes of the database.
Ex: Gender (Male, Female, Others).

Relation
➢ A relation is defined as a set of tuples and attributes.
➢ A relation consists of Relation schema and relation instance.
➢ Relation schema: A relation schema represents the name of the relation with its attributes.
Ex: STUDENT (ROLL_NO, NAME, ADDRESS, PHONE and AGE) is Relation schema for
STUDENT.
➢ Relation instance: The set of tuples of a relation at a particular instance of a time is called
Relation Instance.
An instance of „Employee „relation

Emp_code Emp_Name Dept_Name


01234 John HR
12567 Smith Sales
21678 Sai Production
12456 Jay Design

2.3 Importance of Null values:


➢ SQL supports a special value known as NULL which is used to represent the values of
attributes that may be unknown or not apply to a tuple.
➢ For example, the apartment_number attribute of an address applies only to the address that
is in apartment buildings and not to other types of residences.
➢ It is important to understand that a NULL value is different from Zero value.
➢ A Null value is used to represent a missing value, but that is usually has one of the following
interpretations:
• Value unknown (Value exists but it is unknown)
• Value not available (exists but it is purposely withheld)
• Attribute not applicable (undefined for this tuple)
➢ It is often not possible to determine which of the meanings is intended.

2.4 Constraints
➢ On modeling the design of the relational data base, we can put some rules(conditions) like
what values are allowed to be inserted in the relation
➢ Constraints are the rules enforced on the data columns of a table. These are used to limit the
type of data that can go in to a table
➢ This Ensure the accuracy and reliability of the data in the database. Constraints could be
either on a column level on a table level.

3
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

2.5 Domain Constraints In DBMS


➢ In DBMS table is viewed as a combination of rows and columns
➢ For example, if you are having a column called month and you want only (jan, feb,
march……) as values allowed to be entered for that particular column which is referred to as
domain for that particular column
Definition: Domain constraint ensures two things it makes sure that the data value entered for that
particular column matches with the data type defined by that column
It shows that the constraints (NOT NULL/UNIQUE/PRIMARY KEY/FOREIGN
KEY/CHECK/DEFAULT)

Domain constraint= data type check for the column +constraints.


Example:, we want to create a table “STUDENT” with “stu_id” field having a value greater
than 100, can create a domain and table like this.

▪ Create domain id_value int constraint id_test check (value>=100);


▪ CREATE table STUDENT (stu_id id value primary key, stu_name varchar
(30), stu_age int);

2.6 Key constraints in DBMS:


➢ Constraints are nothing but the rules that are to be followed while entering data into columns of the
database table.
➢ Constraints ensure that the data entered by the user into columns must be within the criteria specified by
the condition.
➢ We have 6 types of key constraints in DBMS
1. Not Null
2. Unique
3. Default
4. Check
5. Primary key
6. Foreign key

1. Not Null:
• Null represents a record where data may be missing data or data for that record may be optional.
• Once not null is applied to a particular column, you cannot enter null values to that column.
• A not null constraint cannot be applied at table level.

4
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Example:

Create table EMPLOYEE (id int Not null, name varchar Not null, Age int
not null, address char (25), salary decimal (18,2), primary key(id));

➢ In the above example we have applied not null on three columns id, name and age which
means whenever a record is entered using insert statement all three columns should contain a
value other than null.
➢ We have two other columns address and salary, where not null is not applied which means
that you can leave the row as empty.

2. Unique:

Some times we need to maintain only. Unique data in the column of a database table, this is
possible by using a Unique constraint.

➢ Unique constraint ensures that all values in a column are Unique.

Example:

Create table PERSONS (id int unique, last_name varchar (25) not null,
First name varchar (25), age int);

➢ In the above example, as we have used unique constraint on ID column we are not supposed
to enter the data that is already present, simply no two ID values are same.

5
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

3. Default:

Default in SQL is used to add default data to the columns.

➢ When a column is specified as default with same value then all the rows will use the same
value i.e., each and every time while entering the data we need not enter that value.
➢ But default column value can be customised i.e., it can be over ridden when inserting a data
for that row based on the requirement.

(Row with default values “abc”)

Example:

Create table EMPLOYEE (id int Not null, last_name varchar (25) Not null,
first_name varchar (25), Age int, city varchar (25) Default Hyderabad);

➢ As a result, whenever you insert a new row each time you need not enter a value for this
default column that is entering a column value for a default column is optional.

4. Check:
➢ Check constraint ensures that the data entered by the user for that column is within the range
of values or possible values specified.

Example: Create table STUDENT (id int, name varchar (25), age int,
check(age>=18));

➢ As we have used a check constraint as (age>=18) which means value entered by user for this
age column while inserting the data must be less than or equal to 18.

6
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

5. Primary Key:
➢ A primary key is a constraint in a table which uniquely identifies each row record in a
database table by enabling one or more column in the table as primary key.

Creating a primary key:

➢ A particular column is made as a primary key column by using the primary key keyword
followed by the column name.
Example:
Create table EMP (ID int, name varchar (20), age int, course varchar
(10), Primary key (ID));
➢ Here we have used the primary key on ID column then ID column must contain unique
values i.e., one ID cannot be used for another student.

6. Foreign Key:
➢ The foreign key constraint is a column or list of columns which points to the primary key
column of another table.
➢ The main purpose of the foreign key is only those values are allowed in the present table that
will match to the primary key column of another table.

From the above two tables, COURSE_ID is a primary key of the table STUDENT_MARKS and also
behaves as a foreign key as it is same in STUDENT_DETAILS and STUDENT_MARKS.

7
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Example:

(Reference Table)

Create table CUSTOMER1 (id int, name varchar (25), course varchar (10),
primary key (ID));

(Child table)

Create table CUSTOMER2 (id int, marks int, references customer1(ID));

2.7 Integrity Constraints in DBMS:


➢ There are two types of integrity constraints
1. Entity Integrity Constraints
2. Referential Integrity Constraints

Entity Integrity constraints:

➢ These constraints are used to ensure the uniqueness of each record or row in the data
table.
➢ Entity Integrity constraints says that no primary key can take NULL VALUE, since
using primary key we identify each tuple uniquely in a relation.

Example:

Explanation:

➢ In the above relation, EID is made primary key, and the primary key can‟t
take NULL values but in the 3rd tuple, the primary key is NULL, so it is
violating Entity integrity constraints.

Referential Integrity constraints:

➢ The referential integrity constraint is specified between two relations or tables and used
to maintain the consistency among the tuples in two relations.
➢ This constraint is enforced through foreign key, when an attribute in the foreign key of
relation R1 have the same domain as primary key of relation R2, then the foreign key of
R1 is said to reference or refer to the primary key of relation R2.
➢ The values of the foreign key in a tuple of relation R1 can either take the values of the
primary key for some tuple in Relation R2, or can take NULL values, but can‟t be empty.

8
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Explanation:

➢ In the above, DNO of the first relation is the foreign key and DNO in the second relation is the
primary key
➢ DNO=22 in the foreign key of the first relation is not available in the second relation so, since
DNO=22 is not defined in the primary key of the second relation therefore Referential
integrity constraints is violated here.

Relational Algebra is a procedural query language. Relational algebra mainly provides a theoretical
foundation for relational databases and SQL. The main purpose of using Relational Algebra is to define
operators that transform one or more input relations into an output relation. Given that these operators
accept relations as input and produce relations as output, they can be combined and used to express
potentially complex queries that transform potentially many input relations (whose data are stored in the
database) into a single output relation (the query results). As it is pure mathematics, there is no use of
English Keywords in Relational Algebra and operators are represented using symbols.

Fundamental Operators
These are the basic/fundamental operators used in Relational Algebra.
1. Selection(σ)
2. Projection(π)
3. Union(U)
4. Set Difference(-)
5. Set Intersection(∩)
6. Rename(ρ)
7. Cartesian Product(X)

1. Selection(σ): It is used to select required tuples of the relations.


Example:
A B C
1 2 4
2 2 3
3 2 3
4 3 4
9
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
For the above relation, σ(c>3)R will select the tuples which have c more than 3.
A B C
1 2 4
4 3 4
Note: The selection operator only selects the required tuples but does not display them. For display, the
data projection operator is used.

2. Projection(π): It is used to project required column data from a relation.


Example: Consider Table 1. Suppose we want columns B and C from Relation R.
π(B,C)R will show following columns.
B C
2 4
2 3
3 4
Note: By Default, projection removes duplicate data.

3. Union(U): Union operation in relational algebra is the same as union operation in set theory.
Example:
FRENCH
Student_Name Roll_Number
Ram 01
Mohan 02
Vivek 13
Geeta 17

GERMAN
Student_Name Roll_Number
Vivek 13
Geeta 17
Shyam 21
Rohan 25
Consider the following table of Students having different optional subjects in their course.
π(Student_Name)FRENCH U π(Student_Name)GERMAN
Student_Name
Ram
Mohan
Vivek
Geeta
Shyam
Rohan
Note: The only constraint in the union of two relations is that both relations must have the same set of
Attributes.

4. Set Difference(-): Set Difference in relational algebra is the same set difference operation as in set
theory.
Example: From the above table of FRENCH and GERMAN, Set Difference is used as follows
π(Student_Name)FRENCH - π(Student_Name)GERMAN

10
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Student_Name
Ram
Mohan
Note: The only constraint in the Set Difference between two relations is that both relations must have
the same set of Attributes.

5. Set Intersection(∩): Set Intersection in relational algebra is the same set intersection operation in set
theory.
Example: From the above table of FRENCH and GERMAN, the Set Intersection is used as follows
π(Student_Name)FRENCH ∩ π(Student_Name)GERMAN
Student_Name
Vivek
Geeta
Note: The only constraint in the Set Difference between two relations is that both relations must have
the same set of Attributes.

6. Rename(ρ): Rename is a unary operation used for renaming attributes of a relation.


ρ(a/b)R will rename the attribute 'b' of the relation by 'a'.

7. Cross Product(X): Cross-product between two relations. Let’s say A and B, so the cross product
between A X B will result in all the attributes of A followed by each attribute of B. Each record of A
will pair with every record of B.
Example:
A
Name Age Sex
Ram 14 M
Sona 15 F
Kim 20 M
B
ID Course
1 DS
2 DBMS
AXB
Name Age Sex ID Course
Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS
Note: If A has ‘n’ tuples and B has ‘m’ tuples then A X B will have ‘ n*m ‘ tuples.

11
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Relational calculus in RDBM is referring to the non-procedural query language that emphasizes on the
concept of what to for the data management rather how to do those. The relational calculus provides
descriptive information about the queries to achieve the required result by using mathematical predicates
calculus notations. It is an integral part of the relational data model. The relational calculus in DBMS uses
specific terms such as tuple and domain to describe the queries. Some of the other related common
terminologies for relational calculus are variables, constant, Comparison operators, logical connectives, and
quantifiers. It creates the expressions that are also known as formulas with unbound formal variables.
Types of Relational Calculus in DBMS
In this section, we will discuss the types of relational calculus in DBMS based on the terms and process of the
mathematical description of queries functionalities. Tuple and domain are the major components of
relational calculus. A result tuple is an assignment of constants to these
Variables that make the formula evaluate to be true. There are two types of relational calculus available in
DBMS
• Tuple relational calculus (TRC)
• Domain relational calculus (DRC)
Both the types of relational calculus are semantically similar for operating in DBMS data retrieval definitions.
We will discuss each type of relational calculus with some database table examples to represent the syntax
and its uses.
TRC
Tuple relational calculus works on filtering the tuples based on the specified conditions.TRC is the variable
range over the tuples and is a type of simple subset of the first-order logic.TRC considers tuples as equal
status as variables, and field referencing can be used to select the tuple parts. It is represented using letter ‘T’
and conditions with the pipe symbol and enclosing curly braces.
Syntax of TRC:
{T | Conditions)
The TRC syntax supports to denote the Table names or relation names, defining the tuple variables, and the
column names. It uses the ‘.’ operator symbol to specify the column names with the table name.
TRC specifies the relation names with the Tuple variable name such as ’T’. Syntax of Relation definition in
TRC:
Relation(T)
For example, if the Product is the relation name, it can be denoted as Product(T). Similarly, TRC has the
provision to specify the conditions. The condition is applicable for a particular attribute or the column.
For instance, if the data need to be represented for the particular product id of value 10, it can be denoted as
T.product_id=10, where T is the tuple variable that represents the row of the table.
Let us assume the Product table in the database as follows:

Product_id Product Category Product Name Product Unit Price

8 New TV Unit 1 $100

10 New TV Unit 2 $120

12
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
12 Existing TV Cabinet $77

Now to represent the relational calculus to return the product name that has the product id value as 10 from
the product table, it can be denoted as with the tuple variable T.
T.Product Name | Product(T) AND T.Product_id = 10
This relational calculus predicate describes what to do for getting the resultant tuple from the database. The
result of the tuple relational calculus for the Product table will be:

Product_id Product Name

10 TV Unit 2

DRC
The domain regional calculus works based on the filtering of the domain and the related attributes.DRC is the
variable range over the domain elements or the filed values. It is a type of simple subset of first-order logic. It
is domain-dependent compared to TRC is tuple dependent. In DRC the formal variables are explicit for the
relational calculus representations. The domain attributes in DRC can be represented as C1, C2,…, Cn and the
condition related to the attributes can be denoted as the formula defining the condition for fetching the F(C1,
C2, …Cn )
Syntax of DRC in DBMS
{c1, c2,...,cn| F(c1, c2,... ,cn)}
Let us assume the same Product table in the database as follows:

Product_id Product Category Product Name Product Unit Price

8 New TV Unit 1 $100

10 New TV Unit 2 $120

DRC for the product name attribute from the Product table needs where the product id is 10, It will be
demoted as:
{< Product Name, Product_id> | ∈ Product ∧ Product_id> 10}
The result of the domain relational calculus for the Product table will be

Product_id Product Name

10 TV Unit 2

Some of the commonly used logical operator notations for DRC are ∧ for AND,∨ for OR, and ┓ for NOT.
Similarly, the mathematical symbol ∈ refers to the relation “is an element of” or known as the set
membership.

13
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Difference between Relational Algebra and Relational Calculus:

S.NO Basis of Relational Algebra Relational Calculus


Comparison
1. Language Type It is a Procedural language. Relational Calculus is a Declarative
(non-procedural) language.
2. Procedure Relational Algebra means how Relational Calculus means what
to obtain the result. result we have to obtain.
3. Order In Relational Algebra, the In Relational Calculus, the order is
order is specified in which the not specified.
operations have to be
performed.
4. Domain Relational Algebra is Relation Calculus can be domain-
independent of the domain. dependent because of domain
relational calculus.
5. Programming Relational Algebra is nearer to Relational Calculus is not nearer to
language a programming language. programming language but to
natural language.
6. Inclusion in SQL The SQL includes only some SQL is based to a greater extent on
features from the relational the tuple relational calculus.
algebra.
7. Relationally Relational Algebra is one of For a database language to be
completeness the languages in which relationally complete, the query
queries can be expressed but written in it must be expressible in
the queries should also be relational calculus.
expressed in relational
calculus to be relationally
complete.
8. Query The evaluation of the query The order of operations does not
Evaluation relies on the order matter in relational calculus for the
specification in which the evaluation of queries.
operations must be
performed.
9. Database access For accessing the database, For accessing the database,
relational algebra provides a relational calculus provides a
solution in terms of what is solution in terms as simple as what
required and how to get that is required and lets the system find
information by following a the solution for that.
step-by-step description.
10. Expressiveness The expressiveness of any The completeness of a language is
given language is judged using measured in the manner that it is
relational algebra operations least as powerful as calculus. That
as a standard. implies relation defined using some
expression of the calculus is also
definable by some other expression,
the language is in question.
14
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Basic SQL (introduction)

➢ SQL stands for Structure Query Language it is used for storing and managing data in
relational database management system.
➢ It is standard language for relational database system. It enables a user to create, read, update
and delete relational databases and tables.
➢ All the RDBMS like MYSQL, Oracle, MA access and SQL Server use SQL as their standard
database language.
➢ SQL allows users to Query the database in a number of ways using statements like common
English.
Rules: SQL follows following rules

• SQL is not a case sensitive. Generally, keywords are represented in


UPPERCASE.
• Using the SQL statements, you can perform most of the actions in a database.
• Statements of SQL are dependent on text lines. We can use a single SQL
statement on one or multiple text line.

2.8 SQL Process:


➢ When an SQL command is executing for any RDBMS, then the system figure out the best
way to carry out the request and the sql engine determines that how to interrupt the task.
➢ In the process, various components are included. These components can be optimization
engine, query engine, query dispatcher etc.,
➢ All the non-sql queries are handled by the classic query engine, but sql query engine won‟t
handle logical files.

2.9 Characteristics of SQL:


• SQL is easy to learn.
• SQL is used to access data from relational database management system.
• SQL is used to describe the data.
• SQL is used to create and drop the database and table.
• SQL allows users to set permissions on tables, procedures and views.

2.10 Simple database Schema:


➢ A database schema is a structure that represents the logical storage of the data in the
database.
➢ It represents the organization of data and provides information about the relationships
between the tables in a given database.
➢ A database schema is the logical representation of a database, which shows how the data is
stored logically in the entire database.
➢ It contains list of attributes and instruction that informs the database engine that how the
data is organized and how the elements are related to each other.
➢ A database schema contains schema objects that may include tables, fields, packages, views,
relationship, primary key, foreign key.
➢ In actual, the data is physically stored in files that may be in unstructured form, but to
retrieve it and use it, we need to keep them in a structured manner. To do this a database
schema is used. It provides knowledge about how the data is organized in a database and
how it is associated with other data.
➢ A database schema object includes the following:
• Consistent formatting for all data entries.
• Database objects and unique keys for all data entries.

15
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
• Tables with multiple columns, and each column contains its names and datatypes.
• The given diagram is an example of a database schema it contains three tables, their
data types. This also represents the relationships between the tables and primary keys
as well as foreign keys.

SQL Commands:
SQL commands are categorized into three types.

1. Data Definition Language (DDL): used to create (define) a table.

2. Data Manipulation Language (DML): used to update, store and retrieve data from tables.

3. Data Control Language (DCL): used to control the access of database created using DDL and
DML.

2.11 SQL DATATYPES :


SQL data type is used to define the values that a column can contain

Every column is required to have a name and data type in the database table.

DATA TYPES OF SQL :

16
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

SQL DATA
TYPES

Binary Numeric Extract numeric String datatype Date data type


datatype datatype datatype

1. BINARY DATATYPES:
There are three types of binary data types which are given below
DATA TYPE DESCRIPTION

Binary It has a maximum length of 800 bytes. It contains a fixed-


length binary data
Var binary It has a maximum length of 800 bytes. It contains a
variable - length binary data
Image It has a maximum length of 2,147,483,647 bytes. It contains
a variable - length binary data

2. NUMERIC DATATYPE:
DATA TYPE FROM TO DESCRIPTION

Float -1.79 E 1.79 E It is used to specify a floating-point value.


+308 +308 Ex: 6.2, 2.9 etc
Real -3.40 E 3.40 E It specifies a single precision floating
+38 +38 point number.
3. EXACT NUMERIC DATA TYPE:
DATA TYPE DESCCRIPTION

Int It is used to specify an integer value


Small int It is used to specify small integer value
Bit It has the number of bits to store
Decimal It specifies a numeric value that can have a decimal number
Numeric It is used to specify a numeric value
4. DATE AND TIME DATATYPES:
DATA TYPE DESCRIPTION
Date It is used to store the year, month, and days value
Time It is used to store the hour, minute, and seconds value
Time stamp It stores the year, month, hour, minute, and the second value

5. STRING DATATYPE:
DATA TYPE DESCRIPTION

17
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Char It has a maximum length of 8000 characters. It contains fixed-length non-
Unicode characters.
Varchar It has a maximum length of 8000 characters. It contains variable-length
non-Unicode characters.
Text It has a maximum length of 2,147,483,647 characters. It contains variable-
length non-Unicode characters.

2.12 TABLE DEFINITIONS: (CREATE, ALTER)


SQL TABLE: SQL table is a collection of data which is organized in terms of rows and columns.

• In DBMS, the table is known as relation and row as a tuple


• Let‟s see an example of the “EMPLOYEE “table
EMP_ID EMP_NAME CITY PHONE_ID
1 Kristen Washington 7289201223
2 Anna Franklin 9378282882
3 Jackson California 9264783838
4 Daniel Hawaii 9638482678
• In the above table, “EMPLOYEE” is the table name, “EMP_ID, “EMP_NAME”, “CITY”,”
PHONE-NO” are the column names.
• The combination of data of multiple columns forms a row
EG: 1, “Kristen”, “Washington” and “7289201223 “are the data of one row

2.13 OPERATIONS ON TABLE:


1. Create table
2. Alter table
3. Drop table

1. Create table: SQL create table is used to create a table in the database. To define the table, you
should define the name of the table and also define its column and column‟s data type.
SYNTAX:

Create table table_name (“column1” “datatype”,

“column2” “datatype”,
….

“column N” “datatype”);

EXAMPLE:
SQL > create table employee (emp_id int, emp_name varchar (25), phone_no int,
address char (30));

• If you create the table successfully, you can verify the table by looking at the message by the
sql server. else you can use DESC command as follows

SQL > DESC employee;

FIELD TYPE NULL DEFAULT EXTRA


Emp_id Int (11) No NULL
Emp_name Varchar (25) No NULL
Phone_no No Int (11) NULL
address yes NULL Char(30)

18
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

2. ALTER TABLE:

• The alter table command adds, delete or modifies columns in a table


• The alter table command also adds and deletes various constraints in a table
• The following SQL adds an “EMAIL” column to the “EMPLOYEE “table

SYNTAX:

ALTER table table_name add column1 datatype;

EXAMPLE:

ALTER table employee add email varchar (255);

SQL > DESC employee;

FIELD TYPE NULL DEFAULT EXTRA


Emp_id Int (11) No NULL
Emp_name Varchar (25) No NULL
Phone_no No Int (11) NULL
Address Yes NULL Char (30)
Email Varchar (255) NULL

3. DROP TABLE:

• The drop table command deletes a table in the data base


• The following example SQL deletes the table “EMPLOYEE”

SYNTAX :

DROP table table_name;

EXAMPLE:

DROP table employee;

• Dropping a table results in loss of all information stored in the table.

2.14 Different DML Operations (insert, delete, update):


➢ DML-Data Manipulation Language.
➢ Data Manipulation Commands are used to manipulate data to the database.
➢ Some of the data manipulation commands are
1. Insert
2. Update
3. Delete

1. Insert:
SQL insert statement is a sql query. It is used to insert a single multiple records in a table.

Syntax:

19
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Insert into table name values (value 1, value 2, value 3);

Let‟s take an example of table which has 3 records within it.

▪ insert into student values(„alekhya‟,501,‟hyderabad‟);

▪ insert into student values(„deepti‟,502,‟guntur‟);

▪ insert into student values(„ramya‟,503,‟nellore‟);

The following table will be as follows:

NAME ID CITY
Alekhya 501 Hyderabad
Deepti 502 Guntur
Ramya 503 Nellore

2. Update:
➢ The SQL Commands update are used to modify the data that is already in the database.
➢ SQL Update statement is used to change the data of records held by tables which rows is to
be update, it is decided by condition to specify condition, we use “WHERE” clause.
➢ The update statement can be written in following form:

Syntax:
Update table_name set column_name=expression where condition;

Example:

Let‟s take an example: here we are going to update an entry in the table.

Update students set name=‟rasi‟ where id=503;

After update the table is as follows:

NAME ID CITY
Alekhya 501 Hyderabad
Deepti 502 Guntur
Rasi 503 Nellore

3. Delete:
➢ The SQL delete statement is used to delete rows from a table.
➢ Generally, delete statement removes one or more records from a table.

Syntax:

delete from table_name [where condition];

Example:

Let us take a table named “student” table

20
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Delete from students where id=501;

Resulting table after the query:

NAME ID CITY
Deepti 502 Guntur
Rasi 503 Nellore

2.15 Basic SQL querying (select and project) using where clause:
➢ The following are the various SQL clauses:

SQL Clause

Group by clause having clause Order by clause

1. Group by:
➢ SQL group by statement is used to arrange identical data into groups.
➢ The group by statement is used with the SQL select statement.
➢ The group by statement follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.

Syntax:
Select column from table_name where column group by column, order by
column;

Sample table: product


PRODUCT COMPANY QTY RATE COST
Item 1 Com 1 2 10 20
Item 2 Com 2 3 25 75
Item 3 Com 1 2 30 60
Item 4 Com 3 5 10 50
Item 5 Com 2 2 20 40

Example:
➢ Select company count (*) from product group by company;

21
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Output:
Com 1 2
Com 2 3
Com 3 5

2. Having clause:
➢ Having clause is used to specify a search condition for a group or an aggregate.

Having clause is used in a group by clause, if you are not using group by clause then you can
use having function like a where clause.

Syntax:
Select column1, column2 from table_name

Where conditions

Group by column1, column2

Having conditions

Order by column1, column2;

Example:
➢ select company count (*) from product

Group by company

Having count (*) > 2;

Output:
Com 3 5
Com 2 2

3. Order by clause:
The order by clause sorts the result _set in ascending or descending order.

Syntax:

Select column1, column2, from table_name

Where condition

Order by column1, column2…asc;

Sample table:

Take a student table

22
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Example:

Select * from student order by name;

Output:

NAME ID CITY
Alekhya 501 Hyderabad
Deepti 502 Guntur
Rasi 503 Nellore

2.16 SQL Where clause:


➢ A where clause in SQL is a data manipulation language statement.
➢ Where clauses are not mandatory clauses of SQL DML statements but it can be used to limit
the number of rows affected by a SQL DML statement or returned by query.
➢ Actually, it follows the records.it returns only those queries which the specific conditions.

Syntax:
Select column1, column2, …………column from table_name where[condition];

➢ Where clause uses same conditional selection.

= Equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
<> Not equal to

2.17 Arithmetic and logical operations:

SQL operators:
➢ SQL statements generally contain some reserved words or characters that are used to
perform operations such as arithmetic and logical operations etc. Their reserved words are
known as operators.

SQL arithmetic operator:


➢ We can use various arithmetic operators on the data stored in tables.
➢ Arithmetic operators are:

+ Addition
- Subtraction
/ Division
* Multiplication

23
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

% modulus

1. Addition (+):
It is used to perform addition operation on data items.

Sample table:
EMP_ID EMP_NAME SALARY

1 Alex 25000
2 John 55000
3 Daniel 52000
4 Sam 12312

➢ select emp id, emp_name, salary, salary+100 as “salary +100” from


addition;

Output:
EMP_ID EMP_NAME SALARY SALARY+100
1 Alex 25000 25100
2 John 55000 55100
3 Daniel 52000 52100
4 Sam 12312 12412
➢ Here we have done addition of 100 to each emp‟s salary.

2. Subtraction (-):
➢ It is used to perform subtraction on the data items.

Example:
Select emp_id, emp_name, salary, salary-100 as “salary-100” from
subtraction;
EMP_ID EMP_NAME SALARY SALARY-100
1 Alex 25000 24900
2 John 55000 54900
3 Daniel 52000 51900
4 Sam 90000 89900
Here we have done subtraction of 100 for each emp‟s salary.

3. Division (/):
➢ The division function is used to integer division (x is divided by y).an integer value is
returned.

Example:
➢ Select emp_id, emp_name, salary, salary/100 as “salary/100” from
division;

EMP_ID EMP_NAME SALARY Salary/100


1 Alex 25000 250
2 John 55000 550
3 Daniel 52000 520
4 Sam 90000 900

24
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

4. Multiplication (*):
➢ It is used to perform multiplication of data items.
➢ Select emp_id, emp_name, salary, salary*100 as “salary*100” from
multiplication;

EMP_ID EMP_NAME SALARY SALARY*100


1 Alex 25000 2,500,000
2 John 55000 5,500,000
3 Daniel 52000 5,200,000
4 Sam 90000 9,000,000
➢ Here we have done multiplication of 100 to each emp‟s salary.

5. Modulus (%):
➢ It is used to get remainder when one data is divided by another.
➢ Select emp_id, emp_name, salary, salary%25000 as “salary%25000” from
modulus;

Output:
EMP_ID EMP_NAME SALARY SALARY%25000
1 Alex 25000 0
2 John 55000 5000
3 Daniel 52000 2000
4 Sam 90000 15000
➢ Here we have done modulus operation to each emp‟s salary.

2.18 Logical operations:


➢ Logical operations allow you to test for the truth of a condition.
➢ The following table illustrates the SQL logical operator.
OPERATOR MEANING
ALL Returns true if all comparisons are true
AND Returns true if both expressions are true
ANY Returns true if any one of the comparisons is
true
BETWEEN Return true if the operand is within a range
IN Return true if the operand is equal to one of
the values in a list
EXISTS Return true if the sub query contains any rows
1. AND:
The AND operator allows you to construct multiple condition in the WHERE clause of an SQL
statement such as select.

➢ The following example finds all employees where salaries are greater than the 5000 and less
than 7000.
➢ Select first_name, last_name, salary from employees where
salary>5000 AND salary<7000 order by salary;

Output:
FIRST_NAME LAST_NAME SALARY
John Wesley 6000
Eden Daniel 6000
Luis Popp 6900
Shanta Suji 6500

25
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

2. ALL:
The ALL operator compares a value to all values in another value set.

➢ The following example finds all employees whose salaries are greater than all salaries of
employees.
EX:
select first_name, last_name, salary from employees where salary>=ALL
(select salary from employees where department_id =8) order by salary
DESC;
Output:
FIRST_NAME LAST_NAME SALARY
Steven King 24000
John Russel 17000
Neena Kochhar 14000

3. ANY:
The ANY operator compares a value to any value in a set ascending to condition.
The following example statement finds all employees whose salaries are greater than the average
salary of every department.
EX:
select first_name, last_name, salary from employees where salary >ANY
(select avg (salary) from employees‟ group by department_id) order by
first_name, last_name;

Output:
FIRST_NAME LAST_NAME SALARY
Alexander Hunold 9000.00
Charles Johnson 6200.00
David Austin 4800.00
Eden Flip 9000.00

4. Between:
➢ The between operator searches for values that are within a set of values.
➢ For example, the following statement finds all employees where salaries are between 9000
and 12000.

EX:

select first_name, last_name, salary from employees where salary


between 9000 AND 12000 order by salary;

Output:
FIRST_NAME LAST_NAME SALARY
Alexander Hunold 9000.00
Den Richards 10000.00
Nancy Prince 12000.00

26
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

5. IN:
➢ The IN operator compares a value to list of specified values. The IN operator return true if
compared value matches at least one value in the list.
➢ The following statement finds all employees who work in department _id 8 or 9.

EX:

select first_name, last_name, department_id from employees where


department_id IN (8,9) order by department_id;

Output:
FIRST_NAME LAST_NAME DEPARTMENT_ID
John Russel 8
Jack Livingstone 8
Steven King 9
Neena Kochhar 9

6. Exists:
➢ The EXISTS operator tests if a sub query contains any rows.
➢ For example, the following statement finds all employees who have dependents.
➢ select first_name, last_name from employees where EXISTS (select 1
from dependent d where d.employee_id=e.employee_id);

FIRST_NAME LAST_NAME
Steven King
Neena Kochhar
Alexander Hunold

Tables: Tables are the basic structure used to store data in a relational database.
• They consist of rows and columns, where each row represents a record and each column
represents a specific attribute or field of the data.
• Tables are defined with a schema that specifies the name of the table, the names and data
types of its columns, and any constraints or rules that apply to the data.
• Example:
CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, FirstName VARCHAR(50),
LastName VARCHAR(50), Age INT, DepartmentID INT );
Views: Views are virtual tables that are defined by a SQL query.
• They do not store data themselves but rather provide a way to present data from one or more
tables in a specific way.
• Views can be used to simplify complex queries, provide a level of security by restricting
access to certain columns or rows, or to provide a customized view of the data to different
users or applications.
• Example:
CREATE VIEW EmployeeNames AS SELECT FirstName, LastName FROM Employees;
27
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Indexes: Indexes are data structures that improve the speed of data retrieval operations on a database table.
• They are created on one or more columns of a table and store a sorted copy of the data in
those columns, along with pointers to the actual rows in the table.
• Indexes speed up SELECT queries by allowing the database to quickly locate rows based on
the values in the indexed columns.
• However, they can also slow down data modification operations (such as INSERT, UPDATE,
and DELETE) because the indexes need to be updated whenever the data in the indexed
columns changes.
• Example:
CREATE INDEX idx_LastName ON Employees(LastName);

SQL joins are used to combine rows from two or more tables based on a related column between them.
They are fundamental in database query operations and allow for the retrieval of data from multiple tables
in a single result set. Here's an overview of the main types of SQL joins:
• INNER JOIN
• LEFT JOIN
• RIGHT JOIN
• FULL JOIN
• NATURAL JOIN
Consider the two tables below as follows:
Student

StudentCourse

28
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
The simplest Join is INNER JOIN.
A. INNER JOIN
The INNER JOIN keyword selects all rows from both the tables as long as the condition is satisfied. This
keyword will create the result-set by combining all rows from both the tables where the condition satisfies
i.e value of the common field will be the same.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also write JOIN instead of INNER JOIN. JOIN is same as INNER JOIN.

Example Queries(INNER JOIN)


This query will show the names and age of students enrolled in different courses.
SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE FROM Student
INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Output:

B. LEFT JOIN
This join returns all the rows of the table on the left side of the join and matches rows for the table on the
right side of the join. For the rows for which there is no matching row on the right side, the result-set will
contain null. LEFT JOIN is also known as LEFT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
LEFT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


29
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
table2: Second table
matching_column: Column common to both the tables.
Note: We can also use LEFT OUTER JOIN instead of LEFT JOIN, both are the same.

Example Queries(LEFT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
LEFT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

C. RIGHT JOIN
RIGHT JOIN is similar to LEFT JOIN. This join returns all the rows of the table on the right side of the join
and matching rows for the table on the left side of the join. For the rows for which there is no matching row
on the left side, the result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Note: We can also use RIGHT OUTER JOIN instead of RIGHT JOIN, both are the same.

30
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Example Queries(RIGHT JOIN):


SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:

D. FULL JOIN
FULL JOIN creates the result-set by combining results of both LEFT JOIN and RIGHT JOIN. The result-set
will contain all the rows from both tables. For the rows for which there is no matching, the result-set will
contain NULL values.

Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
FULL JOIN table2
ON table1.matching_column = table2.matching_column;

table1: First table.


table2: Second table
matching_column: Column common to both the tables.
Example Queries(FULL JOIN):
SELECT Student.NAME,StudentCourse.COURSE_ID
FROM Student
31
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
FULL JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Output:
NAME COURSE_ID
HARSH 1
PRATIK 2
RIYANKA 2
DEEP 3
SAPTARHI 1
DHANRAJ NULL
ROHIT NULL
NIRAJ NULL
NULL 4
NULL 5
NULL 4

E. Natural join (?)


Natural join can join tables based on the common columns in the tables being joined. A natural join returns
all rows by matching values in common columns having same name and data type of columns and that
column should be present in both tables.
Both table must have at least one common column with same column name and same data type.
The two table are joined using Cross join.
DBMS will look for a common column with same name and data type Tuples having exactly same values in
common columns are kept in result.
Example:
Employee
Emp_id Emp_name Dept_id
1 Ram 10
2 Jon 30
3 Bob 50
Department
Dept_id Dept_name
10 IT
30 HR
40 TIS
Query: Find all Employees and their respective departments.
Solution: SELECT * FROM employees NATURAL JOIN departments;
(Employee) ? (Department)
Emp_id Emp_name Dept_id Dept_id Dept_name
1 Ram 10 10 IT
2 Jon 30 30 HR
Employee data Department data

32
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Unions, intersections, and minus (or EXCEPT) are set operations used in SQL to combine or compare the
results of two or more queries. Here's a brief overview of each:
1. UNION:
• The UNION operator is used to combine the results of two or more SELECT statements into a
single result set.
• It removes duplicate rows from the combined result set.
• Syntax:

SELECT columns FROM table1 UNION SELECT columns FROM table2;

2. INTERSECT:
• The INTERSECT operator returns the common rows between two SELECT statements.
• It only includes rows that exist in both result sets.
• Syntax:

SELECT columns FROM table1 INTERSECT SELECT columns FROM table2;

3. MINUS (or EXCEPT):


• The MINUS operator (or EXCEPT in some databases) returns the rows that are unique to the
first SELECT statement but not in the second SELECT statement.
• It subtracts the rows returned by the second query from the first query.
• Syntax:
SELECT columns FROM table1 MINUS SELECT columns FROM table2;

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 us to access data of one row at a time. This concept of SQL is useful when
the user wants to update the rows of the table one by one.

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

In SQL database systems, users define the cursor using DECLARE statement and take the SELECT statement
as the parameter, which helps in returning the set of rows.

In this SQL article, we will learn about the types of a cursor, the life cycle of a cursor, syntax of a cursor, and
the implementation of a cursor.

Types of Cursor in SQL

Following are the two types of Cursor in Structured Query Language:

1. Implicit Cursor
2. Explicit Cursor

33
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Implicit Cursor

These types of cursors are generated and allocated by the SQL server when the system performs INSERT,
DELETE, and UPDATE operations on SQL queries.

This cursor is also referred to as the default cursor in SQL.

An implicit cursor is also created by the system when the SELECT query selects the single row.

Explicit Cursor

These types of cursors are created by the user using the SELECT query.

An explicit cursor holds multiple records but processes a single row at a time. It uses the pointer, which
moves to another row after reading one row.

It is basically used for gaining extra control over the temporary workstation.

Life Cycle of Cursor

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

Let's discuss each stage in brief:

1. Declare a Cursor

First, we have to declare the cursor by using the following SQL syntax:

1. DECLARE Cursor_Name CURSOR FOR Select_Statement;

In this syntax, we have to specify the name and data type of the cursor 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

It is the second stage that opens the cursor for storing the data retrieved from the result set. We can open the
cursor by using the following SQL syntax:

1. OPEN Cursor_Name;

34
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

3. Fetch Cursor

It is the third stage in the cursor life cycle that fetches the rows for performing the insertion, deletion, and
updation operations on the currently active tuple in the cursor.

Following are the six options that are used in syntax for fetching data from the cursor:

i. FIRST: This option allows the system to access only the first record from the cursor table. The syntax for
the FIRST option is given below:

FETCH FIRST FROM Cursor_Name;

ii. LAST: This option allows the system to access only the last record from the cursor table. The syntax for the
LAST option is as follows:

FETCH LAST FROM Cursor_Name;

iii. NEXT: This method allows the system to access the data in the forward direction from the cursor table. It
is the default option. The syntax of this method is as follows:

FETCH NEXT FROM Cursor_Name;

iv. PRIOR: This method allows the system to access the data in the backward direction from the cursor table.
The syntax of this option is as follows:

FETCH PRIOR FROM Cursor_Name;

v. ABSOLUTE n: This method allows the system to access the data of the exact nth row from the cursor table.
The syntax of this option is mentioned below:

FETCH ABSOLUTE n FROM Cursor_Name;

vi. RELATIVE n: This method allows the system to access the data in both incremental and decremental
processes. The syntax of this option is mentioned below:

FETCH RELATIVE n FROM Cursor_Name;

4. Close Cursor

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. We can close the cursor in SQL by using the following query:
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
and discharge all the system resources combined with the cursor.

DEALLOCATE My_Cursor_Name
35
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

DELIMITER //
CREATE PROCEDURE PrintEmployeeDetails()
BEGIN
-- Declare variables for cursor
DECLARE emp_id INT;
DECLARE emp_first_name VARCHAR(50);
DECLARE emp_department VARCHAR(50);

-- Declare a variable to handle the cursor


DECLARE no_more_rows BOOLEAN DEFAULT FALSE;

-- Declare a cursor for selecting data from Employees table


DECLARE emp_cursor CURSOR FOR
SELECT employee_id, first_name, department
FROM Employees;

-- Declare a CONTINUE HANDLER to exit loop when no more


rows are found
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_rows = TRUE;

-- Open the cursor


OPEN emp_cursor;

-- Loop through cursor result set


FETCH_LOOP: LOOP
-- Fetch data from cursor into variables
FETCH emp_cursor INTO emp_id, emp_first_name,
emp_department;

-- Check if no more rows


IF no_more_rows THEN
LEAVE FETCH_LOOP;
END IF;

-- Print employee details


SELECT CONCAT('Employee ID: ', emp_id, ', First Name:
', emp_first_name, ', Department: ', emp_department);
END LOOP;
-- Close the cursor
CLOSE emp_cursor;
END //
DELIMITER ;

36
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
CALL PrintEmployeeDetails();

37
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
Procedures : Procedures are stored programs in SQL/PL SQL that can contain multiple SQL and procedural
statements. They are used to group and encapsulate a series of SQL statements into a single unit, which can
then be executed on demand. Here's an overview of procedures in SQL/PL SQL:
Creating a Procedure:
In SQL, you can create procedures using the CREATE PROCEDURE statement.
Syntax:
CREATE PROCEDURE procedure_name
[ (parameter_list) ]
AS
BEGIN
-- Procedure body (SQL and procedural statements)
END;
Parameters:
Procedures can have input parameters, output parameters, or both.
Input parameters are used to pass values into the procedure.
Output parameters are used to return values from the procedure.
Syntax:
CREATE PROCEDURE procedure_name
(parameter1 datatype, parameter2 datatype, ...)
AS
BEGIN
-- Procedure body
END;
Executing a Procedure:
Once a procedure is created, it can be executed using the EXECUTE or EXEC statement.
Syntax:
EXEC procedure_name;
Example:
Below is a simple example of a procedure that takes two input parameters (a and b) and returns their sum:
CREATE PROCEDURE AddNumbers
@a INT,
@b INT
AS
BEGIN
DECLARE @sum INT;
SET @sum = @a + @b;
PRINT 'The sum is ' + CAST(@sum AS VARCHAR);
END;

1. Stored Procedure Example 1 - Retrieve Employees by Department: This procedure


retrieves employees from the Employees table based on a specified department.

DELIMITER //

CREATE PROCEDURE GetEmployeesByDepartment(IN dept VARCHAR(50))


BEGIN
SELECT * FROM Employees WHERE department = dept;
END //

DELIMITER ;

38
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

CALL GetEmployeesByDepartment('HR');

2. Stored Procedure Example 2 - Calculate Total Order Amount: This procedure calculates
the total order amount for a given order ID from the Orders table.
DELIMITER //

CREATE PROCEDURE CalculateTotalOrderAmount(IN orderId INT, OUT totalAmount


DECIMAL(10, 2))
BEGIN
SELECT total_amount INTO totalAmount FROM Orders WHERE order_id =
orderId;
END //

DELIMITER ;

CALL CalculateTotalOrderAmount(1, @totalAmount);


SELECT @totalAmount;
Triggers : Triggers are special types of stored procedures in SQL/PL SQL that are automatically
executed or fired in response to certain events occurring in a database. These events can include INSERT,
UPDATE, DELETE operations on a table, or even DDL (Data Definition Language) statements like CREATE,
ALTER, or DROP. Triggers are used to enforce business rules, maintain data integrity, perform logging or
auditing tasks, or automate tasks based on specific conditions.
Here's an overview of triggers in SQL/PL SQL:
1. Types of Triggers:
• BEFORE Triggers: Fired before the triggering event occurs, such as before an INSERT,
UPDATE, or DELETE operation.
• AFTER Triggers: Fired after the triggering event occurs, such as after an INSERT, UPDATE, or
DELETE operation.
• INSTEAD OF Triggers: Used with views and fired instead of the triggering event, such as
instead of an INSERT, UPDATE, or DELETE operation on a view.
2. Creating a Trigger:
• Triggers are created using the CREATE TRIGGER statement.
• Syntax:

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE | DROP | ALTER | ...}
ON table_name
[FOR EACH ROW] -- Only for row-level triggers
[WHEN condition] -- Optional
BEGIN
-- Trigger body (SQL and procedural statements)
END;
3. Trigger Events:

39
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL
• Triggers can be fired based on various events, including INSERT, UPDATE, DELETE, or even
DDL statements.,k,.m,,.m.,.,.,,.;………..
• You specify the event that triggers the execution of the trigger in the CREATE TRIGGER
statement.
4. Trigger Timing:
• Triggers can be fired either before or after the event that triggers them.
• BEFORE triggers are commonly used for validation or modification of data before it is
inserted, updated, or deleted.
• AFTER triggers are often used for logging, auditing, or other actions that occur after data
modification.
5. Trigger Body:
• The trigger body contains SQL and procedural statements that define what action should be
taken when the trigger fires.
• The trigger body can include conditionals, loops, and other procedural constructs to perform
complex logic.
6. Accessing OLD and NEW Values:
• Within the trigger body, you can access the OLD and NEW values of the affected rows.
• OLD values represent the values before the triggering event, while NEW values represent the
values after the triggering event.
7. Dropping a Trigger:
• Triggers can be dropped using the DROP TRIGGER statement.
• Syntax:

DROP TRIGGER trigger_name;

EXE:
DELIMITER //

CREATE TRIGGER PreventEmployeeDeletion


BEFORE DELETE ON Employees
FOR EACH ROW
BEGIN
IF OLD.salary > 60000 THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot delete employee with salary above $60,000';
END IF;
END //

DELIMITER ;

mysql> DELETE FROM Employees WHERE employee_id = 6;


ERROR : Cannot delete employee with salary above $60,000

40
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Content Beyond Syllabus

2.19 SQL FUNCTIONS (Date & Time, Numeric, Aggregate, String conversions):

DATE & TIME FUNCTIONS:

41
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

Some important date and time functions are below:

Sysdate: It generates the system date.

Ex: Select sysdate from dual;

Output: 05-DEC-2021.

ADD_MONTHS: This function returns a date after adding data with specified no of months.

EX: Select ADD_MONTHS („2017-02-29‟,1) from dual;

Output: 31-MAR-17.

Select add_months(sysdate,3) from dual;

Output: 05-MAR-22.

CURRENT_DATE: This function displays the current date.

Ex: Select CURRENT_DATE from dual;

Output: 05-DEC-2021.

NEXT_DAY: This function represents both day and date and returns the day of the next given day.

EX: Select NEXT_DAY(SYSDATE,‟MONDAY‟) from dual;

Output: 07-DEC-21.

LAST_DAY: This function returns a day corresponding last day of months.

EX: Select LAST_DAY (sysdate) from dual;

Output: 31-DEC-21.

42
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

MONTHS_BETWEEN: It is used to find no of months between two given dates.

EX: Select MONTHS_BETWEEN(‟16-APRIL-2021‟,‟16-AUGUST-2021) from dual;

Output: -4.

ROUND: It gives the nearest value or round off value for the argument pass. (or) It returns a date
rounded to a specific unit of measure.

EX: Select ROUND(‟26-NOV-21‟,‟YYYY‟) from dual;

Output: 01-JAN-22.

TRUNC: This function returns the date with the time(co-efficient) portion of the date truncated to
the unit specified.

EX: Select TRUNC (sysdate, ‟MM‟) from dual;

Output: 01-DEC-21.

TO_DATE: This function converts date which is in the character string to a date value.

EX: Select TO_DATE (‟01 jan 2017‟,‟DD MM YYYY‟) from dual;

Output: 01-JAN-17.

TO_CHAR: This function converts DATE or an INTERVAL value to a character string in a


specified format.

EX: Select TO_CHAR (sysdate,‟DD MM YYYY‟) from dual;

Output: 05 12 2021.

LEAST: This function displays the oldest date present in the argument list.

EX: Select LEAST(‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟) from dual;

Output: 01-MAR-21.

GREATEST: This function displays the latest date present in the argument list.

EX: Select GREATEST (‟01-march-2021‟,‟16-feb-2021‟,‟28-dec-2021‟) from dual;

Output: 28-DEC-21.

2.20 Aggregate Functions:


Aggregate Functions take a collection of values as input and returns a single value.

1. Count ()

2. Sum ()

3. Avg ()

43
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

4. Max ()

5. Min ()

1. Count (): This function returns number of rows returned by a query.

Syntax: Select count(column_name)

From table_name

Where condition);

Example: Select count (distinct manager_id) from employees;

2. Sum (): It will add/ sum all the column values in the query.

Syntax: Select sum (column_name)

From table_name

Where condition);

Example: Select sum(salaries) from employees;

3. Avg (): Avg function used to calculate average values of the set of rows.

Syntax: Select avg (column_name)

From table_name

Where condition);

Example: Select avg(salary) from employees;

4. Max (): This function is used to find maximum value from the set of values.

Syntax: Select max (column_name)

From table_name

Where condition);

Example: Select max (salary) from employees;

5. Min (): This function is used to find minimum value from the set of values.

Syntax: Select min (column_name)

From table_name

Where condition);

Example: Select min (salary) from employees;

44
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

2.21 SQL NUMERIC FUNCTIONS:

Numeric functions are used to perform operations on numbers and return numbers.

Following are some of the Numeric functions

1. ABS (): It returns the absolute value of a number.

EX: select ABS (-243.5) from dual;

OUTPUT: 243.5

2. ACOS (): It returns the cosine of a number.


EX: select ACOS (0.25) from dual;
OUTPUT: 1.318116071652818

3. ASIN (): It returns the arc sine of a number.


EX: select ASIN (0.25) from dual;
OUTPUT: 0.253680255142

4. CEIL (): It returns the smallest integer value that is a greater than or equal to a number.
EX: select CEIL (25.77) from dual;
OUTPUT: 26

45
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

5. FLOOR (): It returns the largest integer value that is a less than or equal to a number.
EX: select FLOOR (25.75) from dual;

OUTPUT: 25
6. TRUNCATE (): This does not work for SQL server. It returns the truncated to 2 places right of the
decimal point.
EX: select TRUNCATE (7.53635, 2) from dual;
OUTPUT: 7.53
7. MOD (): It returns the remainder when two numbers are divided.
EX: select MOD (55,2) from dual;
OUTPUT: 1.
8. ROUND (): This function rounds the given value to given number of digits of precision.
EX: select ROUND (14.5262,2) from dual;
OUTPUT: 14.53.
9. POWER (): This function gives the value of m raised to the power of n.
EX: select POWER (4,9) from dual;
OUTPUT: 262144.
10. SQRT (): This function gives the square root of the given value n.
EX: Select SQRT (576) from dual;
OUTPUT: 24.
11. LEAST (): This function returns least integer from given set of integers.

EX: select LEAST (1,9,2,4,6,8,22) from dual;

OUTPUT: 1.

12. GREATEST (): This function returns greatest integer from given set of integers.

EX: select GREATEST (1,9,2,4,6,8,22) from dual;

OUTPUT: 22

2.22 STRING CONVERSION FUNCTIONS OF SQL:

46
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

String Functions are used to perform an operation on input string and return the output string.
Following are the string functions

1. CONCAT (): This function is used to add two words (or) strings.

EX: select „database‟ ||‟ „|| „management system‟ From dual;

OUTPUT: „database management system‟

2. INSTR (): This function is used to find the occurrence of an alphabet.

EX: instr („database system‟,‟ a‟) from dual;

OUTPUT: 2 (the first occurrence of „a‟)

3. LOWER (): This function is used to convert the given string into lowercase.

EX: select lower („DATABASE‟) from dual;

OUTPUT: database

4. UPPER (): This function is used to convert the lowercase string into uppercase.

EX: select upper („database „) from dual;

OUTPUT: DATABASE

5. LPAD (): This function is used to make the given string of the given size by adding the given symbol.

EX: > lpad („system „, 8, „0‟) from dual;

OUTPUT: 00system

6. RPAD (): This function is used to make the given string as long as the given size by adding the given
symbol on the right.

EX: rpad („system „,8, „0„) from dual;

OUTPUT: system00

7. LTRIM (): This function is used to cut the given substring from the original string.

EX: ltrim („database „, „data „) from dual;

47
DATABASE MANAGEMENT SYSTEMS UNIT – II : RELATIONAL MODEL & SQL

OUTPUT: base

8. RTRIM (): This function is used to cut the given substring from the original string.

EX: rtrim („database „, „base „) from dual;

OUTPUT: data.

9. INITCAP (): This function returns the string with first letter of each word starts with uppercase.

EX: Select INITCAP („data base management system‟) from dual;

OUTPUT: Data Base Management System.

10. LENGTH (): Tis function returns the length of the given string.

EX: select LENGTH („SQ LANGUAGE‟) from dual;

OUTPUT: 11.

11. SUBSTR (): This function returns a portion of a string beginning at the character position.

EX: select SUBSTR („MY WORLD IS AMAZING‟,12,3) from dual;

OUTPUT: AM.

12. TRANSLATE (): This function returns a string after replacing some set of characters into another set.

EX: select TRANSLATE („Delhi is the capital of India‟,‟i‟,‟a‟) from dual;

OUTPUT: Delha as the capatal andaa.

48

You might also like