You are on page 1of 62

Harlal Institute Of Management & Technology

Address:(8 Institutional area Knowledge park I greater Noida


Uttar Pradesh)
201310

Estd.1998

A
Practicle file of ‘Database Management System’
Subject Code: 505
COURSE: Bachlor’s Of Computer Application (BCA)

Submitted To :- Submitted By :-
Himanshu Sir Abhinay Rana

(BCA Vth Semester)


Roll No: 210916106001
INDEX

S.NO. TITTLE NAME PAGE NO.


1. Introduction to MYSQL
2. Data Definition Language (DDL)
Commands
3. Data Manipulation Language (DML)
Commands
4. Sub Queries and Joins
5. Views
6. Procedures
7. Cursors
8. Triggers
9. Normalization
10. Checking Normalization
1. Introduction To MYSQL

A Database Management System (DBMS) is a software application that interacts with the
user, applications and the database itself to capture and analyze data. The data stored in the
database can be modified, retrieved and deleted, and can be of any type like strings, numbers,
images etc.

There are mainly 4 types of DBMS, which are Hierarchical, Relational, Network, and
Object-Oriented DBMS.

• Hierarchical DBMS: As the name suggests, this type of DBMS has a style of
predecessor-successor type of relationship. So, it has a structure similar to that of
a tree, wherein the nodes represent records and the branches of the tree represent
fields.
• Relational DBMS (RDBMS): This type of DBMS, uses a structure that allows the
users to identify and access data in relation to another piece of data in the
database.
• Network DBMS: This type of DBMS supports many to many relations wherein
multiple member records can be linked.
• Object-oriented DBMS: This type of DBMS uses small individual software called
objects. Each object contains a piece of data, and the instructions for the actions
to be done with the data.

Structured Query Language (SQL)


SQL is the core of a relational database which is used for accessing and managing the
database. By using SQL, you can add, update or delete rows of data, retrieve subsets of
information, modify databases and perform many actions. The different subsets of SQL
are as follows:

• DDL (Data Definition Language) – It allows you to perform various operations on


the database such as CREATE, ALTER and DELETE objects.
• DML (Data Manipulation Language) – It allows you to access and manipulate data.
It helps you to insert, update, delete and retrieve data from the database.
• DCL (Data Control Language) – It allows you to control access to the database.
Example – Grant or Revoke access permissions.
• TCL (Transaction Control Language) – It allows you to deal with the transaction of
the database. Example – Commit, Rollback, Savepoint, Set Transaction.
MYSQL :-
The full form of MYSQL is My Structured Query Language. It is a popular open-source
relational database management system (RDBMS) that is used for storing and
managing data.

MySQL is currently the most popular database management system software


used for managing the relational database. It is open-source database software, which is
supported by Oracle Company. It is fast, scalable, and easy to use database
management system in comparison with Microsoft SQL Server and Oracle Database.

MySQL is becoming so popular because of these following reasons:

o MySQL is an open-source database, so you don't have to pay a single penny to use
it.
o MySQL is a very powerful program that can handle a large set of functionality of
the most expensive and powerful database packages.
o MySQL is customizable because it is an open-source database, and the open-
source GPL license facilitates programmers to modify the SQL software according
to their own specific environment.
o MySQL is quicker than other databases, so it can work well even with the large data
set.
o MySQL supports many operating systems with many languages like PHP, PERL, C,
C++, JAVA, etc.
o MySQL uses a standard form of the well-known SQL data language.
o MySQL is very friendly with PHP, the most popular language for web development.
o MySQL supports large databases, up to 50 million rows or more in a table. The
default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).

• MySQL is a relational database management system


• MySQL is open-source
• MySQL is free
• MySQL is ideal for both small and large applications
• MySQL is very fast, reliable, scalable, and easy to use
• MySQL is cross-platform
• MySQL is compliant with the ANSI SQL standard
• MySQL was first released in 1995
• MySQL is developed, distributed, and supported by Oracle Corporation
• MySQL is named after co-founder Monty Widenius's daughter: My

Difference Between MYSQL and SQL:

MySQL SQL

SQL is developed by Microsoft


MySQL was owned by Oracle corporation.
Corporation.

MySQL is open source and accessible to any


SQL is not open to others for free.
and everyone for free.

MySQL supports basic programming SQL is in itself a programming language


languages like C, C++, Python, Ruby, etc. used for database systems.

MySQL available only in the English language. SQL is available in different languages.

MySQL doesn’t support user-defined SQL supports user-defined functions and


functions and XML. XML.

Application of MySQL :
• MySQL used in E-Commerce websites.
• MySQL used in Data Warehousing.
• MySQL is used in the Login Application.
These SQL commands are mainly categorized into five categories:

1. DDL – Data Definition Language


