Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
293 views

Dbms Lab File

The document provides instructions on how to install MySQL and verify the installation. It also provides examples of basic MySQL statements including: 1. Creating a table with columns, data types, primary key, default values and specifying the engine. 2. Inserting data into a table with an insert statement and updating data with an insert statement using the ON DUPLICATE KEY clause. 3. Performing different types of joins between two tables to retrieve data including inner, left and right joins. 4. Adding, dropping and altering constraints like primary keys on tables.

Uploaded by

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

Dbms Lab File

The document provides instructions on how to install MySQL and verify the installation. It also provides examples of basic MySQL statements including: 1. Creating a table with columns, data types, primary key, default values and specifying the engine. 2. Inserting data into a table with an insert statement and updating data with an insert statement using the ON DUPLICATE KEY clause. 3. Performing different types of joins between two tables to retrieve data including inner, left and right joins. 4. Adding, dropping and altering constraints like primary keys on tables.

Uploaded by

Saksham Saxena
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Affiliated to Dr. A.P.J.

Abdul Kalam Technical University,


Uttar Pradesh, Lucknow

Department of Computer Science & Engineering

Practical Lab File


Session: 2022-23
Course: B. Tech.
Year: 3rd Year
Branch: CSE
Subject: DBMS LAB
Subject Code: KCS-551
Name: SAKSHAM SAXENA
Roll No.: 2002220100140
Section: C
Name of Instructor: Dr. VRINDA SACHDEVA
LAB FILE INDEX
S. No. Topic Date Sign
1 MYSQL Installation

2 Basic MYSQL statements

3 Creating and managing tables/ Restricting and sorting


data.
4 Working with DDL, DML, DCL and Key Constraints.

5 Working with Queries and Nested QUERIES.

6 Working with Queries USING Aggregate Operators &


views.
7 Displaying data from multiple tables.

8 Creating view of a table in MYSQL.

9 Creating cursor in MYSQL.


1. MYSQL INSTALLATION
How to install MySQL
MySQL is one of the most popular relational database management software that is widely used in
today's industry. It provides multi-user access support with various storage engines. It is backed by
Oracle Company. In this section, we are going to learn how we can download and install MySQL for
beginners.

Prerequisites

The following requirements should be available in your system to work with MySQL :
o MySQL Setup Software o Microsoft .NET Framework 4.5.2
o Microsoft Visual C++ Redistributable for Visual Studio 2019 o RAM 4 GB (6 GB
recommended)
Download MySQL
Follow these steps:
Step 1: Go to the official website

of MySQL and download the community server edition software. Here, you will see the option to
choose the Operating System, such as Windows.

Step 2: Next, there are two options available to download the setup. Choose the version number for
the MySQL community server, which you want. If you have good internet connectivity, then choose
the mysql-installer-web-community. Otherwise, choose the other one.

Installing MySQL on Windows

Step 1: After downloading the setup, unzip it anywhere and double click the MSI installer .exe file.
It will give the following screen:
Step 2: In the next wizard, choose the Setup Type. There are several types available, and you need
to choose the appropriate option to install MySQL product and features

. Here, we are going to select the Full option and click on the Next button.

This option will install the following things: MySQL Server, MySQL Shell, MySQL
Router, MySQL Workbench
, MySQL Connectors, documentation, samples and examples, and many more.

Step 3: Once we click on the Next button, it may give information about some features that may fail
to install on your system due to a lack of requirements. We can resolve them by clicking on the
Execute button that will install all requirements automatically or can skip them. Now, click on the
Next button.
Step 4: In the next wizard, we will see a dialog box that asks for our confirmation of a few products
not getting installed. Here, we have to click on the Yes button.

After clicking on the Yes button, we will see the list of the products which are going to be installed.
So, if we need all products, click on the Execute button.

Step 5: Once we click on the Execute button, it will download and install all the products. After
completing the installation, click on the Next button.
Step 6: In the next wizard, we need to configure the MySQL Server and Router. Here, I am not going
to configure the Router because there is no need to use it with MySQL. We are going to show you
how to configure the server only. Now, click on the Next button.

Step 7: As soon as you will click on the Next button, you can see the screen below. Here, we have to
configure the MySQL Server. Now, choose the Standalone MySQL Server/Classic MySQL
Replication option and click on Next. Here, you can also choose the InnoDB Cluster based on your
needs.
Step 8: In the next screen, the system will ask you to choose the Config Type and other connectivity
options. Here, we are going to select the Config Type as 'Development Machine' and Connectivity
as TCP/IP, and Port Number is 3306, then click on Next.

Step 9: Now, select the Authentication Method and click on Next. Here, I am going to select the first
option.
Step 10: The next screen will ask you to mention the MySQL Root Password. After filling the
password details, click on the Next button.

Step 11: The next screen will ask you to configure the Windows Service to start the server. Keep the
default setup and click on the Next button.
Step 12: In the next wizard, the system will ask you to apply the Server Configuration. If you agree
with this configuration, click on the Execute button.

Step 13: Once the configuration has completed, you will get the screen below. Now, click on the
Finish button to continue.
Step 14: In the next screen, you can see that the Product Configuration is completed. Keep the default
setting and click on the Next-> Finish button to complete the MySQL package installation.

Step 15: In the next wizard, we can choose to configure the Router. So click on Next>Finish and then
click the Next button.
Step 16: In the next wizard, we will see the Connect to Server option. Here, we have to mention the
root password, which we had set in the previous steps.

In this screen, it is also required to check about the connection is successful or not by clicking on the
Check button. If the connection is successful, click on the Execute button. Now, the configuration is
complete, click on Next.

Step 17: In the next wizard, select the applied configurations and click on the Execute button.
Step 18: After completing the above step, we will get the following screen. Here, click on the Finish
button.

Step 19: Now, the MySQL installation is complete. Click on the Finish button.
Verify MySQL installation

