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

Database Management Unit 2 (Self)

DBMS notes

Uploaded by

raghvendrac210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Database Management Unit 2 (Self)

DBMS notes

Uploaded by

raghvendrac210
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit =2

(relational data model and languages)


Relational data model concept:
E.F. Codd proposed the relational Model to model data in the
form of relations or tables. After designing the conceptual
model of the Database using ER diagram, we need to convert
the conceptual model into a relational model which can be
implemented using any RDBMS language like Oracle SQL,
MySQL, etc. So we will see what the Relational Model is.

Relational model:
The relational model represents how data is stored in
Relational Databases. A relational database consists of a
collection of tables, each of which is assigned a unique name.
Consider a relation STUDENT with attributes ROLL_NO, NAME,
ADDRESS, PHONE, and AGE shown in the table.

Table Student
ROLL_NO NAME ADDRESS PHONE AGE

1 RAM DELHI 9455123451 18

2 RAMESH GURGAON 9652431543 18

3 SUJIT ROHTAK 9156253131 20

4 SURESH DELHI 18

Important Terminologies
 Attribute: Attributes are the properties that define an
entity. e.g.; ROLL_NO, NAME, ADDRESS
 Relation Schema: A relation schema defines the
structure of the relation and represents the name of
the relation with its attributes. e.g.; STUDENT
(ROLL_NO, NAME, ADDRESS, PHONE, and AGE)

 Tuple: Each row in the relation is known as a tuple. The


above relation contains 4 tuples, one of which is shown
as:
1 RAM DELHI 9455123451 18

 Relation Instance: The set of tuples of a relation at a


particular instance of time is called a relation instance.
 Degree: The number of attributes in the relation is
known as the degree of the relation.
The STUDENT relation defined above has degree 5.
 Cardinality: The number of tuples in a relation is
known as cardinality. The STUDENT relation defined
above has cardinality 4.
 Column: The column represents the set of values for a
particular attribute. The column ROLL_NO is extracted
from the relation STUDENT.
ROLL_NO

 NULL Values: The value which is not known or


unavailable is called a NULL value. It is represented by
blank space. e.g.; PHONE of STUDENT having ROLL_NO
4 is NULL.
 Relation Key: These are basically the keys that are
used to identify the rows uniquely or also help in
identifying tables
Introduction to Integrity
Constraints in DBMS
Integrity constraints in Database Management Systems

(DBMS) are a set of rules that are applied on the table

columns or relationships to ensure that the overall validity,

integrity, and consistency (i.e. the quality) of the data

present in the database table is maintained. Each and every

time a table insert, update, delete, or alter operation is

performed, it is evaluated against the terms or rules

mentioned in the integrity constraint. The data is inserted,

updated, deleted, or altered only if the result of the

constraint comes out to be True. Thus, integrity constraint

prevents accidental damage to the database by an

authorized user.

Types of Integrity Constraints in DBMS


in relational DBMS, we primarily have four types of integrity

constraints, namely :

.Domain Integrity Constraint

. Entity Integrity Constraint


 Referential Integrity Constraint

 Key Constraints

1. Domain Integrity Constraint


A domain integrity constraint is a set of rules that restricts

the kind of attributes or values a column or relation can hold

in the database table. For example, we can specify if a

particular column can hold null values or not, if the values

have to be unique or not, the data type or size of values that

can be entered in the column, the default values for the

column, etc.

For example, we want to create a “customer_details” table,

with information such as customer id, customer name, the

number of items purchased, date of purchase, etc. So, in

order to ensure domain integrity, we can specify the

customer_id has to be unique, the quantity of items

purchased has to be an integer number only and the date of

purchase has to be a date or timestamp, etc. This can be

achieved in the following manner while creating the table.

CREATE TABLE customer_details


(
customer_id character varying(255) NOT NULL,
customer_name character varying(255) NOT NULL,
quantity integer NOT NULL,
date_purchased date
);

insert query and check if the domain constraints have been

successfully applied.