2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language
2. Data Definition Language (DDL)
Commands
o DDL stands for Data Definition Language. It is used to define database structure
or pattern.
o It is used to create schema, tables, indexes, constraints, etc. in the database.
o Using the DDL statements, you can create the skeleton of the database.
o Data definition language is used to store the information of metadata like the
number of tables and schemas, their names, indexes, columns in each table,
constraints, etc.

These commands are used to update the database schema that's why they come under
Data definition language.

o Create: It is used to create objects in the database.


o Alter: It is used to alter the structure of the database.
o Drop: It is used to delete objects from the database.
o Truncate: It is used to remove all records from a table.
o Rename: It is used to rename an object.
o Comment: It is used to comment on the data dictionary.

CREATE

The create command is used to create a new database object, such as a table,
view, or index.

Example :- The SQL query that follows creates the "employees" database
with the columns "id," "name," and "salary" −

CREATE TABLE employees (


id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
salary DECIMAL(10,2)
);
Output Table :-
+ + + +
| id | name | salary |
+ + + +

ALTER

ALTER is used to change a database object's existing structure. You can create,
alter, or delete columns, constraints, or indexes with the ALTER command.

Example :- The "employees" database gets a new field called


"department" thanks to the SQL query that follows –

ALTER TABLE employees ADD department VARCHAR(50);

Output Table :-
+ + + + +
| id | name | salary | department |
+ + + + +
DROP

DROP is used to remove a table, view, or other existing database object. The
object and any related data are permanently deleted with the DROP command.

Example :- The "employees" table is deleted with the SQL query that
follows –

DROP TABLE employees;

Output :-
The "employees" table and all of its data would be permanently wiped following
the execution of the "DROP TABLE employees" command, and there would be
no input or output table to show.
TRUNCATE

Every piece of data from a table that already exists can be removed using
TRUNCATE. The Shorten order, as opposed to the DROP order, basically
eliminates the information from a data set, not the actual table.

Example :- This was the employee's table −

+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +

The "employees" table is truncated by the SQL expression that follows –

TRUNCATE TABLE employees;

Output Table :-

+----+------+-------+ ------------ +
| id | name | salary| department |
+----+------+-------+ ------------ +
| | | | |
+----+------+-------+ ------------ +

The "employees" table's data is completely removed by the TRUNCATE


command, but the table itself is left intact. The table would still be there once
the command was run, but it would be empty of data rows. The output table
displays the "employees" table's structure after the command has been run but
without any data.
RENAME

This command is used to rename a table or column in an existing database.

Example :-

Input Table

+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +
The "staff" table is renamed in the following SQL query from the "employees"
table −
RENAME TABLE employees TO staff;

Output Table :-
+ + + + +
| id | name | salary | department |
+ + + + +
| 1 | Alice | 50000 | Engineering |
| 2 | Bob | 60000 | Marketing |
| 3 | Charlie| 75000 | Sales |
| 4 | Dave | 65000 | Engineering |
| 5 | Eve | 55000 | Marketing |
+ + + + +

The SQL command "RENAME TABLE employees TO staff" just renames the
existing "employees" table to "staff" in the current keyspace, therefore there is
no change to the input and output tables. As a result, the sole distinction is the
name of the table, which has been changed from "employees" to "staff".
3. Data Manipulation Language
(DML) Commands
DML (data manipulation language) is part of SQL, the language used to interact
with relational databases. It is used to add, update, and remove records from a
database and otherwise change the data there. DML enables you to interact with and
modify the data in your database
Data Manipulation Language (DML) is a language by which users access and
manipulate data. Data manipulation refers to retrieval, insertion, deletion and modification
of data or information stored in the database. The basic goal is to attain efficient human
interaction with the system. DML is just like simple English language and is mostly used
as a Structured Query Language (SQL) for information retrieval and manipulation.

Data Manipulation Language is of two types:


a) Procedural – The type of data needed and the mechanism to get it is
specified by the user.
b) Non Procedural – Only the type of data needed is specified by the user.

The basic DML commands are :


a) SELECT – This is the most widely used DML command. It retrieves information or records
from the database.
b) UPDATE – This command is used for modification purpose. It can modify data of one or
more records according to the specified conditions.

c) INSERT – This command is used for adding one or more records to a database.
d) DELETE – This command is used for removing one or more records from a database
according to the specified conditions.

INSERT
The INSERT command is used to add data to a table.
The syntax of the INSERT command is as follows –
INSERT INTO table_name (column1, column2, column3, ...) VALUES
(value1, value2, value3, ...);
Example :- Consider a table having the columns "id," "name," and "email"
named "customers." We can use the following command to add a new record to
the table −

Input Table
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +

INSERT INTO customers (id, name, email) VALUES (1, 'John Doe',
'john.doe@example.com');

Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 1 | John Doe| john.doe@example.com|
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +

UPDATE

A table's existing data can be changed using the UPDATE command.

The UPDATE command has the following syntax –


UPDATE table_name SET column1 = value1, column2 = value2,
... WHERE condition;

Example :- suppose we need to change the email address for a client


with ID 1. We can use the following command to this −