Once MySQL has been successfully installed, the base tables have been initialized, and the server has
been started, you can verify its working via some simple tests.

Open your MySQL Command Line Client; it should have appeared with a mysql> prompt. If you
have set any password, write your password here. Now, you are connected to the MySQL server, and
you can execute all the SQL command at mysql> prompt as follows:

For example: Check the already created databases with show databases command:
2. BASIC MYSQL STATEMENTS
1. Create Table

You would not use the create table query every time the script executes in normal scenarios. However, when you start
building an application, you need to create database tables. To do so with a primary key, you can use the following
query.

CREATE TABLE 'emp' (


'id' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
'name' VARCHAR(45) NOT NULL,
'lastname' VARCHAR(45),
'dept' VARCHAR(45) DEFAULT 'sales',
PRIMARY KEY ('id')
)
ENGINE = InnoDB;

The above query creates a table "emp" in the selected database. We will have an "id" column as auto increment and
with a PRIMARY KEY constraint, which ensures an incremented integer value is added every time a new row is
inserted; the constraint checks for non-duplicate value. The column "dept" is populated by default values ("sales" if
no value is supplied). You can specify the "Engine" to be used while creating the table. Otherwise, the default engine
will be used. We used "InnoDB" here because it allows FOREIGN KEY and transactions.

2. Insert Query

Now that you have a table in your database, let us see how you can insert values into that table. You might have used
insert query many times, but have you used an insert query that not only inserts data but can also updates data if need
be? This is achieved by using the keyword "on DUPLICATE KEY." Here is an example:

Simple insert query


insert into emp (name,lastname,dept) values('new name','new last name','Accounts');