INSERT INTO public.customer_details(


customer_id, customer_name, quantity, date_purchased)
VALUES ('US1002','Kabir Khan','ABC', 2019-12-31);

we can see that for the ‘quantity’ attribute when we tried to

insert a character value instead of an integer, the domain

constraint enables the server to throw an error.

2. Entity Integrity Constraint


Entity Integrity Constraint is used to ensure the uniqueness

of each record or row in the data table. There are primarily

two types of integrity constraints that help us in ensuring the

uniqueness of each row, namely, UNIQUE constraint and

PRIMARY KEY constraint. The unique key helps in uniquely

identifying a record in the data table. It can be considered

somewhat similar to the Primary key as both of them


guarantee the uniqueness of a record. But unlike the primary

key, a unique key can accept NULL values and it can be used

on more than one column of the data table.

CREATE TABLE Students(


Student_ID int NOT NULL,
Student_Name varchar(255) NOT NULL,
Class_Name varchar(255) UNIQUE,
Age int,
PRIMARY KEY (Student_ID)
);

INSERT INTO public.students(


student_id, student_name, class_name, age)
VALUES (32,'ABC','V',12),(32,'XYZ','V',11);

3. Referential Integrity Constraint


Referential Integrity Constraint ensures that there always

exists a valid relationship between two tables . This makes

sure that if a foreign key exists in a table relationship then it

should always reference a corresponding value in the second

table or it should be null.

We can create relationships between two tables in the

following manner. Here, we have created a “Department”


table and then “Employees” where the “department”

attribute references to Department_ID” in the former table.

CREATE TABLE Department(


Department_ID int NOT NULL,
Department_Name varchar(255) NOT NULL,
PRIMARY KEY(Department_ID)
);
CREATE TABLE Employees(
Employee_ID int NOT NULL,
Employee_Name varchar(255) NOT NULL,
Department int NOT NULL,
Age int,
FOREIGN KEY (Department) REFERENCES
Department(Department_ID)
);

After a few insertion operations, the data in the

“Department” table looks something like this . Now let’s try

to make an insert query and check if the entity constraints

have been successfully applied.

INSERT INTO public.employees(


employee_id, employee_name, department, age)
VALUES (1002,'K K Davis',10,43);
In the above example, we tried to insert a department that

does not exist in the “Department” table, hence it gives an

error.

4. Key Constraints
There are a number of key constraints in SQL that ensure

that an entity or record is uniquely or differently identified in

the database. There can be more than one key in the table

but it can have only one primary key.

Some of the key constraints in SQL are :

1. Primary Key Constraint

2. Foreign Key Constraint

3. Unique Key Constraint

Advantages of the Relational Model


 Simple model: Relational Model is simple and easy to use
in comparison to other languages.
 Flexible: Relational Model is more flexible than any other
relational model present.
 Secure: Relational Model is more secure than any other
relational model.
 Data Accuracy: Data is more accurate in the relational
data model.
 Data Integrity: The integrity of the data is maintained in
the relational model.
 Operations can be Applied Easily: It is better to
perform operations in the relational model.
Disadvantages of the Relational Model
 Relational Database Model is not very good for large
databases.
 Sometimes, it becomes difficult to find the relation
between tables.
 Because of the complex structure, the response time for
queries is high.
Characteristics of the Relational Model
 Data is represented in rows and columns called relations.
 Data is stored in tables having relationships between them
called the Relational model.
 The relational model supports the operations like Data
definition, Data manipulation, and Transaction
management.
 Each column has a distinct name and they are representing
attributes.
 Each row represents a single entity.
Relational Calculus



Both Relational Algebra and Relational Calculus are formal
query languages.

Relational Algebra:

Relational Algebra is a procedural language. In Relational Algebra,


The order is specified in which the operations have to be performed.
In Relational Algebra, frameworks are created to implement the
queries. The basic operation included in relational algebra are:
1. Select (σ)
2. Project (Π)
3. Union (U)
4. Set Difference (-)
5. Cartesian product (X)
6. Rename (ρ)

Relational Calculus:

Relational Calculus is the formal query language. It is also known


as Declarative language. In Relational Calculus, the order is not
specified in which the operation has to be performed. Relational
Calculus means what result we have to obtain.
Relational Calculus has two variations:
1. Tuple Relational Calculus (TRC)
2. Domain Relational Calculus (DRC)

Relational Calculus is denoted as:


{ t | P(t) }

Where,
t: the set of tuples
p: is the condition which is true for the given set of tuples.

Difference between Relational Algebra and Relational Calculus:

S.N Basis of
O Comparison Relational Algebra Relational Calculus

Relational Calculus is a
It is a Procedural
Language Type Declarative (non-procedural)
language.
1. language.

Relational Algebra means Relational Calculus means


Procedure
2. how to obtain the result. what result we have to obtain.

In Relational Algebra, the


order is specified in which In Relational Calculus, the
Order
the operations have to be order is not specified.
3. performed.

Relational Algebra is Relation Calculus can be


Domain independent of the domain-dependent because
4. domain. of domain relational calculus.

Relational Calculus is not


Relational Algebra is
Programming nearer to programming
nearer to a programming
language language but to natural
language.
5. language.
S.N Basis of
O Comparison Relational Algebra Relational Calculus

The SQL includes only SQL is based to a greater


Inclusion in
some features from the extent on the tuple relational
SQL
6. relational algebra. calculus.

Relational Algebra is one


of the languages in which For a database language to be
queries can be expressed relationally complete, the
Relationally
but the queries should query written in it must be
completeness
also be expressed in expressible in relational
relational calculus to be calculus.
7. relationally complete.

The evaluation of the


The order of operations does
query relies on the order
Query not matter in relational
specification in which the
Evaluation calculus for the evaluation of
operations must be
queries.
8. performed.

For accessing the


database, relational For accessing the database,
algebra provides a relational calculus provides a
Database solution in terms of what solution in terms as simple as
access is required and how to get what is required and lets the
that information by system find the solution for
following a step-by-step that.
9. description.

10. Expressiveness The expressiveness of any The completeness of a


given language is judged language is measured in the
using relational algebra manner that it is least as
operations as a standard. powerful as calculus. That
implies relation defined using
some expression of the
calculus is also definable by
S.N Basis of
O Comparison Relational Algebra Relational Calculus

some other expression, the


language is in question.

Tuple Relational Calculus (TRC) :


A tuple relational calculus is a non-procedural query language that
specifies to select of the tuples in a relation. It can select the tuples
with a range of values or tuples for certain attribute values etc. The
resulting relation can have one or more tuples.
Notation :
{T | P (T)} or {T | Condition (T)}
where T is the resulting tuples and P(T) is a condition used to fetch
T.
Example :
{T | EMPLOYEE (T) AND T.DEPT_ID = 10}
This selects all the tuples of employee names who work for
Department 10.

2. Domain Relational Calculus (DRC) :


A domain relational calculus uses the list of attributes to be selected
from the relation based on the condition. It is the same as TRC but
differs by selecting the attributes rather than selecting whole

tuples.
Notation :
{ a1, a2, a3, ..., an | P (a1, a2, a3, ..., an) }
Where a1, a2, a3, … an are attributes of the relation and P is the
condition.

Example :
{ | < EMPLOYEE > DEPT_ID = 10 }
select EMP_ID and EMP_NAME of employees who work for
department 10.
Difference between Tuple Relational Calculus (TRC) and Domain
Relational Calculus (DRC) :

S. Basis of Tuple Relational Domain Relational


No. Comparison Calculus (TRC) Calculus (DRC)

The Tuple Relational The Domain Relational


Calculus (TRC) is used to Calculus (DRC) employs a list
select tuples from a of attributes from which to
relation. The tuples with choose based on the
1. Definition
specific range values, tuples condition. It’s similar to TRC,
with certain attribute but instead of selecting
values, and so on can be entire tuples, it selects
selected. attributes.

In TRC, the variables In DRC, the variables


Representation
2. represent the tuples from represent the value drawn
of variables
specified relations. from a specified domain.