Input Table
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +
UPDATE customers SET email = 'johndoe@example.com' WHERE id = 1;

Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 1 | John Doe| johndoe@example.com|
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +

DELETE

To remove current data from a table, use the DELETE command.

The DELETE command has the following syntax –


DELETE FROM table_name WHERE condition;

Example :- That we wish to remove the customer record with the id of 1.


We can use the following command to this –

DELETE FROM customers WHERE id = 1;

Using the same input table −

Output Table :-
+ + + +
| id | name | email |
+ + + +
| 0 | Alice | alice@example.com |
| 2 | Bob | bob@example.com |
| 3 | Charlie | charlie@example.com |
| 4 | Dave | dave@example.com |
| 5 | Eve | eve@example.com |
+ + + +

SELECT

To get data out of a table, use the SELECT command.

The SELECT command has the following syntax –

SELECT column1, column2, ... FROM table_name WHERE


condition;

Example :- Consider the scenario where we need to get the names and
email addresses of every consumer who has made a transaction.We can use the
following command to this −

Input Table

+ + + + +
| id | name | email | has_made_purchase |
+ + + + +
|1 | John Doe | john.doe@example.com | true |
|2 | Jane Doe | jane.doe@example.com | false |
|3 | Bob Smith| bob.smith@example.com| true |
|4 | Alice Lee| alice.lee@example.com| true |
+ + + + +

SELECT name, email FROM customers WHERE has_made_purchase =


true;

Output Table :-

+ + +
| name | email |
+ + +
| John Doe | john.doe@example.com |
| Bob Smith| bob.smith@example.com|
| Alice Lee| alice.lee@example.com|
+ + +
4. Sub Queries and Joins
Sub Queries –
A Subquery or Inner query or Nested query is a query within SQL
query and embedded within the WHERE clause. A Subquery is a SELECT
statement that is embedded in a clause of another SQL statement. They can be
very useful to select rows from a table with a condition that depends on the data
in the same or another table. A Subquery is used to return data that will be used
in the main query as a condition to further restrict the data to be retrieved. The
subquery can be placed in the following SQL clauses they are WHERE clause,
HAVING clause, FROM clause.

Advantages Of Subquery:

• Subqueries divide the complex query into isolated parts so that a complex
query can be broken down into a series of logical steps.
• It is easy to understand and code maintenance is also at ease.
• Subqueries allow you to use the results of another query in the outer query.
• In some cases, subqueries can replace complex joins and unions.

Disadvantages of Subquery:
• The optimizer is more mature for MYSQL for joins than for subqueries, so in
many cases a statement that uses a subquery can be executed more
efficiently if you rewrite it as join.
• We cannot modify a table and select from the same table within a subquery
in the same SQL statement.

An SQL Subquery, is a SELECT query within another query. It


is also known as Inner query or Nested query and the query containing
it is the outer query.

The outer query can contain the SELECT, INSERT, UPDATE,


and DELETE statements. We can use the subquery as a column
expression, as a condition in SQL clauses, and with operators like =,
>, <, >=, <=, IN, BETWEEN, etc.
Subqueries with the SELECT Statement
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name
OPERATOR (SELECT column_name [,column_name ] FROM table1 [,
table2 ] [WHERE]);

Subqueries with the INSERT Statement


INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ]

Subqueries with the UPDATE Statement

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

Subqueries with the DELETE Statement

DELETE FROM TABLE_NAME


[WHERE OPERATOR [ VALUE ](SELECT COLUMN_NAME FROM
TABLE_NAME)[WHERE)];

Joins :-
A join is a query that combines records from two or more tables. A join
will be performed whenever multiple tables appear in the FROM clause of the
query. The select list of the query can select any columns from any of these
tables. If join condition is omitted or invalid then a Cartesian product is formed.
If any two of these tables have a column name in common, then must qualify
these columns throughout the query with table or table alias names to avoid
ambiguity. Most join queries contain at least one join condition, either in the
FROM clause or in the WHERE clause.
Advantages Of Joins:
• The advantage of a join includes that it executes faster.
• The retrieval time of the query using joins almost always will be faster than
that of a subquery.
• By using joins, you can minimize the calculation burden on the database i.e.,
instead of multiple queries using one join query. This means you can make
better use of the database’s abilities to search through, filter, sort, etc.

Disadvantages Of Joins:
• Disadvantage of using joins includes that they are not as easy to read as
subqueries.
• More joins in a query means the database server has to do more work,
which means that it is more time consuming process to retrieve data
• As there are different types of joins, it can be confusing as to which join is
the appropriate type of join to use to yield the correct desired result set.
• Joins cannot be avoided when retrieving data from a normalized database,
but it is important that joins are performed correctly, as incorrect joins can
result in serious performance degradation and inaccurate query results.

A JOIN clause is used to combine rows from two or more tables,


based on a related column between them.

There are the different types of the JOINs in SQL:

• (INNER) JOIN: Returns records that have matching values in both tables
• LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
• RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
• FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
INNER JOIN :-
The INNER JOIN keyword selects records that have matching values in
both tables.
Syntax :
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

LEFT JOIN :-
The LEFT JOIN keyword returns all records from the left table
(table1), and the matching records from the right table (table2). The
result is 0 records from the right side, if there is no match.
Syntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
RIGHT JOIN :-

The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1). The
result is 0 records from the left side, if there is no match.
Syntax:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

FULL OUTER JOIN :-

The FULL OUTER JOIN keyword returns all records when there
is a match in left (table1) or right (table2) table records.
Syntax:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
5. Views
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of
a table.

There are two types of views

1. Join View: A join view is a view that has more than one table or view in its from
clause and it does not use any Group by Clause, Rownum, Distinct and set
operation.
2. Inline View: An inline view is a view which is created by replacing a subquery in
the from clause which defines the data source that can be referenced in the main
query. The sub query must be given an alias for efficient working.

Advantages of View:
1. Complexity: Views help to reduce the complexity. Different views can be created
on the same base table for different users.
2. Security: It increases the security by excluding the sensitive information from the
view.
3. Query Simplicity: It helps to simplify commands from the user. A view can draw
data from several different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure
of the database. Views can be used to rename the columns without affecting the
base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets the specified integrity
constraints.
6. Storage Capacity: Views take very little space to store the data.
7. Logical Data Independence: View can make the application and database tables
to a certain extent independent.

Disadvantages of View:
The DML statements which can be performed on a view created using single base table
have certain restrictions are:

1. You cannot INSERT if the base table has any not null column that do not appear in
view.
2. You cannot INSERT or UPDATE if any of the column referenced in the INSERT or
UPDATE contains group functions or columns defined by expression.
3. You can't execute INSERT, UPDATE, DELETE statements on a view if with read only
option is enabled.
4. You can't be created view on temporary tables.
5. You cannot INSERT, UPDATE, DELETE if the view contains group functions GROUP
BY, DISTINCT or a reference to a pseudo column row num.
6. You can't pass parameters to the SQL server views.
7. You can't associate rules and defaults with views.

1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.

Syntax:

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE condition;

2. Creating View from a single table


Query:
CREATE VIEW DetailsView AS
SELECT NAME, ADDRESS
FROM Student_Details
WHERE STU_ID < 4;

Just like table query, we can query the view to view the data.

SELECT * FROM DetailsView;

3. Creating View from multiple tables


View from multiple tables can be created by simply include multiple tables in the
SELECT statement.

Example: A view is created named MarksView from two tables Student_Detail


and Student_Marks.

Query:

CREATE VIEW MarksView AS


SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Mark
WHERE Student_Detail.NAME = Student_Marks.NAME;

To display data of View MarksView:

SELECT * FROM MarksView;

4. Deleting View
A view can be deleted using the Drop View statement.

Syntax:

DROP VIEW view_name;


6. Procedures
SQL is a block-structured language that enables developers to
combine the power of SQL with procedural statements.
A stored procedure in 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

7. Cursors
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.

The two types of Cursor in Structured Query Language:

1. Implicit Cursor

2. Explicit Cursor
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

1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:

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:

OPEN Cursor_Name;
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.
8. Triggers
A Trigger in Structured Query Language is a set of procedural statements which are
executed automatically when there is any response to certain events on the particular
table in the database. Triggers are used to protect the data integrity in the database.

In SQL, this concept is the same as the trigger in real life. For example, when we pull the
gun trigger, the bullet is fired.

The six types of triggers in SQL are

1. AFTER INSERT TRIGGERS

This trigger is invoked after the insertion of data in the table.

2. AFTER UPDATE TRIGGERS

This trigger is invoked in SQL after the modification of the data in the table.

3. AFTER DELETE TRGGERS

This trigger is invoked after deleting the data from the table.

4. BEFORE INSERT TRIGGERS

This trigger is invoked before the inserting the record in the table.

5. BEFORE UPDATE TRIGGERS

This trigger is invoked before the updating the record in the table.

6. BEFORE DELETE TRIGGERS

This trigger is invoked before deleting the record from the table.

Syntax of Trigger in SQL


CREATE TRIGGER Trigger_Name
[ BEFORE | AFTER ] [ Insert | Update | Delete]
ON [Table_Name]
[FOR EACH ROW | FOR EACH COLUMN ]
AS
Set of SQL Statement

Advantages of Triggers in SQL


The main advantages of triggers in Structured Query Language:

1. SQL provides an alternate way for maintaining the data and referential integrity in
the tables.
2. Triggers helps in executing the scheduled tasks because they are called
automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.

Disadvantages of Triggers in SQL


The main disadvantages of triggers in Structured Query Language:

1. They are not compiled.