Insert and Update query insert into emp (id,name,lastname,dept) values('key that already exists', 'new
name','new last name','Accounts') on duplicate KEY UPDATE name='default name', lastname='default
last name';

In the above query, if the value of "id" passed already exists, then we can update the value of the row instead of
inserting a new row. This is more useful when you need to check columns other than auto-incremented ones.

3. JOINS

Joins are supposed to be complicated because there is so much variety in them. Joins are known by different names in
different databases: self join, outer join, inner join, natural join, and so many others. We will use a join between two
tables, which is generally used to pull data.

Let us assume we have another table called "departments", which has a list of all the departments. If you want to pull
employee data including departments, the query would be:

Regular Join select emp.name,department.name from emp join department on emp.dept =


department.name

Left Join select emp.name,department.name from emp left join department on emp.dept = department.name

Right Join select emp.name,department.name from emp right join department on emp.dept = department.name
The regular join will get all the records that match the condition in both tables. The left join will
match records that match the condition as above, but it will also get all the unmatched records from
the left table. On the other hand, the right join will get all the unmatched records from the right
table.

4. Create and Drop Constraints

Often times you need to edit/add/delete constraints applied on a table. You can do so using the
following queries:

Add a primary key:


ALTER TABLE 'TABLE_NAME' DROP PRIMARY KEY, ADD PRIMARY KEY
('COLUMN_NAME');
Drop a Primary key:
ALTER TABLE 'TABLE_NAME' DROP PRIMARY KEY;

While adding a primary key, we first drop the already added keys and then add the key to a new
column. Otherwise it won't allow you to add the key.

5. Order By, Having Clauses

Order by is used to arrange data by a specific column and then having is used to filter that result
set. These are really useful when you need some specific information from a large database.

Select * from TABLE_NAME group_by dept having salary > 10000;

In the above query the result set would contain data organized by departments and those who have
salaries greater than $10,000. It's worth noting that when we use the "having" clause without "order
by" it works more like the "where" clause.

6. Adding Indexing and Search Queries

Creating indexes for a column undoubtedly increases incoming queries to the database, and indexes
are created on a column basis. For example, in our sample table "emp", if most of the queries fetch
data using the column id, then it would be a wise decision to create an index for the id column.

Upon creating indexes, MySQL will first search for ID in the created index and if none is found it
will run the query on the table level. So, that speeds up the process if indexes are created wisely.
To create an Index, the following query is used.

Create index at time of creating table


CREATE TABLE 'emp' (
Name varchar(45),
'id' INT, INDEX(ID)
)
Create Index for an existing table
Create Index id_index on emp(ID);
7. Aggregate Function Queries

Aggregate functions are used to perform mathematical operations on the data retrieved from the
database. These types of functions include sum, count, etc. For example, if you want to calculate
the number of employees working in a particular department, then you can do so with the help of
an aggregate function as follows:

select distinct name,count(dept) as cnt from emp group by dept order by cnt DESC;

The above query will return the name of the employee and count in the department, and it is then
arranged in descending order of the count returned.

7. Alter and Update Columns of a Table

Tables are created and then edited quite often. In the following few lines we will see how to
add/change columns of an existing table.

Add a column
Alter table 'emp' add column salary varchar(45);
Edit a column

Salary should be in integer instead of having varchar, so let's change its datatype to int. Note that
there may be loss of data if there is a compatibility issue.

Alter table 'emp' modify column salary int(10);


Rename a column Alter table 'emp' change salary salary2
varchar(45);
Drop a column
Alter table 'emp' drop column salary;

8. Create a New Table with Non-Duplicate Values

Suppose you have thousands of records in your database table and when you started it the data
wasn't entered correctly and contains repetitions. Now you plan to clean up all the junk and create
a new table. Let's see how we do it.

create table 'emp2' as select * from emp where 1 group by 'lastname';

So it will create a new table "emp2" with only the employees having unique "last names". You can
sort your table with a different approach.

9. Creating Dump of Your Database and Optimizing the Table


There may be times when your application needs to schedule backups and send them over email or
keep them somewhere safe. You can write a script to do so and set a cron for the same thing. That
will save a lot of work with backing up your work and avoid running into some unanticipated
trouble. Let's see how you can create a backup of your database as well as optimize the table.

mysqldump –h localhost –u username –ppassword databasename > backup_file.sql

This will create a sql dump file, which can be then imported again to restore the database at some
level.

10. Optimizing a Table

It's pretty straightforward to optimize a table in MySQL, as the name indicates:

Optimize table TABLE_NAME


3. CREATING AND MANAGING TABLES/
RESTRICTING AND SORTING DATA.
The essential capabilities of SELECT statement are Selection, Projection and Joining. Displaying
specific columns from a table is known as a project operation. We will now focus on displaying
specific rows of output. This is known as a select operation. Specific rows can be selected by adding
a WHERE clause to a SELECT query. As a matter of fact, the WHERE clause appears just after the
FROM clause in SELECT query hierarchy. The sequence has to be maintained in all scenarios. If
violated, Oracle raises an exception.

Syntax:
SELECT *|{[DISTINCT] column| expression [alias],..}
FROM table
[WHERE condition(s)]

In the syntax,
• WHERE clause is the keyword
• [condition] contains column names, expressions, constants, literals and a comparison operator.
Suppose that your manager is working on the quarterly budget for your organization. As part of this
activity, it is necessary to produce a listing of each employee's essential details, but only for
employees that are paid at least $25,000 annually. The SQL query below accomplishes this task.
Note the use of the WHERE clause shown in bold text.
SELECT Employee_ID, Last_Name, First_Name, Salary
FROM employees
WHERE Salary >= 25000;

EMPLOYEE_ID LAST_NAME FIRST_NAME SALARY


---------- --------------- --------------- -----------
88303 Jones Quincey $30,550.00
88404 Barlow William $27,500.00
88505 Smith Susan $32,500.00

3 rows selected

Points to be noted -
• A SELECT clause can contain only one WHERE clause. However, multiple filter conditions can be
appended to WHERE clause using AND or OR operator.
• The columns, literals or expressions in a predicate clause must be of similar or interconvertible data
types.
• Column alias cannot be used in the WHERE clause.
• Character literals must be enclosed within single quotation marks and are case sensitive.
• Date literals must be enclosed within single quotation marks and are format sensitive. Default format
is DD-MON-RR.

Comparison Operators
Comparison operators are used in predicates to compare one term or operand with another term.
SQL offers comprehensive set of equality, inequality and miscellaneous operators. They can be used
depending on the data and filter condition logic in the SELECT query. When you use comparison
operators in a WHERE clause, the arguments (objects or values you are comparing) on both sides
of the operator must be either a column name, or a specific value. If a specific value is used, then
the value must be either a numeric value or a literal string. If the value is a character string or date,
you must enter the value within single quotation marks
(' ').
Oracle has nine comparison operators to be used in equality or inequality conditions.
Operator Meaning
= equal to
< less than
> greater than
>= greater than or equal to
<= less than or equal to
!= not equal to
<> not equal to

Other Oracle operators are BETWEEN..AND, IN, LIKE, and IS NULL.

The BETWEEN Operator


The BETWEEN operator can be used to compare a column value within a definite range. The
specified range must have a lower and upper limit where both are inclusive during comparison. Its
use is similar to composite inequality operator (<= and >=). It can be used with numeric, character
and date type values.
For example, the WHERE condition SALARY BETWEEN 1500 AND 2500 in a SELECT query
will list those employees whose salary is between 1500 and 2500.

The IN Operator
The IN operator is used to test a column value in a given set of value. If the column can be equated
to any of the values from the given set, the condition is validated. The condition defined using the
IN operator is also known as the membership condition.
For example, the WHERE condition SALARY IN (1500, 3000, 2500) in a SELECT query will
restrict the rows where salary is either of 1500, 3000 or 2500.

The LIKE Operator


The LIKE operator is used for pattern matching and wildcard searches in a SELECT query. If a
portion of the column value is unknown, wildcard can be used to substitute the unknown part. It
uses wildcard operators to build up the search string, thus search is known as Wildcard search. These
two operators are Percentile ('%') and Underscore ('_'). Underscore ('_') substitutes a single character
while percentile ('%') replaces more than one characters. They can be used in combination as well.
For example, the below SELECT query lists the first names of those employees whose last name
starts with 'SA'.
SELECT first_name
FROM employees
WHERE last_name LIKE 'SA%';

IS (NOT) NULL Conditions


To be noted, NULL values cannot be tested using equality operator. It is because NULL values are
unknown and unassigned while equality operator tests for a definite value. The IS NULL operator
serves as equality operator to check NULL values of a column.
For example, the WHERE condition COMMISSION_PCT IS NULL in a SELECT query will list
employees who don't have commission percentage.

Logical Operators
Multiple filter conditions can be added to the WHERE clause predicate. More than one condition
can be combined together using logical operators AND, OR and NOT.
• AND: joins two or more conditions, and returns results only when all of the conditions are true. •
OR: joins two or more conditions, and it returns results when any of the conditions are true.
• NOT: negates the expression that follows it.
The AND operator links two or more conditions in a WHERE clause and returns TRUE only if all
the conditions are true. Suppose that a manager needs a list of female employees. Further, the list
should only include employees with last names that begin with the letter "E" or that come later in
the alphabet. Additionally, the result table should be sorted by employee last name. There are two
simple conditions to be met. The WHERE clause may be written as: WHERE Gender = 'F' AND
last_name > 'E'.
SELECT last_name "Last Name", first_name "First Name", Gender
"Gender"
FROM employees
WHERE Gender = 'F' AND last_name > 'E' ORDER BY last_name;

The OR operator links more than one condition in a WHERE clause and returns TRUE if either of
the condition returns true. Suppose that your organizational manager's requirements change a bit.
Another employee listing is needed, but in this listing the employees should: (1) be female or, (2)
have a last name that begins with the letter "T" or a letter that comes later in the alphabet. The result
table should be sorted by employee last name. In this situation either of the two conditions can be
met in order to satisfy the query. Female employees should be listed along with employees having
a name that satisfies the second condition.
The NOT operator is used to negate an expression or conition.

The ORDER BY Clause


When you display only a few rows of data, it may be unnecessary to sort the output; however, when
you display numerous rows, managers may be aided in decision making by having the information
sorted. Output from a SELECT statement can be sorted by using the optional ORDER BY clause.
When you use the ORDER BY clause, the column name on which you are ordering must also be a
column name that is specified in the SELECT clause.
The below SQL query uses an ORDER BY clause to sort the result table by the last_name column
in ascending order. Ascending order is the default sort order.
SELECT last_name, first_name
FROM employees
WHERE last_name >= 'J'
ORDER BY last_name;

last_name first_name --------------- ---------------


Jones Quincey
Klepper Robert Quattromani Toni
Schultheis Robert

Sorting can be based on numeric and date values also. Sorting can also be done based on multiple
columns.
By default, the ORDER BY clause will sort output rows in the result table in ascending order. We
can use the keyword DESC (short for descending) to enable descending sort. The alternative default
is ASC which sorts in ascending order, but the ASC keyword is rarely used since it is the default.
When the ASC or DESC optional keyword is used, it must follow the column name on which you
are sorting in the WHERE clause.
Positional Sorting - Numeric position of the column in the selected column list can be given in
ORDER BY clause, instead of column name. It is mainly used in UNION queries (discussed later).
The Query orders the result set by salary since it appears 2nd in the column list.
SELECT first_name, salary
FROM employees ORDER BY 2;

Substitution Variables
When a SQL query has to be executed more than once for the different set of inputs, substitution
variables can be used. Substitution variables can be used to prompt for user inputs before the query
execution. They are widely used in query based report generation which takes data range from the
users as input for the conditional filtering and data display. Substitution variables are prefixed by a
singleampersand (&) symbol to temporarily store values. For example,
SELECT EMPLOYEE_ID, LAST_NAME, SALARY
FROM employees
WHERE LAST_NAME = &last_name OR EMPLOYEE_ID = &EMPNO;

When the above SELECT query is executed, oracle identifies the '&' as substitution variable. It
prompts user to enter value for 'last_name' and 'EMPNO' as below.
Enter value for last_name: Enter value for empno:

Once the user provides inputs to both the variables, values are substituted, query is verified and
executed.
Points to be noted -

• If the variable is meant to substitute a character or date value, the literal needs to be enclosed in
single quotes. A useful technique is to enclose the ampersand substitution variable in single quotes
when dealing with character and date values.
• Both SQL Developer and SQL* Plus support the substitution variables and the
DEFINE/UNDEFINE commands. Though SQL Developer or SQL* Plus does not support
validation checks (except for data type) on user input.
• You can use the substitution variables not only in the WHERE clause of a SQL statement, but also
as substitution for column names, expressions, or text.

Using the Double-Ampersand Substitution Variable


When the same substitution variable is used at more than one place, then to avoid re-entering the
same data again, we use double ampersand substitution. In such cases, value of the substitution
variable, once entered, would be substituted at all instants of usage.
SELECT first_name, HIRE_DATE, SEPARATION_DATE
FROM employees
WHERE HIRE_DATE LIKE '%&DT%' AND SEPARATION_DATE '%&&DT%'

Note that the same value of &DT is substituted twice in the above query. So, its value once given
by the user will be substituted at two places.

The DEFINE and VERIFY Commands


Setting the definition of variables in a session is set by DEFINE feature of SQL* Plus. The variables
can be defined in the session, so as to avoid halt during query execution. Oracle reads the same
variable whenever encountered in an SQL query. It is in ON state by default. With the help of
DEFINE clause, one can declare a variable in command line before query execution as DEFINE
variable=value;.
Verify command verifies the above substitution showing as OLD and NEW statement. It is OFF by
default and can be set to ON using SET command.
SQL> SET DEFINE ON
SQL> SET VERIFY ON
SQL> DEFINE NAME = MARTIN'
SQL> SELECT first_name, SALARY
FROM employees
WHERE first_name = '&NAME';
OLD 1: select first_name, sal from employee where first_name =
'&first_name'
new 1: select first_name, sal from employee where first_name =
'MARTIN'

first_name SALARY ------- -------


MARTIN 5000
4. WORKING WITH DDL, DML, DCL AND KEY
CONSTRAINTS

Data Definition Language is used to define the database structure or schema. DDL is also used to
specify additional properties of the data. The storage structure and access methods used by the
database system by a set of statements in a special type of DDL called a data storage and definition
language. These statements define the implementation details of the database schema, which are
usually hidden from the users. The data values stored in the database must satisfy certain
consistency constraints.
For example, suppose the university requires that the account balance of a department must never
be negative. The DDL provides facilities to specify such constraints. The database system checks
these constraints every time the database is updated. In general, a constraint can be an arbitrary
predicate pertaining to the database. However, arbitrary predicates may be costly to the test. Thus,
the database system implements integrity constraints that can be tested with minimal overhead.
Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course by
GeeksforGeeks.
1. Domain Constraints : A domain of possible values must be associated with every attribute (for
example, integer types, character types, date/time types). Declaring an attribute to be of a particular
domain acts as the constraints on the values that it can take.
2. Referential Integrity : There are cases where we wish to ensure that a value appears in one relation
for a given set of attributes also appear in a certain set of attributes in another relation i.e.
Referential Integrity. For example, the department listed for each course must be one that actually
exists.
3. Assertions : An assertion is any condition that the database must always satisfy. Domain
constraints and Integrity constraints are special form of assertions.
4. Authorization : We may want to differentiate among the users as far as the type of access they are
permitted on various data values in database. These differentiation are expressed in terms of
Authorization. The most common being : read authorization – which allows reading but not
modification of data ; insert authorization – which allow insertion of new data but not modification
of existing data update authorization – which allows modification, but not deletion.
Some Commands:
CREATE : to create objects in database
ALTER : alters the structure of database
DROP : delete objects from database
RENAME : rename an objects
Following SQL DDL-statement defines the department table :
create table department (dept_name
char(20), building char(15), budget
numeric(12,2));
Execution of the above DDL statement creates the department table with three columns –
dept_name, building, and budget; each of which has a specific datatype associated with it.
DML (Data Manipulation Language) :
DML statements are used for managing data with in schema objects.
DML are of two types –
1. Procedural DMLs : require a user to specify what data are needed and how to get those data.
2. Declerative DMLs (also referred as Non-procedural DMLs) : require a user to specify what data
are needed without specifying how to get those data.
Declarative DMLs are usually easier to learn and use than procedural DMLs. However, since a
user does not have to specify how to get the data, the database system has to figure out an efficient
means of accessing data.
Some Commands :
SELECT: retrieve data from the database
INSERT: insert data into a table
UPDATE: update existing data within a table
DELETE: deletes all records from a table, space for the records remain
Example of SQL query that finds the names of all instructors in the History department :
select instructor.name from instructor
where instructor.dept_name = 'History';
The query specifies that those rows from the table instructor where the dept_name is History must
be retrieved and the name attributes of these rows must be displayed.
TCL (Transaction Control Language) :
Transaction Control Language commands are used to manage transactions in the database. These
are used to manage the changes made by DML-statements. It also allows statements to be grouped
together into logical transactions.
Examples of TCL commands –
COMMIT: Commit command is used to permanently save any transaction into the
database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction so that you
can rollback to that point whenever necessary.
DCL (Data Control Language) :
A Data Control Language is a syntax similar to a computer programming language used to control
access to data stored in a database (Authorization). In particular, it is a component of Structured
Query Language (SQL).
Examples of DCL commands :
GRANT: allow specified users to perform specified tasks.
REVOKE: cancel previously granted or denied permissions.
The operations for which privileges may be granted to or revoked from a user or role apply to both
the Data definition language (DDL) and the Data manipulation language (DML), and may include
CONNECT, SELECT, INSERT, UPDATE, DELETE, EXECUTE and USAGE.
In the Oracle database, executing a DCL command issues an implicit commit. Hence, you cannot
roll back the command.
5. WORKING WITH QUERIES AND NESTED
QUERIES
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded
within the WHERE clause.
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.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
There are a few rules that subqueries must follow − • Subqueries must
be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.
• An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER
BY in a subquery.
• Subqueries that return more than one row can only be used with multiple value operators such as
the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY,
CLOB, or NCLOB.
• A subquery cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can
be used within the subquery.

Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows

SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

Example

Consider the CUSTOMERS table having the following records −


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now, let us check the following subquery with a SELECT statement.


SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS WHERE SALARY > 4500) ;