A domain is equivalent to
A tuple is a single element
column data type and any
3. Tuple/ Domain of relation. In database
constraints on the value of
terms, it is a row.
data.

This filtering variable uses a This filtering is done based


4. Filtering
tuple of relations. on the domain of attributes.

The predicate expression


DRC takes advantage of
condition associated with
domain variables and, based
the TRC is used to test
on the condition set, returns
5. Return Value every row using a tuple
the required attribute or
variable and return those
column that satisfies the
tuples that met the
criteria of the condition.
condition.

5. Membership The query cannot be The query can be expressed


S. Basis of Tuple Relational Domain Relational
No. Comparison Calculus (TRC) Calculus (DRC)

expressed using a using a membership


condition
membership condition. condition.

The QUEL or Query The QBE or Query-By-


6. Query Language Language is a query Example is query language
language related to it, related to it.

It reflects traditional pre- It is more similar to logic as a


7. Similarity
relational file structures. modeling language.

Notation: {T | P (T)} or {T | Notation: { a1, a2, a3, …, an


8. Syntax
Condition (T)} | P (a1, a2, a3, …, an)}

{T | EMPLOYEE (T) AND { | < EMPLOYEE > DEPT_ID =


9. Example
T.DEPT_ID = 10} 10 }

Focuses on selecting tuples Focuses on selecting values


10. Focus
from a relation from a relation

Uses scalar variables (e.g.,


11. Variables Uses tuple variables (e.g., t)
a1, a2, …, an)

12. Expressiveness Less expressive More expressive

Easier to use for simple More difficult to use for


13. Ease of use
queries. simple queries.

14. Use case Useful for selecting tuples Useful for selecting specific
that satisfy a certain values or for constructing
condition or for retrieving a more complex queries that
S. Basis of Tuple Relational Domain Relational
No. Comparison Calculus (TRC) Calculus (DRC)

subset of a relation. involve multiple relations.

SQL



SQL is a standard database language used to access and manipulate
data in databases. SQL stands for Structured Query Language. SQL
was developed by IBM Computer Scientists in the 1970s. By
executing queries SQL can create, update, delete, and retrieve data
in databases like MySQL, Oracle, PostgreSQL, etc. Overall SQL is a
query language that communicates with databases.
SQL also provides a standardized way of communicating with
databases, ensuring that data is consistent and uniform across
different systems. Its popularity and versatility have made it a
must-have skill for data professionals and developers, as it is used
extensively in various applications such as web development, data
analytics, business intelligence, and more.

Need of SQL :

 It is widely used in the Business Intelligence tool.

 Data Manipulation and data testing are done through SQL.

 Data Science tools depend highly on SQL. Big data tools


such as Spark, Impala are dependent on SQL.

 It is one of the demanding industrial skills.

Advantages of SQL :
SQL has many advantages which makes it popular and highly
demanded. It is a reliable and efficient language used for
communicating with the database. Some advantages of SQL are as
follows:

1. Faster Query Processing –


Large amount of data is retrieved quickly and efficiently.
Operations like Insertion, deletion, manipulation of data is
also done in almost no time.

2. No Coding Skills –
For data retrieval, large number of lines of code is not
required. All basic keywords such as SELECT, INSERT INTO,
UPDATE, etc are used and also the syntactical rules are not
complex in SQL, which makes it a user-friendly language.

3. Standardized Language –
Due to documentation and long establishment over years,
it provides a uniform platform worldwide to all its users.

4. Portable –
It can be used in programs in PCs, server, laptops
independent of any platform (Operating System, etc). Also,
it can be embedded with other applications as per
need/requirement/use.

5. Interactive Language –
Easy to learn and understand, answers to complex queries
can be received in seconds.

6. Multiple data views –