2. It is not possible to find and debug the errors in triggers.
3. If we use the complex code in the trigger, it makes the application run slower.
4. Trigger increases the high load on the database system.
9. Normalizations
o Normalization is the process of organizing the data in the database.
o Normalization is used to minimize the redundancy from a relation or set of
relations. It is also used to eliminate undesirable characteristics like Insertion,
Update, and Deletion Anomalies.
o Normalization divides the larger table into smaller and links them using
relationships.
o The normal form is used to reduce redundancy from the database table.

Data modification anomalies can be categorized into three types:

o Insertion Anomaly: Insertion Anomaly refers to when one cannot insert a new
tuple into a relationship due to lack of data.
o Deletion Anomaly: The delete anomaly refers to the situation where the deletion
of data results in the unintended loss of some other important data.
o Updatation Anomaly: The update anomaly is when an update of a single data
value requires multiple rows of data to be updated.

Types of Normal Forms:


Normalization works through a series of stages called Normal forms. The normal forms
apply to individual relations. The relation is said to be in particular normal form if it
satisfies constraints.

Following are the various types of Normal forms:


Normal Form Description

1NF A relation is in 1NF if it contains an atomic value.

2NF A relation will be in 2NF if it is in 1NF and all non-key attributes are fully

functional dependent on the primary key.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

BCNF A stronger definition of 3NF is known as Boyce Codd's normal form.

4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has no

multi-valued dependency.

5NF A relation is in 5NF. If it is in 4NF and does not contain any join dependency,

joining should be lossless.


Advantages of Normalization
o Normalization helps to minimize data redundancy.
o Greater overall database organization.
o Data consistency within the database.
o Much more flexible database design.
o Enforces the concept of relational integrity.

Disadvantages of Normalization
o You cannot start building the database before knowing what the user needs.
o The performance degrades when normalizing the relations to higher normal forms,
i.e., 4NF, 5NF.
o It is very time-consuming and difficult to normalize relations of a higher degree.
o Careless decomposition may lead to a bad database design, leading to serious
problems.
10. Checking Normalizations
Data normalization formula is the method of scaling values to bring them to a
common range. It is used to process any data set so that they become comparable to
other data set and can be used by anyone who wants to understand and interpret it.

It is mainly used by professionals working with a huge data volume. The formula
changes the data set, so their variation falls between 0 and 1. Thus, in
the data normalization formula, the highest data point will have a value of one as the
normalized value and the lowest data point will have zero as the normalized value. The
decimal values of other data points will be between zero and one.

The process is also called feature selling and is mainly used in sets in which the two ends
of the two extreme limits are known, and the data is more or less evenly distributed. It is
frequently used by data analysts in modelling or forecasting.

Mathematically, the normalization equation represents as:

x normalized = (x – x minimum) / (x maximum – x minimum)

The equation of calculation of normalization formula can be


derived by using the following simple four steps:

1. Firstly, identify the minimum and maximum values in the data set,
denoted by x(minimum) and x(maximum).

2. Next, calculate the range of the data set by deducting the minimum
value from the maximum value.
Range = x(maximum) – x(minimum)

3. Next, determine how much more in value the variable is to normalize


from the minimum value by deducting the minimum value from the
variable, i.e., x – x(minimum).
4. Finally, the formula for calculating the normalization of the variable x
derives by dividing the expression in Step 3 by the expression in Step
2.

Limitations

• Outlier sensitive – Outliers are data points that differ significantly from the other values.
The formula is outlier sensitive, which can reduce its effectiveness.
• May not suit all data sets – The method may not suit all types of data, like the ones that
are categorical or non-linear in nature.
• Bias – The method can bring in the problem of biasness during the choice of range. If
the range is too wide or too narrow, then the result may be incorrect.
• Interpretation and communication are difficult – Sometime, the performance of the
result of the standard normalization formula may not be straightforward, and it is
further difficult to communicate it to the stakeholders.
INDEX
S_no. TITLE Page no.
Write a SQL Statement to Create a table
1.
Write a SQL Statement for Describing the table.
2.
Write a SQL command for Inserting the values into table

i. To Insert values in selective columns


3.
ii. To insert values of all columns.

Write a SQL Statement to fetch the data from the table.


4.
Write a SQL Statement Sorting the data
5.
Write a SQL Statement to rename the table.
6.
Write a SQL Statement to Delete a particular row
7.
Write a SQL Statement to delete all records from the table.
8.
Write a SQL Statement to drop the table.
9.
Write a SQL statement using Aggregate Functions(MIN, MAX,
10. AVG,SUM,COUNT)

SQL operators
11.
Write a SQL statement using ALTER command with ADD,
12. MODIFYand DELETE keyword.

Integrity Constraints

i. Primary key
13. ii. Unique key

iii. Not Null

Update
14.
Joins
15.
Q-1 Write a SQL Statement to Create a table?

1. Basic CREATE TABLE: To create a table named “Companies” with different columns
(id, name, address, email, and phone), you can use the following SQL statement:

SQL

CREATE TABLE Companies (


id INT,
name VARCHAR(50),
address TEXT,
email VARCHAR(50),
phone VARCHAR(10)
);