This would produce the following result.


+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+

Subqueries with the INSERT Statement


Subqueries also can be used with INSERT statements. The INSERT statement uses the data
returned from the subquery to insert into another table. The selected data in the subquery can be
modified with any of the character, date or number functions.
The basic syntax is as follows.
INSERT INTO table_name [ (column1 [, column2 ]) ]
SELECT [ *|column1 [, column2 ]
FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR ] Example

Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following
syntax.
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

Subqueries with the UPDATE Statement


The subquery can be used in conjunction with the UPDATE statement. Either single or multiple
columns in a table can be updated when using a subquery with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME) [
WHERE) ]

Example

Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.


The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27.
SQL> UPDATE CUSTOMERS
SET SALARY = SALARY * 0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

This would impact two rows and finally CUSTOMERS table would have the following records.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 125.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 2125.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Subqueries with the DELETE Statement


The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]

Example

Assuming, we have a CUSTOMERS_BKP table available which is a backup of the


CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for
all the customers whose AGE is greater than or equal to 27.
SQL> DELETE FROM CUSTOMERS
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=
27 );

This would impact two rows and finally the CUSTOMERS table would have the following records.
+----+----------+-----+---------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+---------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+---------+----------+
6. WORKING WITH QUERIES USING
AGGREGATE OPERATORS & VIEWS
SQL Aggregate Functions
o SQL aggregation function is used to perform the calculations on multiple rows of a single column
of a table. It returns a single value.
o It is also used to summarize the data.