7. Scalability: SQL databases can handle large volumes of
data and can be scaled up or down as per the requirements
of the application.
8. Security: SQL databases have built-in security features
that help protect data from unauthorized access, such as
user authentication, encryption, and access control.
9. Data Integrity: SQL databases enforce data integrity by
enforcing constraints such as unique keys, primary keys,
and foreign keys, which help prevent data duplication and
maintain data accuracy.
10. Backup and Recovery: SQL databases have built-in
backup and recovery tools that help recover data in case of
system failures, crashes, or other disasters.
11. Data Consistency: SQL databases ensure consistency
of data across multiple tables through the use of
transactions, which ensure that changes made to one table
are reflected in all related tables.
Disadvantages of SQL :
Although SQL has many advantages, still there are a few
disadvantages.
Various Disadvantages of SQL are as follows:

1. Complex Interface –
SQL has a difficult interface that makes few users
uncomfortable while dealing with the database.

2. Cost –
Some versions are costly and hence, programmers cannot
access it.

3. Partial Control –
Due to hidden business rules, complete control is not given
to the database.
4. Limited Flexibility: SQL databases are less flexible than
NoSQL databases when it comes to handling unstructured
or semi-structured data, as they require data to be
structured into tables and columns.
5. Lack of Real-Time Analytics: SQL databases are
designed for batch processing and do not support real-time
analytics, which can be a disadvantage for applications
that require real-time data processing.
6. Limited Query Performance: SQL databases may have
limited query performance when dealing with large
datasets, as queries may take longer to process than in-
memory databases.
7. Complexity: SQL databases can be complex to set up and
manage, requiring skilled database administrators to
ensure optimal performance and maintain data integrity.

Applications of SQL :

 SQL is used by developers and DBAs (Database


Administrators) in writing Data Integration Scripts.

 It is used to deal with analytical queries to analyze the data


and get instincts from it.

 Retrieving Information
 Modification/Manipulation of data and database table such
as Insertion, Deletion and Updation .

SQL Literals



There are four kinds of literal values supported in SQL. They are :
Character string, Bit string, Exact numeric, and Approximate
numeric. These are explained as following below.
1. Character string : Character strings are written as a
sequence of characters enveloped in single quotes. the only
quote character is delineate at intervals a personality string
by 2 single quotes. Some example of character strings are :
 ‘My String’
 ‘I love GeeksForGeeks’
 ‘16378’
2. Bit string : A bit string is written either as a sequence of 0s
and 1s enveloped in single quotes and preceded by the
letter ‘B’ or as a sequence of positional representation
system digits enveloped in single quotes and preceded by
the letter X’ some examples are given below :
 B’10001011′
 B’1′
 B’0′
 X’C 5′
 X’0′
3. Exact numeric : These literals are written as a signed or
unsigned decimal variety probably with mathematical
notation. Samples of actual numeric literals are given
below :
 8
 80
 80.00
 0.8
 +88.88
 -88.88
4. Approximate numeric : Approximate numeric literals are
written as actual numeric literals followed by the letter ‘E’,
followed by a signed or unsigned number. Some example
are :
 6E6
 66.6E6
 +66E-6
 0.66E
 -6.66E-8

SQL Commands
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries
of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.

1. Data Definition Language (DDL)


o DDL changes the structure of the table like creating a table, deleting
a table, altering a table, etc.
o 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:


o CREATE
o ALTER
o DROP
o TRUNCATE

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

Syntax:

CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

b. DROP: It is used to delete both the structure and record stored in the
table.

Syntax

1. DROP TABLE table_name;

c. 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:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);

d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.

Syntax:

1. TRUNCATE TABLE table_name;


2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all
form of changes in the database.
o 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

2:UPDATE

3:DELETE

a. INSERT: The INSERT statement is a SQL query. It is used to insert data


into the row of a table.

Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);

OR

INSERT INTO TABLE_NAME

1. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS")


;

b. UPDATE: This command is used to update or modify the value of a


column in the table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN


= valueN] [WHERE CONDITION]

For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

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

Syntax:
1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. 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:

o Grant
o Revoke

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

Example

1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_U


SER;

b. Revoke: It is used to take back permissions from the user.

Example

1. 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:

o COMMIT
o ROLLBACK
o SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the


database.
Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have