This creates an empty table called “Companies” with the specified columns and
1
their data types .
2. CREATE TABLE … AS SELECT: You can create a new table by extracting specific
rows from an existing table based on certain criteria. For example, to create a new
table named “USACustomers” containing data from an existing table “Customers”
where the country is ‘USA’, you can use:

SQL

CREATE TABLE USACustomers AS


SELECT * FROM Customers WHERE country = 'USA';

This will create a new table “USACustomers” with the same structure as the
2
“Customers” table and populate it with relevant data .
3. CREATE TABLE Using Another Existing Table: To duplicate an existing table’s
structure and create a new table, you can use the following:

SQL

CREATE TABLE CustomersBackup AS


SELECT * FROM Customers;

This creates a new table “CustomersBackup” with the same columns as the
2
“Customers” table and copies all the data into it .
4. Create a Table with a Primary Key: To create a table with a primary key, you can
specify the primary key column(s) within the CREATE TABLE statement. For
example:

SQL

CREATE TABLE Companies (


id INT NOT NULL PRIMARY KEY,
name VARCHAR(50),
address TEXT,
email VARCHAR(50),
phone VARCHAR(10)
);

1
This ensures that the “id” column acts as the primary key for the “Companies” table .
5. Define Constraints While Creating a Table: You can add different types of
constraints while creating a table. For instance, the following statement adds the
NOT NULL constraint to some columns:

SQL

CREATE TABLE Companies (


id INT NOT NULL,
name VARCHAR(50) NOT NULL,
address TEXT,
email VARCHAR(50) NOT NULL,
phone VARCHAR(10)
);
1
Here, the “id,” “name,” and “email” columns cannot contain NULL values .

Remember to adjust the column names, data types, and constraints according to your
specific requirements when creating tables in SQL!
Q-2 Write a SQL Statement for Describing the table.?

Certainly! To describe the structure of a table in SQL, you can use


the DESCRIBE or DESC command. These commands provide information about the columns
within the specified table. Let’s illustrate this with an example:

Suppose we have a table named “users” with the following columns:

 id (integer, primary key)


 name (varchar, maximum length 50 characters)
 email (varchar, maximum length 100 characters)
 age (integer)

Here’s how you can create the “users” table and then describe its structure:
SQL
-- Creating the "users" table
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(100),
age INT
);

-- Describing the structure of the "users" table


DESC users;
.
The output of the DESC command will show details about each column:

 Column names
 Data types
 Nullability (whether a column can contain null values)

For instance, if we execute the DESC users; command, we might see something like this:
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(50) | YES | | NULL | |
| email | varchar(100) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
In this example, the “id” column is the primary key (denoted by PRI), and the other columns
can contain null values (denoted by YES). The data types are also specified.
Remember to execute the DESC command within your database system software, as it
won’t run in a regular text editor.
Q-3 Write a SQL command for Inserting the values into table?

Certainly! To insert new records into a table using SQL, you can use the INSERT
INTO statement. Here are some examples:
1. Inserting Specific Values into All Columns: Suppose we have a table named
“Customers” with
columns: CustomerID, CustomerName, ContactName, Address, City, PostalCode, and Country.
We want to add a new customer named “Cardinal” with contact name “Tom B.
Erichsen,” address “Skagen 21,” city “Stavanger,” postal code “4006,” and country
“Norway.” The SQL statement would be:

SQL

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
.

After executing this command, the “Customers” table will look like this:

Table

CustomerID CustomerName ContactName Address

89 White Clover Markets Karl Jablonski 305 - 14th Ave. S. Suite 3B

90 Wilman Kala Matti Karttunen Keskuskatu 45

91 Wolski Zbyszek ul. Filtrowa 68 Walla

92 Cardinal Tom B. Erichsen Skagen 21

2. Inserting Data Only in Specific Columns: If we want to insert data only in specific
columns (e.g., “CustomerName,” “City,” and “Country”), we can omit the other
columns. For example:

SQL

INSERT INTO Customers (CustomerName, City, Country)


VALUES ('Cardinal', 'Stavanger', 'Norway');

The “CustomerID” will still be automatically generated, and the other columns will
1
be set to default values (usually NULL) .
After executing this command, the “Customers” table will look like this:

Table

CustomerID CustomerName ContactName

89 White Clover Markets Karl Jablonski

90 Wilman Kala Matti Karttunen

91 Wolski Zbyszek ul. Filtrowa 68

92 Cardinal null

3. Inserting Multiple Rows in One Statement: You can insert multiple rows at once
using a single INSERT INTO statement. For example:

SQL

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES
('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway'),
('Greasy Burger', 'Per Olsen', 'Gateveien 15', 'Sandnes', '4306', 'Norway');
Q-4 Write a SQL Statement to fetch the data from the table.?