Types of SQL Aggregation Function

1. COUNT FUNCTION

o COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.

Syntax

1. COUNT(*) 2. or 3. COUNT( [ALL|DISTINCT] expression )

Sample table:

PRODUCT_MAST

Example: COUNT() kip A

1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
PRODUCT COMPANY QTY RATE

Item1 Com1 2 10
Item2 Com2 3 25
Item3 Com1 2 30
Item4 Com3 5 10
Item5 Com2 2 20
Item6 Cpm1 3 25
Item7 Com1 5 30
Item8 Com1 3 10
Item9 Com2 2 25
Item10 Com3 4 30

Output:

10

Example: COUNT with WHERE

1. SELECT COUNT(*) 2. FROM PRODUCT_MAST; 3. WHERE RATE>=20;

Output:

Example: COUNT() with DISTINCT

1. SELECT COUNT(DISTINCT COMPANY)


2. FROM PRODUCT_MAST; Output:

Example: COUNT() with GROUP BY

1. SELECT COMPANY, COUNT(*) 2. FROM PRODUCT_MAST 3. GROUP BY COMPANY;


Output:
Com1 5
Com2 3
Com3 2

Example: COUNT() with HAVING


1. SELECT COMPANY, COUNT(*)
2. FROM PRODUCT_MAST 3. GROUP BY COMPANY
4. HAVING COUNT(*)>2; Output:

Com1 5
Com2 3

2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

Syntax

1. SUM() 2. or 3. SUM( [ALL|DISTINCT] expression )


Example: SUM()

1. SELECT SUM(COST)
2. FROM PRODUCT_MAST; Output:

670