not already been saved to the database.

Syntax:

1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

c. SAVEPOINT: It is used to roll the transaction back to a certain point


without rolling back the entire transaction.

Syntax:

1. SAVEPOINT SAVEPOINT_NAME;
5. Data Query Language
DQL is used to fetch the data from the database.

It uses only one command:

o SELECT

a. 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:

1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;

For example:

1. SELECT emp_name ;
2. FROM employee ;
3. WHERE age > 20;
SQL Operators



Structured Query Language is a computer language that we
use to interact with a relational database. In this article we will
see all types of SQL operators.
In simple operator can be defined as an entity used to perform
operations in a table.
Operators are the foundation of any programming language.
We can define operators as symbols that help us to perform
specific mathematical and logical computations on operands. In
other words, we can say that an operator operates the
operands. SQL operators have three different categories.
Types of SQL Operators
 Arithmetic operator
 Comparison operator
 Logical operator
Arithmetic Operators
We can use various arithmetic operators on the data stored in the tables.
Arithmetic Operators are:

Operator Description

+ The addition is used to perform an addition operation on the data values.

– This operator is used for the subtraction of the data values.

This operator works with the ‘ALL’ keyword and it calculates division
/
operations.
Operator Description

* This operator is used for multiplying data values.

% Modulus is used to get the remainder when data is divided by another.

Example Query:
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:

Comparison Operators
Another important operator in SQL is a comparison operator, which is used to
compare one expression’s value to other expressions. SQL supports different
types of comparison operator, which is described below:
Operator Description

= Equal to.

> Greater than.

< Less than.

>= Greater than equal to.

<= Less than equal to.

<> Not equal to.


Operator Description

Example Query:
SELECT * FROM MATHS WHERE MARKS=50;
Output:

Logical Operators
The Logical operators are those that are true or false. They return true or false
values to combine one or more true or false values.

Operator Description

Logical AND compares two Booleans as expressions and returns true


AND
when both expressions are true.

Logical OR compares two Booleans as expressions and returns true when


OR
one of the expressions is true.

Not takes a single Boolean as an argument and change its value from false
NOT
to true or from true to false.

Example Query:
SELECT * FROM employee WHERE emp_city =
'Allahabad' AND emp_country = 'India';
Output:

SQL Indexes



An index is a schema object. It is used by the server to speed
up the retrieval of rows by using a pointer. It can reduce disk
I/O(input/output) by using a rapid path access method to locate
data quickly.
An index helps to speed up select queries and where clauses,
but it slows down data input, with the update and the insert
statements. Indexes can be created or dropped with no effect
on the data. In this article, we will see how to create, delete,
and use the INDEX in the database.
Creating an Index
Syntax
CREATE INDEX index
ON TABLE column;
SQL | Subquery

 A subquery is a query within another query. The


outer query is called as main query and inner query is
called as subquery.
 The subquery generally executes first when the subquery
doesn’t have any co-relation with the main query,
when there is a co-relation the parser takes the
decision on the fly on which query to execute
on precedence and uses the output of the subquery
accordingly.
 Subquery must be enclosed in parentheses.
 Subqueries are on the right side of the comparison
operator.
 ORDER BY command cannot be used in a
Subquery. GROUPBY command can be used to perform
same function as ORDER BY command.
Use single-row operators with singlerow Subqueries. Use

multiple-row operators with multiple-row Subqueries.
Syntax: There is not any general syntax for Subqueries.
However, Subqueries are seen to be used most frequently with
SELECT statement as shown below:
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT COLUMN_NAME from TABLE_NAME WHERE ... );

Aggregate functions in SQL





In database management an aggregate function is a function
where the values of multiple rows are grouped together as
input on certain criteria to form a single value of more
significant meaning.

Various Aggregate Functions


1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
Now let us understand each Aggregate function with a
example:
Id Name Salary
-----------------------
1 A 80
2 B 40
3 C 60
4 D 70
5 E 60
6 F Null
Count():

Count(*): Returns total number of records .i.e 6.