how to retrieve data from a database table using an SQL SELECT statement.
The SELECT statement allows you to fetch specific information from one or more tables.
Here’s the basic syntax:
SQL
SELECT column1, column2, ...
FROM table_name;column1, column2, and so on represent the names of the columns you want
to retrieve data from.

 table_name is the name of the table containing the data.

Now, let’s look at some examples:


1. Selecting Specific Columns: Suppose we have a table called Customers with columns
like CustomerID, FirstName, LastName, Email, Address, City, PostalCode, and Country. To select
only the FirstName and LastName columns from this table, you can use the following
SQL statement:

SQL

SELECT FirstName, LastName


FROM Customers;
This query will return a result set containing only the FirstName and LastName columns.
2. Selecting All Columns: To retrieve all columns from the Customers table, use the
wildcard *:

SQL

SELECT *
FROM Customers;
This query will return a result set containing all columns from the Customers table.
3. Filtering Data Using the WHERE Clause: Suppose we want to retrieve only those
customers who are located in London. We can add a WHERE clause to filter the data:

SQL

SELECT *
FROM Customers
WHERE City = 'London';
This query will return a result set containing all columns from the Customers table
where the value in the City column is equal to ‘London’.
Q-5 Write a SQL Statement Sorting the data?

you can use the ORDER BY clause. This clause allows you to arrange the result set in
either ascending or descending order based on one or more columns. Here’s how you can
use it:
1. Ascending Order (ASC): To sort data in ascending order, specify the column(s) you
want to sort by and use the ASC keyword. For example, if you have a table
called Orders and you want to retrieve all orders sorted by the OrderDate in ascending
order:

SQL

SELECT *
FROM Orders
ORDER BY OrderDate ASC;
This query will return the orders sorted from the earliest to the latest OrderDate.
2. Descending Order (DESC): To sort data in descending order, use the DESC keyword.
For instance, if you want to retrieve all orders sorted by the TotalAmount in
descending order:

SQL

SELECT *
FROM Orders
ORDER BY TotalAmount DESC;
This query will return the orders sorted from the highest TotalAmount to the lowest.
Q-6 Write a SQL Statement to rename the table.?

To rename a table in SQL, you use the ALTER TABLE statement followed by the RENAME TO clause.
Here's the basic syntax:

Let's say you have a table named students and you want to rename it to class_members. You can
use the following SQL statement:
Q-7 Write a SQL Statement to Delete a particular row?

To delete a particular row from a table in SQL, you use the DELETE FROM statement along with a
WHERE clause to specify the condition that identifies the row(s) you want to delete. Here's the
basic syntax:
Q-8 Write a SQL Statement to delete all records from the table.?
Q-9Write a SQL Statement to drop the table.?
Q-10 Write a SQL statement using Aggregate Functions(MIN, MAX, AVG,
SUM,COUNT)?

CREATE TABLE sales (


product_id INT,
product_name VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);

INSERT INTO sales (product_id, product_name, quantity, price) VALUES


(1, 'Product A', 10, 100.00),
(2, 'Product B', 15, 150.00),
(3, 'Product C', 20, 200.00),
(4, 'Product D', 5, 50.00);
Q-11 SQL operators?
Q-12 Write a SQL statement using ALTER command with ADD, MODIFY
and DELETE keyword.

the ALTER TABLE statement in SQL to add, modify, and delete columns in an existing table. I’ll
provide examples for each operation along with the expected output.
1. Adding a Column: To add a new column to an existing table, you can use the ALTER
TABLE ... ADD statement. Let’s say we have a table called Students, and we want to add
an Email column of type varchar(255):

SQL

ALTER TABLE Students


ADD Email varchar(255);
After running this query, the Students table will have an additional Email column.

Output (Sample Data):

Table

ROLL_NO NAME AGE

1 Ram 20

2 Abhi 22

3 Rahul 21

4 Tanu 19

2. Modifying a Column: To modify an existing column (e.g., changing its data type),
you can use the ALTER TABLE ... MODIFY statement. Let’s say we want to reduce the
maximum size of the COURSE column from varchar(40) to varchar(20):

SQL

ALTER TABLE Students


After running this query, the COURSE column will now allow a maximum of 20
characters.
3. Deleting a Column: To remove a column from a table, use the ALTER TABLE ... DROP
COLUMN statement. Let’s drop the COURSE column from the Students table:

SQL

ALTER TABLE Students


DROP COLUMN COURSE;
Output (Sample Data after Dropping COURSE column):

Table

ROLL_NO NAME

1 Ram

2 Abhi

3 Rahul

4 Tanu

Remember to replace Students, Email, COURSE, and other column names with your actual
table and column names.

13. Integrity Constraints


i. Primary key
ii. Unique key
iii. Not Null
Q-14 Update?
Database Management System (DBMS), the UPDATE statement is used to modify existing
records in a table. It allows you to change the values of specific columns based on certain
conditions. Let’s explore how the OUTPUT clause can be used with an UPDATE statement
and what it provides:
1. The OUTPUT Clause for UPDATE Statements:

o The OUTPUT clause was introduced in SQL Server 2005 and is available in
later versions as well.
o When you use an UPDATE statement with an OUTPUT clause, it returns
information about the rows affected by the update operation.
o The OUTPUT clause provides access to two virtual tables:
 INSERTED: Contains the new rows resulting from the update (values
after the update).
 DELETED: Contains the old copy of the rows (values before the
update).
o Both these tables are accessible simultaneously during the execution of
the UPDATE statement.
o Common use cases for the OUTPUT clause include auditing, logging, and
confirmation messages.
o You can even insert the results from the OUTPUT clause into a separate table.
o Example: Suppose we have a table called Department_SRC with
columns: DepartmentID, Name, GroupName, and ModifiedDate. Let’s say
we want to update a row in this table and capture the updated values:

SQL

-- Sample table creation


CREATE TABLE [dbo].[Department_SRC] (
[DepartmentID] [smallint] IDENTITY(1,1) NOT NULL,
[Name] varchar(50) NOT NULL,
[GroupName] varchar(50) NOT NULL,
[ModifiedDate] [datetime] NOT NULL
);

-- Insert a sample record


INSERT INTO [dbo].[Department_SRC] ([Name], [GroupName],
[ModifiedDate])
VALUES ('Engineering', 'Research and Development', GETDATE());

-- Update the record and capture the results


DECLARE @UpdatedRows TABLE (
[DepartmentID] smallint,
[Name] varchar(50),
[GroupName] varchar(50),
[ModifiedDate] datetime
);

UPDATE [dbo].[Department_SRC]
SET [Name] = 'IT Department'
OUTPUT INSERTED.DepartmentID, INSERTED.Name, INSERTED.GroupName,
INSERTED.ModifiedDate
INTO @UpdatedRows
WHERE [DepartmentID] = 1;

-- Display the updated values


SELECT * FROM @UpdatedRows;

The above query updates the Name column for the department
with DepartmentID = 1 and captures the updated values in
the @UpdatedRows table variable.

2. Viewing Update Values:

o Using the OUTPUT clause, you can display the updated values in the output
window.
o Select the column names with the INSERTED prefix or use INSERTED.* to
display all columns from the INSERTED table.
o Additionally, you can display the old data values (before the update) from
the DELETED table.
o Example:

SQL

UPDATE [dbo].[Department_SRC]
SET [GroupName] = 'IT Group'
OUTPUT INSERTED.DepartmentID, INSERTED.Name, DELETED.GroupName
AS OldGroupName
WHERE [DepartmentID] = 1;

The above query updates the GroupName column and displays both the new
and old values.

Remember, the OUTPUT clause allows you to capture and work with the results of the
updated rows, making it a powerful tool for tracking changes and ensuring data integrity!
Q-15 Joins?

Certainly! In a Database Management System (DBMS), joins are used to combine rows
from two or more tables based on related columns. Let’s explore the different types of
joins and their outputs:
1. Inner Join:

o The INNER JOIN keyword selects all rows from both tables as long as the
condition is satisfied.
o It creates a result-set by combining rows from both tables where the
condition matches (i.e., the value of the common field is the same).
o Syntax:

SQL

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
INNER JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (INNER JOIN):

SQL

SELECT StudentCourse.COURSE_ID, Student.NAME, Student.AGE


FROM Student
INNER JOIN StudentCourse ON Student.ROLL_NO =
StudentCourse.ROLL_NO;

Output:

Table

COURSE_ID NAME AGE

… … …

2. Left Join (Left Outer Join):

o Returns all rows from the left table and matches rows from the right table.
o If there’s no matching row on the right side, the result-set contains null.
o Syntax:

SQL

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
LEFT JOIN table2 ON table1.matching_column = table2.matching_column;
.

o Example Query (LEFT JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

Table

NAME COURSE_ID

… …

3. Right Join (Right Outer Join):

o Similar to LEFT JOIN but returns all rows from the right table.
o Matches rows from the left table.
o For unmatched rows on the left side, the result-set contains null.
o Syntax:

SQL

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
RIGHT JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (RIGHT JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
RIGHT JOIN StudentCourse ON StudentCourse.ROLL_NO =
Student.ROLL_NO;

Output:

Table
NAME COURSE_ID

… …

4. Full Join (Full Outer Join):

o Combines results of both LEFT JOIN and RIGHT JOIN.


o Contains all rows from both tables.
o For unmatched rows, the result-set contains NULL values.
o Syntax:

SQL

SELECT table1.column1, table1.column2, table2.column1, ...


FROM table1
FULL JOIN table2 ON table1.matching_column = table2.matching_column;

o Example Query (FULL JOIN):

SQL

SELECT Student.NAME, StudentCourse.COURSE_ID


FROM Student
FULL JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;

Output:

Table

NAME COURSE_ID

… …

📊
Remember that these joins allow you to retrieve data from multiple tables, enhancing the
power of your database queries!

You might also like