Example: SUM() with WHERE

1. SELECT SUM(COST) 2. FROM PRODUCT_MAST


3. WHERE QTY>3; Output:

320

Example: SUM() with GROUP BY

1.. SELECT SUM(COST) 2. FROM PRODUCT_MAST 3. WHERE QTY>3

4. GROUP BY COMPANY; Output:

Com1 150
Com2 170

Example: SUM() with HAVING


1. SELECT COMPANY, SUM(COST) 2. FROM PRODUCT_MAST 3. GROUP BY
COMPANY 4. HAVING SUM(COST)>=170;

Output:
Com1 335
Com3 170

3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function returns
the average of all non-Null values.

Syntax

1. AVG() 2. or
3. AVG( [ALL|DISTINCT] expression ) Example:

1. SELECT AVG(COST)
2. FROM PRODUCT_MAST; Output:

67.00

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines
the largest value of all selected values of a column.

Syntax

1. MAX() 2. or
3. MAX( [ALL|DISTINCT] expression ) Example:

1. SELECT MAX(RATE) 2. FROM PRODUCT_MAST;


30

5. MIN Function
MIN function is used to find the minimum value of a certain column. This function determines the
smallest value of all selected values of a column.

Syntax

1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression ) Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST; Output:

10
7. DISPLAYING DATA FROM MULTIPLE
TABLES.
Displaying Data from Multiple Tables
The related tables of a large database are linked through the use of foreign and primary keys or
what are often referred to as common columns. The ability to join tables will enable you to add
more meaning to the result table that is produced. For 'n' number tables to be joined in a query,
minimum (n-1) join conditions are necessary. Based on the join conditions, Oracle combines the
matching pair of rows and displays the one which satisfies the join condition. Joins are classified
as below
• Natural join (also known as an equijoin or a simple join) - Creates a join by using a commonly
named and defined column.
• Non-equality join - Joins tables when there are no equivalent rows in the tables to be joined-for
example, to match values in one column of a table with a range of values in another table.
• Self-join - Joins a table to itself.
• Outer join - Includes records of a table in output when there's no matching record in the other
table.
• Cartesian join (also known as a Cartesian product or cross join) - Replicates each row from the
first table with every row from the second table.Creates a join between tables by displaying every
possible record combination.

Natural Join
The NATURAL keyword can simplify the syntax of an equijoin.A NATURAL JOIN is possible
whenever two (or more) tables have columns with the same name,and the columns are join
compatible, i.e., the columns have a shared domain of values.The join operation joins rows from
the tables that have equal column values for the same named columns.
Consider the one-to-many relationship between the DEPARTMENTS and EMPLOYEES
tables.Each table has a column named DEPARTMENT_ID.This column is the primary key of the
DEPARTMENTS table and a foreign key of the EMPLOYEES table.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E NATURAL JOIN departments D;

FIRST_NAME DNAME
---------- ------
MILLER DEPT 1
JOHN DEPT 1
MARTIN DEPT 2
EDWIN DEPT 2
The below SELECT query joins the two tables by explicitly specifying the join condition with the
ON keyword.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
ON (E.department_id = D.department_id);

There are some limitations regarding the NATURAL JOIN.You cannot specify a LOB column
with a NATURAL JOIN.Also, columns involved in the join cannot be qualified by a table name
or alias.

USING Clause
Using Natural joins, Oracle implicitly identify columns to form the basis of join. Many situations
require explicit declaration of join conditions. In such cases, we use USING clause to specify the
joining criteria. Since, USING clause joins the tables based on equality of columns, it is also
known as Equijoin. They are also known as Inner joins or simple joins.

Syntax:

SELECT <column list>


FROM TABLE1 JOIN TABLE2 USING (column name)

Consider the below SELECT query, EMPLOYEES table and DEPARTMENTS table are joined
using the common column DEPARTMENT_ID.
SELECT E.first_name NAME,D.department_name DNAME
FROM employees E JOIN departments D
USING (department_id);

Self Join
A SELF-JOIN operation produces a result table when the relationship of interest exists among
rows that are stored within a single table. In other words, when a table is joined to itself, the join
is known as Self Join.
Consider EMPLOYEES table,which contains employee and their reporting managers.To find
manager's name for an employee would require a join on the EMP table itself. This is a typical
candidate for Self Join.
SELECT e1.FirstName Manager,e2.FirstName Employee
FROM employees e1 JOIN employees e2
ON (e1.employee_id = e2.manager_id)
ORDER BY e2.manager_id DESC;

Non Equijoins
A non-equality join is used when the related columns can't be joined with an equal sign-meaning
there are no equivalent rows in the tables to be joined.A non-equality join enables you to store a
range's minimum value in one column of a record and the maximum value in another column. So
instead of finding a column-tocolumn match, you can use a non-equality join to determine whether
the item being shipped falls between minimum and maximum ranges in the columns.If the join
does find a matching range for the item, the corresponding shipping fee can be returned in the
results. As with the traditional method of equality joins, a non-equality join can be performed in a
WHERE clause. In addition, the JOIN keyword can be used with the ON clause to specify relevant
columns for the join.
SELECT E.first_name,
J.job_hisal,
J.job_losal,
E.salary
FROM employees E JOIN job_sal J
ON (E.salary BETWEEN J.job_losal AND J.job_losal);

We can make use all comparison parameter discussed earlier like equality and inequality operators,
BETWEEN, IS NULL, IS NOT NULL, and RELATIONAL.

Outer Joins
An Outer Join is used to identify situations where rows in one table do not match rows in a second
table, even though the two tables are related.
There are three types of outer joins: the LEFT, RIGHT, and FULL OUTER JOIN. They all begin
with an INNER JOIN, and then they add back some of the rows that have been dropped. A LEFT
OUTER JOIN adds back all the rows that are dropped from the first (left) table in the join
condition, and output columns from the second (right) table are set to NULL. A RIGHT OUTER
JOIN adds back all the rows that are dropped from the second (right) table in the join condition,
and output columns from the first (left) table are set to NULL. The FULL OUTER JOIN adds back
all the rows that are dropped from both the tables.