Count(salary): Return number of Non Null values over the
column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null
values over the column salary .i.e 4

Sum():

sum(salary): Sum all Non Null values of Column salary i.e.,


310
sum(Distinct salary): Sum of all distinct Non-Null values i.e.,
250.

Avg():

Avg(salary) = Sum(salary) / count(salary) = 310/5


Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct
Salary) = 250/4

Min():

Min(salary): Minimum value in the salary column except


NULL i.e., 40.
Max(salary): Maximum value in the salary i.e., 80.
What is Cursor in SQL ?



Cursor is a Temporary Memory or Temporary Work Station. It
is Allocated by Database Server at the Time of
Performing DML(Data Manipulation Language) operations on
the Table by the User. Cursors are used to store Database
Tables.
There are 2 types of Cursors: Implicit Cursors, and Explicit
Cursors. These are explained as following below.
1. Implicit Cursors: Implicit Cursors are also known as
Default Cursors of SQL SERVER. These Cursors are
allocated by SQL SERVER when the user performs DML
operations.
2. Explicit Cursors: Explicit Cursors are Created by Users
whenever the user requires them. Explicit Cursors are
used for Fetching data from Table in Row-By-Row
Manner.

SQL | Triggers



Trigger is a statement that a system executes automatically
when there is any modification to the database. In a trigger, we
first specify when the trigger is to be executed and then the
action to be performed when the trigger executes. Triggers are
used to specify certain integrity constraints and referential
constraints that cannot be specified using the constraint
mechanism of SQL.
Example –
Suppose, we are adding a tuple to the ‘Donors’ table that is
some person has donated blood. So, we can design a trigger
that will automatically add the value of donated blood to the
‘Blood_record’ table.
Types of Triggers –
We can define 6 types of triggers for each table:
1. AFTER INSERT activated after data is inserted into the
table.

2. AFTER UPDATE: activated after data in the table is


modified.

3. AFTER DELETE: activated after data is


deleted/removed from the table.

4. BEFORE INSERT: activated before data is inserted into


the table.

5. BEFORE UPDATE: activated before data in the table is


modified.
6. BEFORE DELETE: activated before data is
deleted/removed from the table.

SQL | Procedures in PL/SQL





PL/SQL is a block-structured language that enables developers
to combine the power of SQL with procedural statements. A
stored procedure in PL/SQL is nothing but a series of declarative
SQL statements which can be stored in the database catalogue.
A procedure can be thought of as a function or a method. They
can be invoked through triggers, other procedures, or
applications on Java, PHP etc. All the statements of a block are
passed to Oracle engine all at once which increases processing
speed and decreases the traffic. Advantages:
They result in performance improvement of the

application. If a procedure is being called frequently in
an application in a single connection, then the compiled
version of the procedure is delivered.
 They reduce the traffic between the database and the
application, since the lengthy statements are already
fed into the database and need not be sent again and
again via the application.
 They add to code reusability, similar to how functions
and methods work in other languages such as C/C++
and Java.
Disadvantages:
 Stored procedures can cause a lot of memory usage.
The database administrator should decide an upper
bound as to how many stored procedures are feasible
for a particular application.
 MySQL does not provide the functionality of debugging
the stored procedures.

Syntax to create a stored procedure


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Comments --

CREATE PROCEDURE procedure_name


= ,
= ,
=

AS
BEGIN
-- Query --
END

GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE GetStudentDetails


@StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, BirthDate, City, Country
FROM Students WHERE StudentID=@StudentID
END
GO
Syntax to modify an existing stored procedure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Comments --

ALTER PROCEDURE procedure_name


= ,
= ,
=

AS
BEGIN
-- Query --
END

GO
Example:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE GetStudentDetails


@StudentID int = 0
AS
BEGIN
SET NOCOUNT ON;
SELECT FirstName, LastName, City
FROM Students WHERE StudentID=@StudentID
END
GO
Syntax to drop a Procedure:
DROP PROCEDURE procedure_name
Example:
DROP PROCEDURE GetStudentDetails

You might also like