Right Outer Join


A RIGHT OUTER JOIN adds back all the rows that are dropped from the second (right) table in
the join condition, and output columns from the first (left) table are set to NULL. Note the below
query lists the employees and their corresponding departments. Also no employee has been
assigned to department 30.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE E.DEPARTMENT_ID (+) = D.DEPARTMENT_ID;
FIRST_NAME SALARY DEPARTMENT_ID
---------- ---------- ----------
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30
Left Outer Join
A LEFT OUTER JOIN adds back all the rows that are dropped from the first (left) table in the join
condition, and output columns from the second (right) table are set to NULL. The query
demonstrated above can be used to demonstrate left outer join, by exchanging the position of (+)
sign.
SELECT E.first_name, E.salary, D.department_id
FROM employees E, departments D
WHERE D.DEPARTMENT_ID = E.DEPARTMENT_ID (+);

FIRST_NAME SALARY DEPARTMENT_ID


---------- ---------- ----------
JOHN 6000 10
EDWIN 2000 20
MILLER 2500 10
MARTIN 4000 20
30

Full Outer Join


The FULL OUTER JOIN adds back all the rows that are dropped from both the tables. Below
query shows lists the employees and their departments. Note that employee 'MAN' has not been
assigned any department till now (it's NULL) and department 30 is not assigned to any employee.
SELECT nvl (e.first_name,'-') first_name, nvl (to_char
(d.department_id),'-') department_id
FROM employee e FULL OUTER JOIN department d
ON e. depARTMENT_ID = d. depARTMENT_ID;
FIRST_NAME DEPARTMENT_ID
---------- --------------------
MAN -
JOHN 10
EDWIN 20
MILLER 10
MARTIN 20
- 30
6 rows selected.

Cartesian product or Cross join


For two entities A and B, A * B is known as Cartesian product. A Cartesian product consists of all
possible combinations of the rows from each of the tables. Therefore, when a table with 10 rows
is joined with a table with 20 rows, the Cartesian product is 200 rows (10 * 20 = 200).For example,
joining the employee table with eight rows and the department table with three rows will produce
a Cartesian product table of 24 rows (8 * 3 = 24).
Cross join refers to the Cartesian product of two tables. It produces cross product of two tables.
The above query can be written using CROSS JOIN clause.
A Cartesian product result table is normally not very useful. In fact, such a result table can be
terribly misleading. If you execute the below query for the EMPLOYEES and DEPARTMENTS
tables, the result table implies that every employee has a relationship with every department, and
we know that this is simply not the case!
SELECT E.first_name, D.DNAME
FROM employees E,departments D;
Cross join can be written as,

SELECT E.first_name, D.DNAME


FROM employees E CROSS JOIN departments D;
8. CREATING VIEW OF A TABLE IN MYSQL
The CREATE VIEW statement creates a new view in the database. Here is the basic syntax of the
CREATE VIEW statement:
CREATE [OR REPLACE] VIEW [db_name.]view_name [(column_list)]
AS
select -statement ;

Code language: SQL (Structured Query Language) (sql)

In this syntax:

First, specify the name of the view that you want to create after the CREATE VIEW keywords.
The name of the view is unique in a database. Because views and tables in the same database
share the same namespace, the name a view cannot the same as the name of an existing table.

Second, use the OR REPLACE option if you want to replace an existing view if the view already
exists. If the view does not exist, the OR REPLACE has no effect.

Third, specify a list of columns for the view. By default, the columns of the view are derived from
the select list of the SELECT statement. However, you can explicitly specify the column list for
the view by listing them in parentheses following the view name.

Finally, specify a SELECT statement that defines the view. The SELECT statement can query
data from tables or views. MySQL allows you to use the ORDER BY clause in the SELECT
statement but ignores it if you select from the view with a query that has its own ORDER BY
clause.

By default, the CREATE VIEW statement creates a view in the current database. If you want to
explicitly create a view in a given database, you can qualify the view name with the database name.

MySQL CREATE VIEW examples

Let’s take some example of using the CREATE VIEW statement to create new views.

1) Creating a simple view example

Let’s take a look at the orderDetails table from the sample database:
This statement uses the CREATE VIEW statement to create a view that represents total sales per
order.
CREATE VIEW salePerOrder AS
SELECT
orderNumber,
SUM(quantityOrdered * priceEach) total
FROM
orderDetails
GROUP by orderNumber
ORDER BY total DESC;
Code language: SQL (Structured Query Language) (sql)

If you use the SHOW TABLE command to view all tables in the classicmodels database, you will
see the viewsalesPerOrder is showing up in the list.
SHOW TABLES;
Code language: SQL (Structured Query Language) (sql)

This is because the views and tables share the same namespace as mentioned earlier.

To know which object is a view or table, you use the SHOW FULL TABLES command as follows:

SHOW FULL TABLES;


Code language: SQL (Structured Query Language) (sql)

The table_type column in the result set specifies the type of the object: view or table (base table).
If you want to query total sales for each sales order, you just need to execute a simple SELECT
statement against the SalePerOrder view as follows:
SELECT * FROM salePerOrder;
Code language: SQL (Structured Query Language) (sql)

2) Creating a view based on another view example

MySQL allows you to create a view based on another view.


For example, you can create a view called bigSalesOrder based on the salesPerOrder view to show
every sales order whose total is greater than 60,000 as follows:

CREATE VIEW bigSalesOrder AS


SELECT
orderNumber,
ROU ND(total,2) as total
FRO M
salePe rOrder
WHER E
total > 60000 ;
Code language: SQL (Structured Query Language) (sql)
Now, you can query the data from the bigSalesOrder view as follows:
SELECT
orderNumber,
total
FRO M
bigSalesOrder;
Code language: SQL (Structured Query Language) (sql )

3)
Creating a view with join example
The following example uses the CREATE VIEW statement to create a view based on multiple tables.
It uses the INNER JOIN clauses to join tables.
CREATE OR REPLACE VIEW customerOrders AS
SELECT
orderNumber,
customerName ,
SUM(quantityOrdered * priceEach) total
FROM
orderDetails
INNER JOIN orders o USING (orderNumber)
INNER JOIN customers USING (customerNumber)
GROUP BY orderNumber;
Code language: SQL (Structured Query Language) (sql)

This statement selects data from the customerOrders view:


SELECT * FROM customerOrders
ORDER BY total DESC;
Code language: SQL (Structured Query Language) (sql) This picture

shows the partial output:

4) Creating a view with a subquery example

The following example uses the CREATE VIEW statement to create a view whose SELECT
statement uses a subquery. The view contains products whose buy prices are higher than the
average price of all products.
CREATE VIEW aboveAvgProducts AS
SELECT
productCode,
productName ,
buyPrice
FRO M
products
WHER E
buyPrice > (
SELECT
AVG(buyPrice )
FRO M
products )
ORDER BY buyPrice DESC ;
Code language: SQL (Structured Query Language) (sql )

This query data from the aboveAvgProducts is simple as follows:


SELECT * FROM aboveAvgProducts;
Code language: SQL (Structured Query Language) (sql )

5) Creating a view with explicit view columns example


This statement uses the CREATE VIEW statement to create a new view based on the customers and
orders tables with explicit view columns:

CREATE VIEW customerOrderStats (


customerName ,
orderCount
)
AS
SELECT
customerName,
COUNT (orderNumber)
FROM
customers
INNER JOIN

orders USING
(customerNumber)

GROUP BY Structured
customerName;
Code language: SQL ( Query Language) (sql)
This query returns data from the customerOrderStats view:
SELECT
customerName ,
orderCount
FROM
customerOrderStats
ORDER BY
orderCount,
customerName ;
9. CREATING CURSOR IN MYSQL
Working with MySQL cursor

First, declare a cursor by using the DECLARE statement:


DECLARE cursor_name CURSOR FOR SELECT_statement;
Code language: SQL (Structured Query Language) (sql)

The cursor declaration must be after any variable declaration. If you declare a cursor before the
variable declarations, MySQL will issue an error. A cursor must always associate with a SELECT
statement.

Next, open the cursor by using the OPEN statement. The OPEN statement initializes the result set
for the cursor, therefore, you must call the OPEN statement before fetching rows from the result
set.
OPEN cursor_name;
Code language: SQL (Structured Query Language) (sql)

Then, use the FETCH statement to retrieve the next row pointed by the cursor and move the cursor
to the next row in the result set.

FETCH cursor_name INTO variables list;


Code language: SQL (Structured Query Language) (sql)

After that, check if there is any row available before fetching it.

Finally, deactivate the cursor and release the memory associated with it using the CLOSE
statement:

CLOSE cursor_name;
Code language: SQL (Structured Query Language) (sql)

It is a good practice to always close a cursor when it is no longer used.

When working with MySQL cursor, you must also declare a NOT FOUND handler to handle the
situation when the cursor could not find any row.

Because each time you call the FETCH statement, the cursor attempts to read the next row in the
result set. When the cursor reaches the end of the result set, it will not be able to get the data, and
a condition is raised. The handler is used to handle this condition.

To declare a NOT FOUND handler, you use the following syntax:


DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
Code language: SQL (Structured Query Language) (sql)
The finished is a variable to indicate that the cursor has reached the end of the result set. Notice
that the handler declaration must appear after variable and cursor declaration inside the stored
procedures.

The following diagram illustrates how MySQL cursor works.

MySQL Cursor Example

We’ll develop a stored procedure that creates an email list of all employees in the employees
table in the sample database.

First, declare some variables, a cursor for looping over the emails of employees, and a NOT
FOUND handler:
DECLARE finished INTEGER DEFAULT 0;
DECLARE emailAddress varchar(100) DEFAULT "";

-- declare cursor for employee email


DEClARE curEmail
CURSOR FOR
SELECT email FROM employees;

-- declare NOT FOUND handle r


DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
Code language: SQL (Structured Query Language) (sql)

Next, open the cursor by using the OPEN statement:


OPEN curEmail;
Code language: SQL (Structured Query Language) (sql)

Then, iterate the email list, and concatenate all emails where each email is separated by a
semicolon(;):
getEmail: LOOP
FETCH curEmail INTO emailAddress;

IF finished = 1 THEN

LEAVE getEmail;

END IF;

-- build email list

SET emailList =
CONCAT(emailAddress,";",emailList);

END LOOP getEmail; Structured Query Language) (sql)


Code language: SQL (
After that, inside the loop, we used the finished variable to check if there is an email in the list to
terminate the loop.
Finally, close the cursor using the CLOSE statement:
CLOSE email_cursor;
Code language: SQL (Structured Query Language) (sql)

The createEmailList stored procedure is as follows:


DELIMITER $$
CREATE PROCEDURE createEmailList (
INOUT emailList varchar(4000)
)
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE emailAddress varchar(100) DEFAULT "";
-- declare cursor for employee email
DEClARE curEmail
CURSOR FOR
SELECT email FROM employees;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
OPEN curEmail;
getEmail: LOOP
FETCH curEmail INTO emailAddress;
IF finished = 1 THEN
LEAVE getEmail;
END IF;
-- build email list
SET emailList = CONCAT(emailAddress,";",emailList);
END LOOP getEmail;
CLOSE curEmail;
END$$
DELIMITER ;
Code language: SQL (Structured Query Language) (sql)
You can test the createEmailList stored procedure using the following script:
SET @emailList = "";
CALL createEmailList(@emailList);
SELECT @emailList;

You might also like