MySQL Queries
MySQL Queries
In this lesson you will be learn how to use SELECT statement in MySQL and you can also learn 
how to use SELECT statement with WHERE clause. The SELECT statement is used to retrieve 
the records Irom the table. There are some keywords uses in SELECT statement that are 
described in the Iollowing table 
 
Keywords                 Description 
SELECT   SELECT statement is used to retrieve Iields Irom one or more tables.      
FROM  Tables containing  to the Iields. 
WHERE 
The WHERE clause is used to describe the criteria to restrict the records 
retrieved. 
GROUP BY 
The GROUP BY clause is used to determine how the records should be 
grouped.   
HAVING 
HAVING clause used with GROUP BY to deIine the criteria Ior grouped 
records 
ORDER BY   The ORDER BY clause is used to described the criteria Ior ordering the record. 
LIMIT  The LIMIT clause is used to restrict the limit oI number oI records retrieved. 
The simple SELECT statement is used to retrieve the all records Irom table. By the Iollowing 
example you can retrieve the Iull list oI Emp table.  
mysql~ SELECT * FROM Emp; 
II you want to retrieve only some Iields Irom a table, then you have to provide a comma 
separated list oI column names. By the Iollowing example you select Name, City and Age Iields 
Irom the Emp table.  
mysql~ SELECT Name, City, Age 
Irom EMP; 
The WHERE clause is used to limit the number oI records. The comparison operators are used 
with WHERE clause to limit the number oI records. Comparison operator`s list are given below:   
 Operator   Description  
   Equal to  
~ or !  Not equal to  
  Less then 
    Less then or equal to  
~   Greater then  
~    Greater then or equal to  
Like   Used Ior comparing string  
Between   Used Ior checking value between a range. 
IN   Used to check values in a list 
NOT IN   Used to check the value is not in the list.  
 Character - II you are working with Strings, then  character can be used as a wildcard. By 
the Iollowing example you can retrieve the all Iields Irom Emp table where the Designation Iield 
contain the text, 'Manager'. 
mysql~ SELECT * FROM Emp WHERE 
Designation LIKE 'Manager'; 
_ character - The underscore character can be used as a placeholder. By the Iollowing example 
you can selects the all records Irom the table Emp, where the Name starts with R` Iollowed by 
Iour characters. For this we have to use Iour underscores. 
mysql~ SELECT * FROM Emp WHERE 
Name LIKE 'R'; 
BETWEEN Clause - The BETWEEN clause can be used with numbers, dates and text. The 
Iollowing example is used to retrieve all Iields Emp table where the Salary is between 10000 
AND 20000. 
mysql~ SELECT * FROM Emp WHERE Salary 
BETWEEN 10000 AND 20000; 
OR Clause - The OR clause is used to check the values against the range oI values that have 
been speciIied. The Iollowing example retrieves the list oI all records where the Designation is 
either Manager or Assistant in the Emp table. 
mysql~ SELECT * FROM Emp WHERE Designation 
'Manager' OR 'Assistant'; 
IN Clause - The IN clause is used to check the values against to many values that have been 
speciIied in IN clause. The Iollowing example retrieves the list oI all records where the 
Designation is either Manager or Assistant in the Emp table. 
mysql~ SELECT * FROM Emp WHERE 
Designation IN ('Manager', 'Assistant'); 
NOT IN Clause - You can use the NOT modiIier with IN clause Ior checking the values,. Which 
are not within the list. The Iollowing example retrieves the list oI all records where the 
Designation is not equal to Manager or Assistant in the Emp table. 
mysql~ SELECT * FROM Emp WHERE Designation 
NOT IN ('Manager', 'Assistant'); 
The Iollowing list shows you a Aggregate Function that available in MySQL. 
O ' ); 
The AVG( ) Iunction returns the average value in a group oI records. Example oI the 
AVG( ) Iunction:-  
SELECT AVG(ProIit) FROM Income GROUP BY EmpId; 
       
O COUNT ); 
The COUNT( ) Iunction returns the number oI  records in a group oI records. Example oI 
the COUNT( ) Iunction:-  
SELECT COUNT(ProIit) FROM Income GROUP BY EmpId; 
       
O M ); 
 The MAX( ) Iunction return the maximum value in a group oI records. Example oI the 
MAX( ) Iunction:-  
SELECT MAX(ProIit) FROM Income GROUP BY EmpId; 
       
O MIN ); 
The MIN( ) Iunction returns minimum value in a group oI records. Example oI the MIN( 
) Iunction:-   
SELECT MIN(ProIit) FROM Income GROUP BY EmpId; 
      
O SUM ); 
The SUM( ) Iunction return the sum oI the Iield. Example oI the SUM() Iunction :  
SELECT SUM(ProIit) FROM Income GROUP BY EmpId ; 
The H'IN Clause 
As you know the WHERE clause is used to restrict the records in a query. But iI you want to 
restrict the records by using the Aggregate Iunction then you have to use the HAVING clause. 
The HAVING clause restricts the records aIter they have been grouped. The Iollowing example 
shows the list oI all Employees who did proIit over 10000 on average. 
mysql~ SELECT AVG(ProIit) FROM Income GROUP BY 
EmpId HAVING AVG(ProIit) ~ 10000; 
The ORDER BY Clause 
The ORDER BY clause can be used to set the order oI the retrieved records. The Iollowing 
example shows the list oI all employees in the Emp table in alphabetical order. In this clause we 
can use the ASC or DESC modiIiers to set the order oI records in ascending or descending order. 
II any modiIier is not provided then the records are listed in ascending order. 
mysql~ SELECT Name FROM Emp 
ORDER BY Name; 
The LIMIT Clause 
The LIMIT clause can be used to limit the number oI records that have been returned by the 
SELECT statement. You can speciIy the start row, and number oI records retrieved.  
mysql~  SELECT * FROM Emp 
LIMIT 0,10; 
Selecting ll Columns or Specific columns 
In this section you will be learn how to create database and create a speciIic columns in MySQL 
.  
CRETE Statement 
The CREATE statement is used to create the table. 
Example: 
Create the tables: 
  
mysql~ CREATE TABLE Employee ( 
-~ id int unsigned not null autoincrement primary key, 
-~ Iname varchar(20), 
-~ lname varchar(20), 
-~ age int, 
-~ salary int, 
-~ email varchar(60) 
-~ ); 
Query OK, 0 rows aIIected (0.03 sec) 
Insert the Data in the table: 
The INSERT statement is used the load the data in the table. Keyword are used in this statement 
are Iollows : 
INSERT - Insert data into the table 
INTO - SpeciIied the Table name Ior inserting the data 
'LUES - Data Ior the columns in the table. 
mysql~ INSERT INTO Employee (Iname, lName, age, 
salary, email) VALUES ("Deepak", "Kumar", 31, 25000, 
"Deepakhotmail.com"); 
Query OK, 1 row aIIected (0.00 sec) 
MySQL creates the table by the name oI Employee with the column along the Iirst row. II you 
want to only select columns, replace the * with the names oI the columns, separated by commas. 
The select statement Iollow just like the , SELECT * FROM Employee : 
mysql~ SELECT * FROM Employee; 
------------------------------------------------------ 
, id     , Iname     ,   lname   ,   age   ,  salary   ,   email     , 
------------------------------------------------------ 
, 1     , Deepak     ,   kumar    ,   31    ,  25000  ,Dhotmail.com , 
------------------------------------------------------ 
1 row in set (0.00 sec)  
Display the MySQL version 
mysql~ SELECT VERSION(); 
For displaying the current date and time 
mysql~ SELECT NOW( ); 
Mysql Evaluating Expression 
Expressions have operators and terms and they are evaluated to generate values. Expressions 
contain constants, Iunction calls and reIerences to table columns. These values can be combined 
using diIIerent kinds oI operators like comparison or arithmetic operators. Expression terms can 
be grouped with parentheses. 
select concat(lastname, ', ', Iirstname), 
(YEAR(death) - YEAR(birth)) - iI(RIGHT(death,5)RIGHT(birth,5),1,0) 
Irom president 
where 
birth ~ '1985-5-5' and death is not null; 
When an Expression is encountered MySQL, it evaluates the expression to produce a result. 
 
Writing Expressions 
An Writing expression can be as simple as a single constant. Expressions may use Iunction calls. 
But some Iunction takes arguments and some does not. And multiple arguments are separated by 
commas.  
 0   Numeric constant 
 'abc'   String constant 
 '06-11-
22'         
 Date constant 
Example: 
mysql~ select ((25*4)/10)35; 
---------------- 
, ((25*4)/10)35 , 
---------------- 
, 45.00 , 
---------------- 
1 row in set (0.00 sec) 
CONCT) 
The CONCAT() Iunction uses argument between parenthesis. These can be use columns name or 
plane text string . 
Example 
mysql~ SELECT CONCAT(Iname, " ", lname) 
Irom employeedata  
where title  'Programmer'; 
 
----------------------------- 
, CONCAT(Iname, " ", lname) , 
----------------------------- 
, Alok Kumar , 
, deepak ranjan , 
, sushil pal , 
, chandan kumar , 
----------------------------- 
4 rows in set (0.00 sec)  
 
 
Data Definition Statement 
In this section we will describe you the syntax oI most oI the Data DeIinition statements 
supported by MySQL. These statements are given below : 
Creating a Database 
For creating a database the command syntax : 
CRETE DTBSE IF NOT EISTS] <db_name> 
By the command CREATE DATABASE we can create the database with the given name. But 
using this command you have the CREATE privilege Ior the database. And iI you are trying to 
create a database, which already exists and you are not using the IF NOT EXIST option then you 
get an error. But iI you are using this option then you will not get the error but the database is not 
created again. 
       
Example for Creating a new Database : 
mysql CREATE DATABASE IF NJT 
EXISTS Employee; 
Query JK, 1 row affected (0.02 
sec) 
In the Iollowing example we are trying to create a database with the same name but without IF 
NOT EXISTS option that gives you an error message. Example : 
mysql CREATE DATABASE Employee; 
ERRJR 1007 (HY000): Can't create database 
'employee'; database exists 
In the Iollowing example we are trying to create a database with the same name with the IF NOT 
EXISTS option that gives you only a warning but the database is not created again. Example :  
mysql CREATE DATABASE IF NJT 
EXISTS Employee; 
Query JK, 1 rows affected, 1 
warning (0.25 sec) 
II you get this message that means you have successIully created the database. Now we want to 
see how many databases are available on the system. We can do this by SHOW statement 
Example : 
mysql show databases; 
+--------------------+ 
| Database           | 
+--------------------+ 
| information_schema | 
| employee           | 
| mysql              | 
| test               | 
+--------------------+ 
4 rows in set (0.23 sec) 
Creating a Table 
Syntax Ior creating a table a little more complex than creating a database. 
CRETE TEMPORRY] TBLE IF NOT EISTS] 
<table_name>create_definition,...)] table_options] select_statement] 
      
IF NOT EXISTS option works like the same as it does in CREATE DATABASE statement. But 
TEMPORARY option is used to deIine that the table has been created will available only until 
the current connection to the database is open. When the connection is disconnected even by 
accidentally, table will be deleted. 
     
There are a variety oI options are available that we can put inside the createdeIinition brackets 
Example : 
<column_name> <data type> NOT NULL [ NULL] DEFULT 
<default_value>]UTO_INCREMENT] PRIMRY KEY <index_column_name>,...) 
O 1he column_name ls used Lo deflne Lhe fleld or column of Lhe Lable of each record And each 
column name has daLa Lype also  
O 1he nC1 nuLL/nuLL opLlon ls used Lo deflne LhaL Lhe fleld ls requlre Lhe daLa or noL  
O 1he uLlAuL1 opLlon ls used Lo seL Lhe defaulL value (whlch Lhe daLabase uses ln lleu of lnpuL 
daLa) 
O An lnLeger column can have Lhe Au1ClnC8LMLn1 aLLrlbuLes 1he Au1ClnC8LMLn1 opLlon ls 
used Lo auLomaLlcally seL counLs up when nuLL ls lnpuL lnLo Lhe column's fleld 
O 98lMA8? kL? opLlon ls used Lo lndlcaLe whlch column of flelds wlll be used Lo form an lndex for 
fasLer access Lo Lhe Lable's records 
BeIore issuing the CRETE TBLE statement we have to issue USE db_name command. 
Example oI Create Table Command : 
mysql use employee 
Database changed 
mysql CREATE TABLE Emp( 
    - Eid INT UNSIGNED NJT NULL AUTJ_INCREMENT PRIMARY KEY, 
    - Ename VARCHAR(20), City VARCHAR(15), 
    - Designation VARCHAR(20), Salary INT); 
Query JK, 0 rows affected (0.83 sec) 
For veriIying about the table creation we can issue the SHOW TBLES command. This 
command returns the list oI tables are available in selected database. 
mysql SHJW TABLES; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
+--------------------+ 
1 row in set (0.00 sec) 
ltering tbe Database 
The general syntax Ior altering the database is : 
LTER DTBSE] db_name] alter_specification alter_specification]...... 
      
By ALTER DATABASE command you can change the overall characteristics oI a database. 
And these characteristics are stored in db.opt Iile in the database directory. But Ior using ALTER 
DATABASE command you have ALTER privilege on the database. The Iollowing example 
increase the size oI one Iile that available in the database. Example : 
mysql ALTER DATABASE 
Emp 
    - MJDIFY FILE 
    - (NAME = test1, 
    - SIZE = 20MB); 
ltering tbe Table  
The general syntax Ior altering the table is : 
LTER TBLE tbl_name alter_specification , alter_specification] ... 
By the ALTER TABLE command you can change the structure oI an existing table. This 
commands allows you add, modiIy or delete the columns, create or destroy the indexes, rename 
the columns or the table itselI. For using the ALTER TABLE command you need the ALTER, 
INSERT and CREATE privileges Ior the tables. Here is some examples are given below that 
helps you to understand the diIIerent alter speciIication Ior altering the table. 
The Iirst example is used to rename the table name by the command LTER TBLE 
old_name RENME TO new_name; 
mysql show tables; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| employee_data      | 
+--------------------+ 
2 rows in set (0.05 sec) 
mysql> ALTER TABLE employee_data RENAME TO employe; 
Query OK, 0 rows affected (0.04 sec) 
mysql show tables; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| employe            | 
+--------------------+ 
2 rows in set (0.00 sec) 
The Iollowing example is used to add a new column in existing table by the command LTER 
TBLE tbl_name DD column_name column_type; and Ior multiple columns we can use 
LTER TBLE tbl_name DD column_1 column_type, column_2 column_type); 
mysql DESCRIBE Emp; 
+-------------+------------------+------+-----+---------+----------------+ 
| Field       | Type             | Null | Key | Default | Extra          | 
+-------------+------------------+------+-----+---------+----------------+ 
| Eid         | int(10) unsigned | NJ   | PRI |         | auto_increment | 
| Ename       | varchar(20)      | YES  |     |         |                | 
| City        | varchar(15)      | YES  |     |         |                | 
| Designation | varchar(20)      | YES  |     |         |                | 
| Salary      | int(11)          | YES  |     |         |                | 
+-------------+------------------+------+-----+---------+----------------+ 
5 rows in set (0.02 sec) 
mysql> ALTER TABLE Emp 
    -> ADD Age numeric(3); 
Query OK, 0 rows affected (0.21 sec) 
Records: 0  Duplicates: 0  Warnings: 0 
mysql DESCRIBE Emp; 
+-------------+------------------+------+-----+---------+----------------+ 
| Field       | Type             | Null | Key | Default | Extra          | 
+-------------+------------------+------+-----+---------+----------------+ 
| Eid         | int(10) unsigned | NJ   | PRI |         | auto_increment | 
| Ename       | varchar(20)      | YES  |     |         |                | 
| City        | varchar(15)      | YES  |     |         |                | 
| Designation | varchar(20)      | YES  |     |         |                | 
| Salary      | int(11)          | YES  |     |         |                | 
| Age         | decimal(3,0)     | YES  |     |         |                | 
+-------------+------------------+------+--25f 
5 rows in set (0.02 sec) 
 
 
Dropping tbe Database 
The general syntax Ior dropping the database command is : 
DROP DTBSE [ SCHEM] IF EISTS] db_name 
 
DROP DATABASE command is used to drop the all tables in the given database and deletes the 
database also. But Ior using the DROP DATABASE statement you need the DROP privilege on 
the database. II you are not using IF EXISTS option and the database is not available which you 
want to drop then it occurs the error but iI you are using this option then it doesn't occur the 
error. Example : 
mysql SHJW DATABASES; 
+--------------------+ 
| Database           | 
+--------------------+ 
| information_schema | 
| emp1               | 
| employee           | 
| mysql              | 
| test               | 
+--------------------+ 
5 rows in set (0.00 sec) 
mysql> DROP DATABASE IF EXISTS 
emp1; 
Query OK, 0 rows affected (0.10 
sec) 
mysql SHJW DATABASES; 
+--------------------+ 
| Database           | 
+--------------------+ 
| information_schema | 
| employee           | 
| mysql              | 
| test               | 
+--------------------+ 
4 rows in set (0.01 sec) 
 
Dropping tbe Table  
The general syntax Ior dropping the table command is : 
DROP TEMPORRY] TBLE IF EISTS] tbl_name  
DROP TABLE statement is used to remove one or more tables in the database but Ior this you 
must have the DROP privilege Ior each table. By this command all the data oI table and the 
deIinition also has been removed. II you are not using IF EXISTS option and any table name in 
the argument list do not exists the MySQL returns an error with the name oI non existing tables it 
was unable to drop. But it drops the all tables oI the list that do exist. By using TEMPORARY 
keyword, the statement drops only temporary tables, the statement does not end an ongoing 
transaction and it does not check the access right because the temporary table is visible only to 
the client that creates it, that`s why the access right checking is not is not necessary. II you are 
not using the TEMPORARY keyword then the DROP TABLE command automatically commits 
the current active transaction. Example :  
mysql SHJW TABLES; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| employe            | 
+--------------------+ 
2 rows in set (0.00 sec) 
mysql> DROP TABLE IF EXISTS 
employe; 
Query OK, 0 rows affected (0.56 
sec) 
mysql SHJW TABLES; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
+--------------------+ 
1 row in set (0.01 sec) 
ename tbe Table 
The general syntax oI rename the table command is : 
RENME TBLE tbl_name TO new_tbl_name, tbl_name2 TO new_tbl_name2 ... 
 
By this statement we can rename the one or more tables. The rename operation is work 
automatically that means no other thread can access any oI the tables while the rename process is 
running. Example :  
mysql SHJW TABLES; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| employee_data      | 
+--------------------+ 
2 rows in set (0.01 sec) 
mysql> RENAME TABLE 
employee_data TO EMP1; 
Query OK, 0 rows affected 
(0.14 sec) 
mysql SHJW TABLES; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| emp1               | 
+--------------------+ 
2 rows in set (0.00 sec) 
 
 
 
 
 
 
 
Data Manipulation Statements 
uaLa ManlpulaLlon SLaLemenL ls used Lo reLrleve lnserL updaLe and deleLe Lhe records ln a daLabase All 
daLabase users wlll use Lhese commands durlng rouLlne operaLlon of Lhe daLabase  
  Data Manipulation Statement is used to retrieve, insert, update and delete the records in a 
database. All database users will use these commands during routine operation oI the 
database. In this section we are describing the Iollowing Data Manipulation Statements : 
O Se|ect Statement 
O nsert Statement 
O Date Statement 
O e|ete Statement 
CT tatement 
The SELECT statement is used to retrieve a result set oI records Irom one or more tables, 
temporary tables or views in a database. It is the most commonly used DML command. In this 
statement the user can speciIy a description oI the required result set. There are some 
keywords uses in SELECT statement that are described in the Iollowing table  
keywords                 uescrlpLlon 
SLLLC1  
SLLLC1 sLaLemenL ls used Lo reLrleve flelds from one or more 
Lables      
l8CM  1ables conLalnlng  Lo Lhe flelds 
WPL8L 
1he WPL8L clause ls used Lo descrlbe Lhe crlLerla Lo resLrlcL 
Lhe records reLrleved 
C8Cu9 8? 
1he C8Cu9 8? clause ls used Lo deLermlne how Lhe records 
should be grouped   
PAvlnC 
PAvlnC clause used wlLh C8Cu9 8? Lo deflne Lhe crlLerla for 
grouped records 
C8uL8 8? 
 1he C8uL8 8? clause ls used Lo descrlbed Lhe crlLerla for 
orderlng Lhe record 
LlMl1 
1he LlMl1 clause ls used Lo resLrlcL Lhe llmlL of number of 
records reLrleved 
The simple SELECT statement is used to retrieve the all records Irom table. By the Iollowing 
example you can retrieve the Iull list oI Emp table.  
mysql SELECT  FRJM Emp; 
+-----+--------+--------+------------
-------+--------+ 
| Eid | Ename  | City   | Designation 
| Salary | 
+-----+--------+--------+------------
-------+--------+ 
| 1   | Rahul  | Delhi  | Manager     
| 10000  | 
| 2   | Gaurav | Mumbai | Assistant 
Manager | 10000  | 
+-----+--------+--------+------------
-------+--------+ 
2 rows in set (0.00 sec) 
II you want to retrieve only some Iields Irom a table, then you have to provide a comma 
separated list oI column names. By the Iollowing example you select Name, City and Age 
Iields Irom the Emp table.  
mysql SELECT Eid, Ename, Salary 
FRJM Emp; 
+-----+--------+--------+ 
| Eid | Ename  | Salary | 
+-----+--------+--------+ 
| 1   | Rahul  | 10000  | 
| 2   | Gaurav | 10000  | 
+-----+--------+--------+ 
2 rows in set (0.02 sec) 
WHERE Clause  
The WHERE clause is used to limit the number oI records. The comparison operators are used 
with WHERE clause to limit the number oI records. Comparison operator`s list are given 
below:   
 CperaLor   uescrlpLlon  
   Lqual Lo  
 or !  noL equal Lo  
  Less Lhen 
    Less Lhen or equal Lo  
   CreaLer Lhen  
    CreaLer Lhen or equal Lo  
Llke   used for comparlng sLrlng  
8eLween   used for checklng value beLween a range 
ln   used Lo check values ln a llsL 
nC1 ln   used Lo check Lhe value ls noL ln Lhe llsL  
 Character - II you are working with Strings, then  character can be used as a wildcard. 
By the Iollowing example you can retrieve the all Iields Irom Emp table where the 
Designation Iield contain the text, 'Manager'. 
mysql SELECT  FRJM Emp WHERE 
Designation LIKE '%Manager%'; 
+-----+--------+--------+---------------
----+--------+ 
| Eid | Ename  | City   | Designation     
| Salary | 
+-----+--------+--------+---------------
----+--------+ 
| 1   | Rahul  | Delhi  | Manager         
| 10000  | 
| 2   | Gaurav | Mumbai | Assistant 
Manager | 10000  | 
+-----+--------+--------+---------------
----+--------+ 
2 rows in set (0.02 sec) 
_ character - The underscore character can be used as a placeholder. By the Iollowing 
example you can selects the all records Irom the table Emp, where the Name starts with C` 
Iollowed by Six characters. For this we have to use Six underscores. 
mysql SELECT  FRJM Emp WHERE Ename LIKE 
'C______'; 
+-----+---------+----------+-------------
+--------+ 
| Eid | Ename   | City     | Designation 
| Salary | 
+-----+---------+----------+-------------
+--------+ 
| 3   | Chandan | Banglore | Team Leader 
| 15000  | 
+-----+---------+----------+-------------
+--------+ 
1 row in set (0.00 sec) 
BETWEEN Clause - The BETWEEN clause can be used with numbers, dates and text. The 
Iollowing example is used to retrieve all Iields Emp table where the Salary is between 8000 
AND 10000. 
mysql SELECT  FRJM Emp WHERE Salary 
BETWEEN 8000 AND 10000; 
+-----+---------+--------+--------------
-----+--------+ 
| Eid | Ename   | City   | Designation    
| Salary | 
+-----+---------+--------+--------------
-----+--------+ 
| 1   | Rahul   | Delhi  | Manager        
| 10000  | 
| 2   | Gaurav  | Mumbai | Assistant 
Manager | 10000  | 
| 4   | Santosh | Delhi  | Designer       
| 8000   | 
+-----+---------+--------+--------------
-----+--------+ 
3 rows in set (0.01 sec) 
OR Clause - The OR clause is used to check the values against the range oI values that have 
been speciIied. The Iollowing example retrieves the list oI all records where the Designation is 
either 'Designer' or City is 'Mumbai' in the Emp table. 
mysql SELECT  FRJM Emp WHERE 
Designation='Designer' JR City='Mumbai'; 
+-----+---------+--------+-------------------
+--------+ 
| Eid | Ename   | City   | Designation       
| Salary | 
+-----+---------+--------+-------------------
+--------+ 
| 2   | Gaurav  | Mumbai | Assistant Manager 
| 10000  | 
| 4   | Santosh | Delhi  | Designer          
| 8000   | 
+-----+---------+--------+-------------------
+--------+ 
2 rows in set (0.44 sec) 
IN Clause - The IN clause is used to check the values against to many values that have been 
speciIied in IN clause. The Iollowing example retrieves the list oI all records where the 
Designation is either 'Manager' or 'Assistant' in the Emp table. 
mysql SELECT  FRJM Emp WHERE Designation 
IN ('Manager','Designer'); 
+-----+---------+-------+-------------+-----
---+ 
| Eid | Ename   | City  | Designation | 
Salary | 
+-----+---------+-------+-------------+-----
---+ 
| 1   | Rahul   | Delhi | Manager     | 
10000  | 
| 4   | Santosh | Delhi | Designer    | 8000 
| 
+-----+---------+-------+-------------+-----
---+ 
2 rows in set (0.03 sec) 
NOT IN Clause - You can use the NOT modiIier with IN clause Ior checking the values, 
which are not within the list. The Iollowing example retrieves the list oI all records where the 
Designation is not equal to 'Manager' or 'Assistant' in the Emp table. 
mysql SELECT  FRJM Emp WHERE Designation NJT 
IN ('Manager','Designer'); 
+-----+---------+----------+-------------------
+--------+ 
| Eid | Ename   | City     | Designation       
| Salary | 
+-----+---------+----------+-------------------
+--------+ 
| 2   | Gaurav  | Mumbai   | Assistant Manager 
| 10000  | 
| 3   | Chandan | Banglore | Team Leader       
| 15000  | 
+-----+---------+----------+-------------------
+--------+ 
2 rows in set (0.81 sec) 
ROUP BY Clause 
The GROUP BY clause is an optional clause. A query has a GROUP BY clause is known as 
GROUPING QUERY. A Grouping Query is a special type oI query that is used to groups and 
summarized the rows. It operators on the rows Irom the FROM Clause as Iiltered by the 
WHERE clause. It is used to collects the rows into groups that`s based on the common values 
in the grouping columns. The general syntax oI GROUP BY clause is : 
SELECT ` FROM tbl_name ROUP BY column_name; 
Example : 
mysql SELECT  FRJM Emp GRJUP BY Ename; 
+-----+---------+----------+---------------
----+--------+-------+ 
| Eid | Ename   | City     | Designation    
| Salary | Perks | 
+-----+---------+----------+---------------
----+--------+-------+ 
| 3   | Chandan | Banglore | Team Leader    
| 15000  | 999   | 
| 2   | Gaurav  | Mumbai   | Assistant 
Manager | 10000  | 853   | 
| 1   | Rahul   | Delhi    | Manager        
| 10000  | 853   | 
| 4   | Santosh | Delhi    | Designer       
| 8000   | 825   | 
+-----+---------+----------+---------------
----+--------+-------+ 
4 rows in set (0.25 sec) 
ggregate Function 
The Iollowing list shows you a Aggregate Function that available in MySQL. Our Table 
records are listed below and on this table we perIorming these aggregate Iunction : 
Table : 
mysql SELECT  FRJM Emp; 
+-----+---------+----------+---------------
----+--------+-------+ 
| Eid | Ename   | City     | Designation     
| Salary | Perks | 
+-----+---------+----------+---------------
----+--------+-------+ 
| 1   | Rahul   | Delhi    | Manager         
| 10000  | 853   | 
| 2   | Gaurav  | Mumbai   | Assistant 
Manager | 10000  | 853   | 
| 3   | Chandan | Banglore | Team Leader     
| 15000  | 999   | 
| 4   | Santosh | Delhi    | Designer        
| 8000   | 825   | 
+-----+---------+----------+---------------
----+--------+-------+ 
4 rows in set (0.00 sec) 
O I% ) 
1he AvC( ) funcLlon reLurns Lhe average value ln a group of records Lxample of Lhe AvC( ) 
funcLlon 
       
mysql SELECT AVG(Perks) FRJM Emp 
GRJUP BY Perks; 
+------------+ 
| AVG(Perks) | 
+------------+ 
| 825.0000   | 
| 853.0000   | 
| 999.0000   | 
+------------+ 
3 rows in set (0.02 sec) 
       
O D-@% ) 
1he CCun1( ) funcLlon reLurns Lhe number of  records ln a group of records Lxample of Lhe 
CCun1( ) funcLlon 
        
mysql SELECT CJUNT(Perks) FRJM 
Emp GRJUP BY Perks; 
+--------------+ 
| CJUNT(Perks) | 
+--------------+ 
| 1            | 
| 2            | 
| 1            | 
+--------------+ 
3 rows in set (0.00 sec) 
       
O ,O% ) 
1he MAx( ) funcLlon reLurn Lhe maxlmum value ln a group of records Lxample of Lhe MAx( ) 
funcLlon 
        
mysql SELECT MAX(Salary) 
FRJM Emp; 
+-------------+ 
| MAX(Salary) | 
+-------------+ 
| 15000       | 
+-------------+ 
1 row in set (0.00 sec) 
       
O ,-% ) 
1he Mln( ) funcLlon reLurns mlnlmum value ln a group of records Lxample of Lhe Mln( ) 
funcLlon  
       
mysql SELECT MIN(Salary) 
FRJM Emp; 
+-------------+ 
| MIN(Salary) | 
+-------------+ 
| 8000        | 
+-------------+ 
1 row in set (0.00 sec) 
       
O SD,% ) 
1he SuM( ) funcLlon reLurn Lhe sum of Lhe fleld Lxample of Lhe SuM() funcLlon  
     
mysql SELECT SUM(Perks) 
FRJM Emp; 
+------------+ 
| SUM(Perks) | 
+------------+ 
| 3530       | 
+------------+ 
1 row in set (0.01 sec) 
The H'IN Clause 
 
As you know the WHERE clause is used to restrict the records in a query. But iI you want to 
restrict the records by using the Aggregate Iunction then you have to use the HAVING clause. 
The HAVING clause restricts the records aIter they have been grouped. The Iollowing 
example shows the list oI all Employees who got the perks more than 900 on average. 
mysql SELECT  FRJM Emp GRJUP BY Salary 
HAVING AVG(Perks)900; 
+-----+---------+----------+------------
-+--------+-------+ 
| Eid | Ename   | City     | Designation 
| Salary | Perks | 
+-----+---------+----------+------------
-+--------+-------+ 
| 3   | Chandan | Banglore | Team Leader 
| 15000  | 999   | 
+-----+---------+----------+------------
-+--------+-------+ 
1 row in set (0.00 sec) 
The ORDER BY Clause 
      
The ORDER BY clause can be used to set the order oI the retrieved records. The Iollowing 
example shows the list oI all employees in the Emp table in alphabetical order. In this clause 
we can use the ASC or DESC modiIiers to set the order oI records in ascending or descending 
order. II any modiIier is not provided then the records are listed in ascending order. 
mysql SELECT  FRJM Emp JRDER BY Eid 
DESC; 
+-----+---------+----------+--------------
-----+--------+-------+ 
| Eid | Ename   | City     | Designation   
| Salary | Perks | 
+-----+---------+----------+--------------
-----+--------+-------+ 
| 4   | Santosh | Delhi    | Designer      
| 8000   | 825   | 
| 3   | Chandan | Banglore | Team Leader   
| 15000  | 999   | 
| 2   | Gaurav  | Mumbai   | Assistant 
Manager | 10000  | 853   | 
| 1   | Rahul   | Delhi    | Manager       
| 10000  | 853   | 
+-----+---------+----------+--------------
-----+--------+-------+ 
4 rows in set (0.00 sec) 
The LIMIT Clause 
     
The LIMIT clause can be used to limit the number oI records that have been returned by the 
SELECT statement. You can speciIy the start row, and number oI records retrieved.  
mysql SELECT  FRJM Emp LIMIT 0,2; 
+-----+--------+--------+-----------------
--+--------+-------+ 
| Eid | Ename  | City   | Designation      
| Salary | Perks | 
+-----+--------+--------+-----------------
--+--------+-------+ 
| 1   | Rahul  | Delhi  | Manager          
| 10000  | 853   | 
| 2   | Gaurav | Mumbai | Assistant 
Manager | 10000  | 853   | 
+-----+--------+--------+-----------------
--+--------+-------+ 
2 rows in set (0.00 sec) 
T tatement 
The INSERT statement is used to add one or more records to a existing table in a database. 
This statement can insert the data into only a single table. The general syntax oI the INSERT 
Statement is : 
INSERT LOW_PRIORITY [ DELYED [ HIH_PRIORITY] INORE] INTO 
tbl_name column1, column2, .. ]) 'LUES value1, value2, ..])  
and 
INSERT LOW_PRIORITY [ DELYED [ HIH_PRIORITY] INORE] INTO 
tbl_name 'LUES value1, value2, ...])  
      
II we are speciIying the column name in INSERT statement then the number oI columns and 
values must be same. In this situation any column is not speciIied then the deIault value Ior 
the column is used. The values are speciIied in the INSERT command must speciIy the all-
applicable constraints like primary keys, NOT NULL and CHECK Constraints. II any 
constraints are violated then it occurs syntax error and new row is not added. Example : 
mysql INSERT INTJ 
Emp(Ename,City,Designation,Salary,Perks) 
VALUES('Tapan','Pune', 
'Developer',20000,1111); 
Query JK, 1 row affected (0.04 sec) 
mysql INSERT INTJ Emp 
VALUES(6,'Rajesh','Hyderabad','Developer',18000,1222); 
Query JK, 1 row affected (0.41 sec) 
INSERT Statement supports the Iollowing modiIiers :  
O lf we are uslng Lhe uLLA?Lu keyword Lhen Lhe server puLs Lhe row lnLo a buffer and Lhe 
cllenL lssues Lhe lnSL81 command can Lhen conLlnue lmmedlaLely lf Lable ls ln use Lhen 
server can holds Lhe rows and when Lhe Lable ls free Lhen only server can beglns lnserLlng Lhe 
rows And lLs also used Lo lnserL from many cllenLs are bundled LogeLher and wrlLLen ln one 
block  
      
O lf we are uslng Lhe LCW_98lC8l1? keyword Lhen Lhe execuLlon of lnSL81 sLaLemenL ls 
delayed unLll no oLher cllenLs are readlng from Lhe Lable lL can be posslble a cllenL whlch 
lssues a lnSL81 LCW_98lC8l1? sLaLemenL have Lo walL for a long Llme(forever also) ln a read 
heavy envlronmenL 
      
O 8uL lf we are uslng PlCP_98lC8l1? Lhen lL overrldes Lhe effecL of LCW_98lC8l1? updaLes 
opLlon 
     
O lf we are uslng lCnC8L keyword Lhen Lhe execuLlon of lnSL81 sLaLemenL error can be LreaLed 
as a warnlngs Means wlLh lCnC8L Lhe row sLlll ls noL lnserLed buL no error ls occurred  
DT tatement 
The UPDATE statement is used to modiIy the record contained with in a table either one row 
or more than one row. The general syntax oI UPDATE Statement is : 
UPDTE LOW_PRIORITY] INORE] tbl_name SET col_name1expr1 , 
col_name2expr2 ...] WHERE where_condition] ORDER BY ...] LIMIT row_count] 
The set clause is used to indicates which columns have to modiIy and the values they should 
be given. II WHERE clause is given then it speciIies the conditions that identiIy which rows 
to modiIy. II ORDER BY clause is given that the rows are modiIy in the order that is 
speciIied. II LIMIT clause is given then it places a limit on the number oI rows that can be 
modiIied. 
The UPDATE statement supports the Iollowing modiIiers:  
O lf LCW_98lC8l1? keyword ls uslng Lhen execuLlon of u9uA1L command ls delayed unLll no 
oLher cllenLs are readlng from Lhe Lable 
     
O lf lCnC8L keyword ls uslng and error occurs durlng Lhe execuLlon of updaLe command Lhen 
Lhe updaLe sLaLemenL does noL aborL 
In the Iollowing example we are updating the salary oI those employees their perks is more 
than 800. Example :  
mysql SELECT  FRJM Emp; 
+-----+---------+-----------+---------------
----+--------+-------+ 
| Eid | Ename   | City      | Designation    
| Salary | Perks | 
+-----+---------+-----------+---------------
----+--------+-------+ 
| 1   | Rahul   | Delhi     | Manager        
| 10000  | 853   | 
| 2   | Gaurav  | Mumbai    | Assistant 
Manager | 10000  | 853   | 
| 3   | Chandan | Banglore  | Team Leader    
| 15000  | 999   | 
| 4   | Santosh | Delhi     | Designer       
| 8000   | 825   | 
| 5   | Tapan   | Pune      | Developer      
| 20000  | 1111  | 
| 6   | Rajesh  | Hyderabad | Developer      
| 18000  | 1222  | 
+-----+---------+-----------+---------------
----+--------+-------+ 
6 rows in set (0.00 sec) 
mysql> UPDATE Emp 
    -> SET Salary = Salary*1.03 WHERE Perks 
> 800; 
Query OK, 6 rows affected (0.22 sec) 
Rows matched: 6  Changed: 6  Warnings: 0 
mysql SELECT  FRJM Emp; 
+-----+---------+-----------+---------------
----+--------+-------+ 
| Eid | Ename   | City      | Designation    
| Salary | Perks | 
+-----+---------+-----------+---------------
----+--------+-------+ 
| 1   | Rahul   | Delhi     | Manager        
| 10300  | 853   | 
| 2   | Gaurav  | Mumbai    | Assistant 
Manager | 10300  | 853   | 
| 3   | Chandan | Banglore  | Team Leader    
| 15450  | 999   | 
| 4   | Santosh | Delhi     | Designer       
| 8240   | 825   | 
| 5   | Tapan   | Pune      | Developer      
| 20600  | 1111  | 
| 6   | Rajesh  | Hyderabad | Developer      
| 18540  | 1222  | 
+-----+---------+-----------+---------------
----+--------+-------+ 
6 rows in set (0.00 sec) 
DT tatement 
The DELETE Statement is used the remove the records Irom the table. The general syntax oI 
DELETE Statement is : 
DELETE LOW_PRIORITY] INORE] FROM tbl_name WHERE where_condition] 
ORDER BY ...] LIMIT row_count]; 
The DELETE Statement is used Ior deleting the rows Irom the given table. II the WHERE 
clause is given then it speciIies the condition Ior identying which rows have to delete. II 
ORDER BY clause is given then it speciIies the rows are deleted in the order that is speciIied. 
The LIMIT clause is used to place a Limit on the number oI rows which can be deleted. 
The DELETE statement supports the Iollowing modiIiers:  
O lf LCW_98lC8l1? keyword ls uslng Lhen execuLlon of uLLL1L command ls delayed unLll no 
oLher cllenLs are readlng from Lhe Lable 
       
O lf lCnC8L keyword ls uslng and error occurs durlng Lhe execuLlon of uLLL1L command Lhen 
Lhe errors are reLurns as warnlngs 
In the Iollowing example we are deleting the records oI those employees their salary is less 
than 10000. Example :  
mysql SELECT  FRJM Emp; 
+-----+---------+-----------+---------------
----+--------+-------+ 
| Eid | Ename   | City      | Designation    
| Salary | Perks | 
+-----+---------+-----------+---------------
----+--------+-------+ 
| 1   | Rahul   | Delhi     | Manager        
| 10300  | 853   | 
| 2   | Gaurav  | Mumbai    | Assistant 
Manager | 10300  | 853   | 
| 3   | Chandan | Banglore  | Team Leader    
| 15450  | 999   | 
| 4   | Santosh | Delhi     | Designer       
| 8240   | 825   | 
| 5   | Tapan   | Pune      | Developer      
| 20600  | 1111  | 
| 6   | Rajesh  | Hyderabad | Developer      
| 18540  | 1222  | 
+-----+---------+-----------+---------------
----+--------+-------+ 
6 rows in set (0.00 sec) 
mysql> DELETE FROM Emp WHERE Salary<10000; 
Query OK, 1 row affected (0.07 sec) 
mysql SELECT  FRJM Emp; 
+-----+---------+-----------+---------------
----+--------+-------+ 
| Eid | Ename   | City      | Designation    
| Salary | Perks | 
+-----+---------+-----------+---------------
----+--------+-------+ 
| 1   | Rahul   | Delhi     | Manager        
| 10300  | 853   | 
| 2   | Gaurav  | Mumbai    | Assistant 
Manager | 10300  | 853   | 
| 3   | Chandan | Banglore  | Team Leader    
| 15450  | 999   | 
| 5   | Tapan   | Pune      | Developer      
| 20600  | 1111  | 
| 6   | Rajesh  | Hyderabad | Developer      
| 18540  | 1222  | 
+-----+---------+-----------+---------------
----+--------+-------+ 
5 rows in set (0.00 sec) 
C tatement 
REPLACE Statement works exactly same as the INSERT Statement, except only then iI an 
old record in the table has the same value as in new row Ior a PRIMARY KEY or UNIQUE 
index then old row is deleted and new row is inserted. The general syntax oI REPLACE 
Statement is : 
REPLCE LOW_PRIORITY [ DELYED] INTO] tbl_name col_name,...)] 
'LUES expr [ DEFULT],...),...),... 
The REPLACE Statement returns a count Ior indicating the number oI records aIIected. It is 
the sum oI rows deleted and inserted. When the count is 1 that means one record was inserted 
and no records were deleted. But iI the count is greater than one that means one or more old 
records were deleted beIore inserted the new row. For using REPLACE command need the 
both INSERT and DELETE privileges Ior the table. 
In the Iollowing example we are replacing the record that's having the Eid is 6. 
mysql SELECT  FRJM Emp; 
+-----+---------+-----------+-------------------+-
-------+-------+ 
| Eid | Ename   | City      | Designation       | 
Salary | Perks | 
+-----+---------+-----------+-------------------+-
-------+-------+ 
| 1   | Rahul   | Delhi     | Manager           | 
10300  | 853   | 
| 2   | Gaurav  | Mumbai    | Assistant Manager | 
10300  | 853   | 
| 3   | Chandan | Banglore  | Team Leader       | 
15450  | 999   | 
| 5   | Tapan   | Pune      | Developer         | 
20600  | 1111  | 
| 6   | Rajesh  | Hyderabad | Developer         | 
18540  | 1222  | 
+-----+---------+-----------+-------------------+-
-------+-------+ 
5 rows in set (0.00 sec) 
mysql> REPLACE INTO Emp 
VALUES(6,'Amar','Chennai','Developer',16000,1124); 
Query OK, 2 rows affected (0.06 sec) 
mysql SELECT  FRJM Emp; 
+-----+---------+----------+-------------------+--
------+-------+ 
| Eid | Ename   | City     | Designation       | 
Salary | Perks | 
+-----+---------+----------+-------------------+--
------+-------+ 
| 1   | Rahul   | Delhi    | Manager           | 
10300  | 853   | 
| 2   | Gaurav  | Mumbai   | Assistant Manager | 
10300  | 853   | 
| 3   | Chandan | Banglore | Team Leader       | 
15450  | 999   | 
| 5   | Tapan   | Pune     | Developer         | 
20600  | 1111  | 
| 6   | Amar    | Chennai  | Developer         | 
16000  | 1124  | 
+-----+---------+----------+-------------------+--
------+-------+ 
5 rows in set (0.00 sec) 
TCT tatement  
TRUNCATE Statement is also used to empty the table completely. The general syntax oI 
TRUNCATE Statement is :  
TRUNCTE tbl_name;  
Logically TRUNCATE Statement is same as DELETE Statement, which deletes all rows. But 
practically they have some diIIerences :  
O 18unCA1L command drop Lhe Lable and recreaLe Lhe deflnlLlon of Lable whlch ls much fasLer 
Lhan deleLlng Lhe rows one by one 
     
O 18unCA1L command operaLlon are noL LransacLlon safe 
     
O 18unCA1L command does noL reLurn Lhe number of deleLed rows 
      
O lf Lable formaL flle tb|_namefrm ls valld Lhen Lhe Lable can be recreaLed lf lLs empLy by Lhe 
18unCA1L command even lf Lhe daLa or lndex flles have become corrupLed 
In the Iollowing example we truncating the Emp1 table. 
mysql select  from Emp1; 
+--------+--------+--------+-----------+------
+------+--------+-------+ 
| emp_id | f_name | l_name | title     | age  
| yos  | salary | perks | 
+--------+--------+--------+-----------+------
+------+--------+-------+ 
| 1      | Rahul  | Jain   | Manager   | 22   
| 1    | 10000  | 5000  | 
| 2      | Rajesh | Kumar  | Developer | 25   
| 2    | 20000  | 500   | 
+--------+--------+--------+-----------+------
+------+--------+-------+ 
2 rows in set (0.00 sec) 
mysql> TRUNCATE Emp1; 
Query OK, 2 rows affected (0.20 sec) 
mysql select  from Emp1; 
Empty set (0.00 sec) 
mysql show tables; 
+--------------------+ 
| Tables_in_employee | 
+--------------------+ 
| emp                | 
| emp1               | 
+--------------------+ 
2 rows in set (0.00 sec) 
   
 
 
oins
 Sometimes you required the data Irom more than one table. When you select the data Irom more than one table this 
is known as Joining. A join is a SQL query that is used to select the data Irom more than one table or views..  
  
Sometimes you required the data Irom more than one table. When you select the data Irom 
more than one table this is known as Joining. A join is a SQL query that is used to select the 
data Irom more than one table or views. When you deIine multiple tables or views in the 
FROM clause oI a query the MySQL perIorms a join that linking the rows Irom multiple 
tables together. 
Types of oins : 
O INNER Joins 
O OUTER Joins 
O SELF Joins 
We are going to describe you the Join with the help oI Iollowing two tables : 
mysql SELECT  FRJM Client; 
+------+---------------+----
------+ 
| C_ID | Name          | 
City     | 
+------+---------------+----
------+ 
| 1    | A K Ltd       | 
Delhi    | 
| 2    | V K Associate | 
Mumbai   | 
| 3    | R K India     | 
Banglore | 
| 4    | R S P Ltd     | 
Kolkata  | 
+------+---------------+----
------+ 
4 rows in set (0.00 sec) 
mysql SELECT  FRJM 
Products; 
+---------+-------------+---
---+ 
| Prod_ID | Prod_Detail | 
C_ID | 
+---------+-------------+---
---+ 
| 111     | Monitor     | 1  
| 
| 112     | Processor   | 2  
| 
| 113     | Keyboard    | 2  
| 
| 114     | Mouse       | 3  
| 
| 115     | CPU         | 5  
| 
+---------+-------------+---
---+ 
5 rows in set (0.00 sec) 
INNER oins 
The INNER join is considered as the deIault Join type. Inner join returns the column values 
Irom one row oI a table combined with the column values Irom one row oI another table that 
satisIy the search condition Ior the join. The general syntax oI INNER Join is : 
SELECT <column_name1>, <column_name2> FROM <tbl_name> INNER OIN 
<tbl_name> ON <join_conditions>  
The Iollowing example takes all the records Irom table Client and Iinds the matching records 
in table Product. But iI no match is Iound then the record Irom table Client is not included in 
the results. But iI multiple results are Iound in table Product with the given condition then one 
row will be return Ior each. 
Example :  
mysql> SELECT * FROM Client 
    -> INNER JOIN Products 
    -> ON Client.C_ID=Products.C_ID; 
+------+---------------+----------+--------
-+-------------+------+ 
| C_ID | Name          | City     | Prod_ID 
| Prod_Detail | C_ID | 
+------+---------------+----------+--------
-+-------------+------+ 
| 1    | A K Ltd       | Delhi    | 111     
| Monitor     | 1    | 
| 2    | V K Associate | Mumbai   | 112     
| Processor   | 2    | 
| 2    | V K Associate | Mumbai   | 113     
| Keyboard    | 2    | 
| 3    | R K India     | Banglore | 114     
| Mouse       | 3    | 
+------+---------------+----------+--------
-+-------------+------+ 
4 rows in set (0.04 sec) 
OUTER oins  
Sometimes when we are perIorming a Join between the two tables, we need all the records 
Irom one table even there is no corresponding record in other table. We can do this with the 
help oI OUTER Join. In other words an OUTER Join returns the all rows that returned by an 
INNER Join plus all the rows Irom one table that did not match any row Irom the other table. 
Outer Join are divided in two types : LEFT OUTER oin, RIHT OUTER oin  
LEFT OUTER oin  
LEFT OUTER Join is used to return all the rows that returned by an INNER Join plus all the 
rows Irom Iirst table that did not match with any row Irom the second table but with the 
NULL values Ior each column Irom second table. The general syntax oI LEFT OUTER Join is 
: 
SELECT <column_name1>, <column_name2> FROM <tbl_name> LEFT OUTER 
OIN <tbl_name> ON <join_conditions>  
In the Iollowing example we are selected every row Irom the Client table which don`t have a 
match in the Products Table. Example :  
mysql> SELECT * FROM CLIENT 
    -> LEFT OUTER JOIN Products 
    -> ON Client.C_ID=Products.C_ID; 
+------+---------------+----------+--------
-+-------------+------+ 
| C_ID | Name          | City     | Prod_ID 
| Prod_Detail | C_ID | 
+------+---------------+----------+--------
-+-------------+------+ 
| 1    | A K Ltd       | Delhi    | 111     
| Monitor     | 1    | 
| 2    | V K Associate | Mumbai   | 112     
| Processor   | 2    | 
| 2    | V K Associate | Mumbai   | 113     
| Keyboard    | 2    | 
| 3    | R K India     | Banglore | 114     
| Mouse       | 3    | 
| 4    | R S P Ltd     | Kolkata  | NULL    
|             | NULL | 
+------+---------------+----------+--------
-+-------------+------+ 
5 rows in set (0.00 sec) 
In the Iollowing example we are using the ORDER BY Clause with the LEFT OUTER Join.  
mysql> SELECT * FROM Client 
    -> LEFT OUTER JOIN Products 
    -> ON Client.C_ID=Products.C_ID 
    -> ORDER BY Client.City; 
+------+---------------+----------+--------
-+-------------+------+ 
| C_ID | Name          | City     | Prod_ID 
| Prod_Detail | C_ID | 
+------+---------------+----------+--------
-+-------------+------+ 
| 3    | R K India     | Banglore | 114     
| Mouse       | 3    | 
| 1    | A K Ltd       | Delhi    | 111     
| Monitor     | 1    | 
| 4    | R S P Ltd     | Kolkata  | NULL    
|             | NULL | 
| 2    | V K Associate | Mumbai   | 113     
| Keyboard    | 2    | 
| 2    | V K Associate | Mumbai   | 112     
| Processor   | 2    | 
+------+---------------+----------+--------
-+-------------+------+ 
5 rows in set (0.08 sec) 
In the result oI LEFT OUTER Join " R S P Ltd " is included even though it has no rows in the 
Products table. 
RIHT OUTER oin 
RIGHT OUTER Join is much same as the LEFT OUTER JOIN. But RIGHT OUTER Join is 
used to return all the rows that returned by an INNER Join plus all the rows Irom second table 
that did not match with any row Irom the Iirst table but with the NULL values Ior each 
column Irom Iirst table. The general syntax oI RIGHT OUTER Join is : 
SELECT <column_name1>, <column_name2> FROM <tbl_name> RIHT OUTER 
OIN <tbl_name> ON <join_conditions>  
In the Iollowing example we are selected every row Irom the Products table which don`t have 
a match in the Client Table. Example :  
mysql> SELECT * FROM Client 
    -> RIGHT OUTER JOIN Products 
    -> ON Client.C_ID=Products.C_ID; 
+------+---------------+----------+---------
+-------------+------+ 
| C_ID | Name          | City     | Prod_ID 
| Prod_Detail | C_ID | 
+------+---------------+----------+---------
+-------------+------+ 
| 1    | A K Ltd       | Delhi    | 111     
| Monitor     | 1    | 
| 2    | V K Associate | Mumbai   | 112     
| Processor   | 2    | 
| 2    | V K Associate | Mumbai   | 113     
| Keyboard    | 2    | 
| 3    | R K India     | Banglore | 114     
| Mouse       | 3    | 
| NULL |               |          | 115     
| CPU         | 5    | 
+------+---------------+----------+---------
+-------------+------+ 
5 rows in set (0.03 sec) 
SELF oin 
SELF Join means a table can be joined with itselI. SELF Join is useIul when we want to 
compare values in a column to other values in the same column. For creating a SELF Join we 
have to list a table twice in the FROM clause and assign it a diIIerent alias each time. For 
reIerring the table we have to use this aliases. 
The Iollowing example provide you the list oI those Clients that belongs to same city oI 
CID1. 
mysql> SELECT b.C_ID,b.Name,b.City FROM 
Client a, Client b 
    -> WHERE a.City=b.City AND a.C_ID=1; 
+------+----------+-------+ 
| C_ID | Name     | City  | 
+------+----------+-------+ 
| 1    | A K Ltd  | Delhi | 
| 5    | A T Ltd  | Delhi | 
| 6    | D T Info | Delhi | 
+------+----------+-------+ 
3 rows in set (0.00 sec) 
we can write this SELF JOIN Query in Subquery like this also : 
mysql> SELECT * FROM Client 
    -> WHERE City=( 
    -> SELECT City FROM 
Client 
    -> WHERE C_ID=1); 
+------+----------+-------+ 
| C_ID | Name     | City  | 
+------+----------+-------+ 
| 1    | A K Ltd  | Delhi | 
| 5    | A T Ltd  | Delhi | 
| 6    | D T Info | Delhi | 
+------+----------+-------+ 
3 rows in set (0.03 sec) 
   
 
 
 
 
 
'iews 
VIEW is a virtual table, which acts like a table but actually it contains no data. That is based on 
the result set oI a SELECT statement. A VIEW consists rows and columns Irom one or more 
than one tables. A VIEW is a query that`s stored as an object. A VIEW is nothing more than a 
way to select a subset oI table`s columns. 
When you deIined a view then you can reIerence it like any other table in a database. A VIEW 
provides as a security mechanism also. VIEWS ensures that users are able to modiIy and retrieve 
only that data which seen by them.  
By using Views you can ensure about the security oI data by restricting access to the Iollowing 
data: 
O SpeciIic columns oI the tables.  
O SpeciIic rows oI the tables.  
O SpeciIic rows and columns oI the tables.  
O Subsets oI another view or a subset oI views and tables 
O Rows Ietched by using joins.  
O Statistical summary oI data in a given tables.  
CRETE 'IEW Statement 
      
CREATE VIEW Statement is used to create a new database view. The general syntax oI 
CREATE VIEW Statement is: 
        CRETE 'IEW view_name column_list)] WITH ENCRYPTION] S 
select_statement WITH CHECK OPTION] 
'iew_name speciIies the name Ior the new view. column_list speciIies the name oI the columns 
to be used in view. column_list must have the same number oI columns that speciIied in 
select_statement. II column_list option is not available then view is created with the same 
columns that speciIied in select_statement. 
WITH ENCRYPTION option encrypts the text to the view in the syscomments table. 
S option speciIies the action that is perIormed by the view. select_statement is used to speciIy 
the SELECT statement that deIines a view. The optional WITH CHECK OPTION clause 
applies to the data modiIication statement like INSERT and UPDATE statements to IulIill the 
criteria given in the select_statement deIining the view. This option also ensures that the data 
can visible aIter the modiIications are made permanent.  
Some restrictions imposed on views are given below :  
O A view can be created only in the current database.   
O The view name must Iollow the rules Ior identiIiers and   
O The view name must not be the same as that oI the base table  
O A view can be created only that time iI there is a SELECT permission on its base table.   
O A SELECT INTO statement cannot be used in view declaration statement.   
O A trigger or an index cannot be deIined on a view.   
O The CREATE VIEW statement cannot be combined with other SQL statements in a 
single batch.   
Example : 
In the Iollowing example we have two table Client and Products. And iI you want to see only 
those client records that are active in Products table also means right now they are supplying us 
the products. For this we are creating the view by the name oI SuppClient. 
mysql SELECT  FRJM Client; 
+------+---------------+-------
---+ 
| C_ID | Name          | City   
| 
+------+---------------+-------
---+ 
| 1    | A K Ltd       | Delhi  
| 
| 2    | V K Associate | Mumbai 
| 
| 3    | R K India     | 
Banglore | 
| 4    | R S P Ltd     | 
Kolkata  | 
| 5    | A T Ltd       | Delhi  
| 
| 6    | D T Info      | Delhi  
| 
+------+---------------+-------
---+ 
6 rows in set (0.00 sec) 
mysql SELECT  FRJM Products; 
+---------+-------------+------
+ 
| Prod_ID | Prod_Detail | C_ID 
| 
+---------+-------------+------
+ 
| 111     | Monitor     | 1    
| 
| 112     | Processor   | 2    
| 
| 113     | Keyboard    | 2    
| 
| 114     | Mouse       | 3    
| 
| 115     | CPU         | 5    
| 
+---------+-------------+------
+ 
5 rows in set (0.00 sec) 
         
Example : Create 'iew Statement 
           
mysql> CREATE VIEW Supp_Client 
AS 
    -> SELECT * FROM Client 
    -> WHERE C_ID IN ( 
    -> SELECT C_ID FROM 
Products) 
    -> WITH CHECK OPTION; 
Query OK, 0 rows affected (0.05 
sec) 
mysql SELECT  FRJM 
Supp_Client; 
+------+---------------+-------
---+ 
| C_ID | Name          | City    
| 
+------+---------------+-------
---+ 
| 1    | A K Ltd       | Delhi   
| 
| 2    | V K Associate | Mumbai  
| 
| 3    | R K India     | 
Banglore | 
| 5    | A T Ltd       | Delhi   
| 
+------+---------------+-------
---+ 
4 rows in set (0.03 sec) 
In the Iollowing example we include the WHERE clause with the select statement oI view. Then 
MySQL adds this condition to the VIEW deIinition when executing the statement Ior Iurther 
restricting the result. Example :  
mysql> SELECT * FROM Supp_Client 
WHERE City='Delhi'; 
+------+---------+-------+ 
| C_ID | Name    | City  | 
+------+---------+-------+ 
| 1    | A K Ltd | Delhi | 
| 5    | A T Ltd | Delhi | 
+------+---------+-------+ 
2 rows in set (0.04 sec) 
LTER 'IEW Statement 
By the ALTER VIEW Statement we can change the deIinition oI a view. This statement is useIul 
to modiIy a view without dropping it. ALTER VIEW statement syntax is similar to CREATE 
VIEW Statement and eIIect is same as the CREATE OR REPLACE VIEW. The general syntax 
oI ALTER VIEW Statement is : 
        LTER 'IEW view_name column_list)] WITH ENCRYPTION] S 
select_statement WITH CHECK OPTION] 
In the Iollowing example we are altering the view deIinition that we have created above. In this 
we add one more column by the name oI ProdDetail oI Products table. Example oI Altering the 
View Statement :  
mysql> ALTER VIEW Supp_Client AS 
    -> SELECT Client.C_ID, 
Client.Name, Client.City, 
    -> Products.Prod_Detail from 
Client, Products 
    -> WHERE 
Client.C_ID=Products.C_ID; 
Query OK, 0 rows affected (0.01 sec) 
mysql SELECT  FRJM Supp_Client; 
+------+---------------+----------+---
----------+ 
| C_ID | Name          | City     | 
Prod_Detail | 
+------+---------------+----------+---
----------+ 
| 1    | A K Ltd       | Delhi    | 
Monitor     | 
| 2    | V K Associate | Mumbai   | 
Processor   | 
| 2    | V K Associate | Mumbai   | 
Keyboard    | 
| 3    | R K India     | Banglore | 
Mouse       | 
| 5    | A T Ltd       | Delhi    | 
CPU         | 
+------+---------------+----------+---
----------+ 
5 rows in set (0.02 sec) 
DROP 'IEW Statement 
For dropping a view you can use the DROP VIEW Statement. When view is dropped but it has 
no eIIect on the underlying tables. AIter dropping a view iI you issue any query that reIerence a 
dropped view then you get an error message. But dropping a table that reIerence any view does 
not drop the view automatically you have to dropt the view explicitly. The general syntax oI 
DROP VIEW Statement is : 
        DROP 'IEW view_name; 
In the Iollowing example we are dropping the view that we have created above. Example oI 
Dropping the View Statement :  
mysql> DROP VIEW Supp_Client; 
Query OK, 0 rows affected (0.00 sec) 
   
mysql SELECT  FRJM Supp_Client; 
ERRJR 1146 (42S02): Table 
'employee.supp_client' doesn't exist 
 
Stored Procedures and Functions 
 
SLored 8ouLlnes (9rocedures and luncLlons) are supporLed ln verslon MySCL 30 SLored 9rocedure ls a seL of 
sLaLemenLs whlch allow ease and flexlblllLy for a programmer because sLored procedure ls easy Lo execuLe Lhan 
relssulng Lhe number of lndlvldual S  
  Stored Routines (Procedures and Functions) are supported in version MySQL 5.0. Stored 
Procedure is a set oI statements, which allow ease and Ilexibility Ior a programmer because 
stored procedure is easy to execute than reissuing the number oI individual SQL statements. 
Stored procedure can call another stored procedure also. Stored Procedure can very useIul 
where multiple client applications are written in diIIerent languages or it can be work on 
diIIerent platIorms but they need to perIorm the same database operations. 
Store procedure can improve the perIormance because by using the stored procedure less 
inIormation needs to be sent between the server and the client. It increase the load on the 
database server because less work is done on the client side and much work is done on the 
server side. 
CT CD ntax 
The general syntax oI Creating a Stored Procedure is : 
        CRETE PROCEDURE proc_name proc_parameter......]]) routine_body 
proc_name : procedure name 
proc_parameter : | IN , OUT , INOUT | paramname type 
routine_body : Valid SQL procedure statement 
The parameter list is available with in the parentheses. Parameter can be declared to use any 
valid data type, except that the COLLATE attribute cannot be used. By deIault each parameter 
is an IN parameter. For speciIying other type oI parameter used the OUT or INOUT keyword 
beIore the parameter name. 
An IN parameter is used to pass the value into a procedure. The procedure can be change the 
value but when the procedure return the value then modiIication is not visible to the caller. An 
OUT parameter is used to pass the value Irom the procedure to the caller but its visible to the 
caller. An INOUT parameter is initialized by the caller and it can be modiIied by the 
procedure, and any change made by the procedure is visible to the caller. 
For each OUT or INOUT parameter you have to pass a user deIined variable because then 
the procedure returns the value then only you can obtain it values. But iI you invoking the 
procedure Irom the other procedure then you can also pass a routine parameter or variable as 
an IN or INOUT parameter. 
The routinebody contains the valid SQL procedure statement that can be a simple statement 
like SELECT or INSERT or they can be a compound statement written using BEGIN and 
END. Compound statement can consists declarations, loops or other control structure. 
Now we are describing you a example oI a simple stored procedure which uses an OUT 
parameter. It uses the mysql client delimiter command Ior changing the statement delimiter 
Irom ; to // till the procedure is being deIined. Example : 
mysql> delimiter // 
mysql> CREATE PROCEDURE Sproc(OUT p1 
INT) 
    -> SELECT COUNT(*) INTO p1 FROM Emp; 
    -> // 
Query OK, 0 rows affected (0.21 sec) 
 
mysql delimiter ; 
mysql CALL Sproc(@a); 
Query JK, 0 rows affected (0.12 sec) 
mysql select @a; 
+------+ 
| @a   | 
+------+ 
| 5    | 
+------+ 
1 row in set (0.00 sec) 
CT FCT ntax 
The general syntax oI Creating a Function is : 
        CRETE FUNCTION func_name func_parameter,...]]) RETURNS type 
routine_body  
Iuncname : Function name 
Iuncparameter : paramname type 
type : Any valid MySQL datatype 
routinebody : Valid SQL procedure statement 
The RETURN clause is mandatory Ior FUNCTION. It used to indicate the return type oI 
Iunction. 
Now we are describing you a simple example a Iunction. This Iunction take a parameter and it 
is used to perIorm an operation by using an SQL Iunction and return the result. In this 
example there is no need to use delimiter because it contains no internal ; statement delimiters. 
Example : 
mysql> CREATE FUNCTION func(str 
CHAR(20)) 
    -> RETURNS CHAR(50) 
    -> RETURN CONCAT('WELCOME TO, 
',str,'!'); 
Query OK, 0 rows affected (0.00 sec) 
mysql SELECT func('RoseIndia'); 
+------------------------+ 
| func('RoseIndia')      | 
+------------------------+ 
| WELCJME TJ, RoseIndia! | 
+------------------------+ 
1 row in set (0.00 sec) 
T CD and T FCT ntax 
For creating the procedure or Iunction we used the CREATE PROCEDURE , FUNCTION 
statement and Ior altering the procedure we used the ALTER PROCEDURE , FUNCTION 
statement. Alter Procedure statement is used to change access permissions that preserves by 
the procedure. And ALTER PROCEDURE needs the use oI the same encryption and 
recompile option as the original CREATE PROCEDURE command. ALTER PROCEDURE , 
FUNCTION statement can be used Ior renaming the stored procedure or Iunction and Ior 
changing it characteristics also. We can speciIy the more than one changes also in an ALTER 
PROCEDURE , FUNCTION statement. But Ior this you required the ALTER ROUTINE 
privilege. 
        LTER PROCEDURE [ FUNCTION] proc_name [ func_name] characteristic ...] 
characteristic: SQL SECURITY DEFINER [ IN'OKER][ COMMENT 'string' 
Example :   
mysql ALTER PRJCEDURE Sproc SQL 
SECURITY DEFINER; 
Query JK, 0 rows affected (2.00 sec) 
With the ALTER PROCEDURE Statement you can change only the characteristics and iI you 
want to change in statement list then you have to DROP the procedure and CREATE again. 
D CD and D FCT ntax 
DROP PROCEDURE , FUNCTION Statement is used to drop a Procedure or Function. But 
Ior dropping them you must have the ALTER ROUTINE privilege. II IF NOT EXISTS clause 
is available then its prevents you Irom occurring an error when the procedure or Iunction does 
not exist its produced only a warning. 
        DROP PROCEDURE [ FUNCTION] IF EISTS] proc_name [ func_name];  
The Iollowing example shows you a syntax oI Dropping procedure and Iunction iI it exists : 
Examples : 
mysql DRJP FUNCTIJN IF EXISTS func; 
Query JK, 0 rows affected (0.30 sec) 
mysql DRJP PRJCEDURE IF EXISTS Sproc; 
Query JK, 0 rows affected (0.00 sec) 
But when you want to drop the procedure and Iunction that does not exists it shows you only a 
warning. Examples : 
mysql DRJP FUNCTIJN IF EXISTS func; 
Query JK, 0 rows affected, 1 warning 
(0.02 sec) 
mysql DRJP PRJCEDURE IF EXISTS 
Sproc; 
Query JK, 0 rows affected, 1 warning 
(0.00 sec) 
C tatement ntax 
The CALL statement is used to call a procedure, which has been deIined previously. CALL 
can return the values to its caller through its parameters that are declared as OUT or INOUT 
parameters. This statement is also used to returns the number oI rows aIIected that a client 
program can obtain at the SQL level by calling the ROWCOUNT(). The general syntax oI 
CALL Statement is : 
        CLL p_nameparameter,...]]) 
The Iollowing example shows you the use oI CALL statement. Example : 
mysql delimiter // 
mysql CREATE PRJCEDURE Sp1(JUT p VARCHAR(20),JUT 
p1 VARCHAR(20),IN p2 INT) 
    - SELECT Ename,City INTJ p,p1 FRJM Emp WHERE 
Eid=p2; 
    - // 
Query JK, 0 rows affected (0.02 sec) 
mysql delimiter ; 
mysql> CALL Sp1(@Name,@City,1); 
Query OK, 0 rows affected (0.00 sec) 
mysql> SELECT @Name,@City; 
+-------+-------+ 
| @Name | @City | 
+-------+-------+ 
| Rahul | Delhi | 
+-------+-------+ 
1 row in set (0.00 sec) 
D Compound tatement ntax 
Stored Procedure or Functions can contain multiple statement by using the BEGIN...END 
compound statement. The general syntax oI BEGIN....END compound statement is : 
        BEIN statement_list] END 
statementlist means a list oI one or more statements but each statements must be terminated 
by a semicolon. statementlist is optional means compound statement can be empty. 
In the Iollowing example Iirstly we are inserting the record and then we are selecting the 
record. Example : 
mysql SELECT  FRJM Emp; 
+-----+---------+----------+-------------------+--
------+-------+ 
| Eid | Ename   | City     | Designation       | 
Salary | Perks | 
+-----+---------+----------+-------------------+--
------+-------+ 
| 1   | Rahul   | Delhi    | Manager           | 
10300  | 853   | 
| 2   | Gaurav  | Mumbai   | Assistant Manager | 
10300  | 853   | 
| 3   | Chandan | Banglore | Team Leader       | 
15450  | 999   | 
| 5   | Tapan   | Pune     | Developer         | 
20600  | 1111  | 
| 6   | Amar    | Chennai  | Developer         | 
16000  | 1124  | 
| 7   | Santosh | Delhi    | Designer          | 
10000  | 865   | 
+-----+---------+----------+-------------------+--
------+-------+ 
6 rows in set (0.00 sec) 
mysql> delimiter // 
mysql> CREATE PROCEDURE Proc(OUT p VARCHAR(20), 
OUT p1 VARCHAR(20),IN p2 INT) 
    -> BEGIN 
    -> INSERT INTO Emp 
VALUES(p2,'Suman','Pune','Web 
Designer',20000,965); 
    -> SELECT Ename,City INTO p,p1 FROM Emp WHERE 
Eid=p2; 
    -> END 
    -> // 
Query OK, 0 rows affected (0.01 sec) 
mysql delimiter ; 
mysql CALL Proc(@Name,@City,8); 
Query JK, 0 rows affected (0.03 sec) 
mysql SELECT @Name,@City; 
+-------+-------+ 
| @Name | @City | 
+-------+-------+ 
| Suman | Pune  | 
+-------+-------+ 
1 row in set (0.00 sec) 
mysql SELECT  FRJM Emp; 
+-----+---------+----------+-------------------+--
------+-------+ 
| Eid | Ename   | City     | Designation       | 
Salary | Perks | 
+-----+---------+----------+-------------------+--
------+-------+ 
| 1   | Rahul   | Delhi    | Manager           | 
10300  | 853   | 
| 2   | Gaurav  | Mumbai   | Assistant Manager | 
10300  | 853   | 
| 3   | Chandan | Banglore | Team Leader       | 
15450  | 999   | 
| 5   | Tapan   | Pune     | Developer         | 
20600  | 1111  | 
| 6   | Amar    | Chennai  | Developer         | 
16000  | 1124  | 
| 7   | Santosh | Delhi    | Designer          | 
10000  | 865   | 
| 8   | Suman   | Pune     | Web Designer      | 
20000  | 965   | 
+-----+---------+----------+-------------------+--
------+-------+ 
7 rows in set (0.00 sec) 
DC tatement ntax 
The DECLARE statement is used to speciIy the various items. Its allowed only inside the 
BEGIN..END compound statements. Declarations must Iollow the order like Cursor must be 
declare beIore declaring handlers and the variables and conditions must be declare beIore 
declaring either handler or cursors 
DECLRE Local 'ariable 
The general syntax oI declaring local variable is : 
        DECLRE var_name,...] type DEFULT value] 
DECLARE statement is used Ior declaring the local variables. DEFAULT clause is used Ior 
providing a deIault value to the variable but iI this clause is missing then the initial value is 
NULL. Local variable scope is limited within the BEGIN..END compound block.  
'ariable SET Statement 
The general syntax oI Variable SET statement is: 
        SET var_name  expr , var_name  expr] ... 
In stored procedure SET statement is extended version oI general SET statement and its 
implements as part oI the preexisting SET Syntax. It allows an extended syntax oI ja , 
kb... where diIIerent variables types (like local variables, global variables etc) can be 
mixed.  
SELECT......INTO Statement Syntax 
The general syntax oI SELECT....INTO Statement is: 
        SELECT column_name1,column_name2...] INTO var_name1,var_name2....] 
table_expr 
This SELECT statement is used to store selected columns into variables. But by this we can 
retrieve only single row. The number oI columns and the number oI variable name must be 
same in this statement. 
In the Iollowing example we are demonstrating you the use oI all above three statement. 
Example : 
mysql>  delimiter // 
mysql> CREATE PROCEDURE Sproced(OUT p 
VARCHAR(20),OUT p1 VARCHAR(20),IN p2 INT) 
    -> BEGIN 
    -> DECLARE a VARCHAR(20); 
    -> DECLARE b INT; 
    -> SET b=p2; 
    -> SET a='Dev%'; 
    -> SELECT * FROM Emp WHERE Designation LIKE a; 
    -> SELECT Ename,City INTO p,p1 FROM Emp WHERE 
Eid=b; 
    -> END 
    -> // 
Query OK, 0 rows affected (0.07 sec) 
mysql delimiter ; 
mysql CALL Sproced(@Name,@City,5); 
+-----+-------+---------+-------------+--------+--
-----+ 
| Eid | Ename | City    | Designation | Salary | 
Perks | 
+-----+-------+---------+-------------+--------+--
-----+ 
| 5   | Tapan | Pune    | Developer   | 20600  | 
1111  | 
| 6   | Amar  | Chennai | Developer   | 16000  | 
1124  | 
+-----+-------+---------+-------------+--------+--
-----+ 
2 rows in set (0.05 sec) 
Query JK, 0 rows affected (0.10 sec) 
mysql SELECT @Name,@City; 
+-------+-------+ 
| @Name | @City | 
+-------+-------+ 
| Tapan | Pune  | 
+-------+-------+ 
1 row in set (0.01 sec) 
Conditions and Handlers 
Some conditions needs speciIic handling and these conditions can be related to errors or may 
be general Ilow control inside a routine. Handlers are the methods oI handling conditions that 
need to be dealt with. BeIore describing conditions and handlers lets try to produce some 
errors. Example : 
mysql INSERT INTJ Emp 
VALUES(1,'AAA','Delhi','Manager',20000,583); 
ERRJR 1062 (23000): Duplicate entry '1' for key 1 
In the above example MySQL produced an error, ERROR 1062. And the number between the 
brackets (23000) is the SQLSTATE that can be the same Ior a number oI errors. nother 
example : 
mysql INSERT INTJ Emp 
VALUES(11,NULL,'Delhi','Manager',20000,583); 
ERRJR 1048 (23000): Column 'Ename' cannot be null 
But in this example we get a diIIerent error number 1048 but the same SQLSTATE. II these 
errors occur in our Iunctions and procedures then they will terminate out programs. To deal 
with these conditions we have to create a handler. The general syntax oI Handler is as Iollows: 
        DECLRE handler_type HNDLER FOR condition_value,...] statement  
Firstly we have to use DECLRE Ior creating a handler, handler_type can be oI the 
Iollowing like CONTINUE, EIT or UNDO. II we are using CONTINUE the the program 
will carry on the process aIter the handler has been called. When we are using EXIT then the 
program will end immediately. The UNDO is used on transactional tables to rollback work 
carried out up to that point. HNDLER FOR tells the compiler, we are declaring a handler. 
Condition_value is used so that the handler Iires when a deIine conditions met. The 
statement is section oI code that we want to execute when the handler is Iired.  
Now we are creating a simple procedure and in this we are trying to deal with duplicate entry. 
In this procedure we are not handling the error. Example : 
mysql delimiter // 
mysql CREATE PRJCEDURE hproc(JUT p VARCHAR(30)) 
    - BEGIN 
    - INSERT INTJ Emp 
VALUES(1,'aaa','Delhi','Manager',20000,535); 
    - SET p='Can not Insert'; 
    - END 
    - // 
Query JK, 0 rows affected (0.19 sec) 
mysql delimiter ; 
mysql CALL hproc(@b); 
ERRJR 1062 (23000): Duplicate entry '1' for key 1 
mysql SELECT @b; 
+------+ 
| @b   | 
+------+ 
|      | 
+------+ 
1 row in set (0.02 sec) 
In the above example we got the error message but our parameter is empty because error 
stopped the procedure. But iI we wouldn`t want that then we must use handler. In the 
Iollowing example lets include a handler to the procedure. Example :  
mysql delimiter // 
mysql CREATE PRJCEDURE hproc(JUT p VARCHAR(35)) 
    - BEGIN 
    -> DECLARE CONTINUE HANDLER FOR SQLSTATE 
'23000' SET @b=' With Errors'; 
    - INSERT INTJ Emp 
VALUES(1,'AAA','Delhi','Manager',20000,698); 
    - SET p=CJNCAT('Can not Insert ',@b); 
    - END 
    - // 
Query JK, 0 rows affected (0.00 sec) 
mysql delimiter ; 
mysql CALL hproc(@c); 
Query JK, 0 rows affected (0.00 sec) 
mysql SELECT @c; 
+---------------------------+ 
| @c                        | 
+---------------------------+ 
| Can not Insert With Errors| 
+---------------------------+ 
1 row in set (0.00 sec) 
Now in this example we didn`t get the error message and our parameter also passed out the 
value because when the error occurred then handler deal with the problem and continue the 
procedure processing. 
In the above example we are using a handler to deal with SQLSTATE but the handler can deal 
with a set oI diIIerent errors. Now in the Iollowing example we are taking the diIIerent error 
numbers but they had the same SQLSTATE that situation we looked at earlier. Example : 
mysql delimiter // 
mysql CREATE PRJCEDURE hproc(JUT p VARCHAR(35)) 
    - BEGIN 
    -> DECLARE CONTINUE HANDLER FOR 1062 SET @b=' 
With Error 1062'; 
    -> DECLARE CONTINUE HANDLER FOR 1048 SET @b=' 
With Error 1048'; 
    -> INSERT INTO Emp 
VALUES(1,'AAA','Delhi','Manager',20000,698); 
    - SET p=CJNCAT('Can not Insert',@b); 
    - END 
    - // 
Query JK, 0 rows affected (0.00 sec) 
mysql delimiter ; 
mysql CALL hproc(@c); 
Query JK, 0 rows affected (0.00 sec) 
mysql SELECT @c; 
+--------------------------------+ 
| @c                             | 
+--------------------------------+ 
| Can not Insert With Error 1062 | 
+--------------------------------+ 
1 row in set (0.01 sec) 
mysql DRJP PRJCEDURE hproc; 
Query JK, 0 rows affected (0.09 sec) 
mysql delimiter // 
mysql CREATE PRJCEDURE hproc(JUT p VARCHAR(35)) 
    - BEGIN 
    -> DECLARE CONTINUE HANDLER FOR 1062 SET @b=' 
With Error 1062'; 
    -> DECLARE CONTINUE HANDLER FOR 1048 SET @b=' 
With Error 1048'; 
    -> INSERT INTO Emp 
VALUES(11,NULL,'Delhi','Manager',20000,698); 
    - SET p=CJNCAT('Can not Insert',@b); 
    - END 
    - // 
Query JK, 0 rows affected (0.09 sec) 
mysql delimiter ; 
mysql CALL hproc(@c); 
Query JK, 0 rows affected (0.04 sec) 
mysql SELECT @c; 
+--------------------------------+ 
| @c                             | 
+--------------------------------+ 
| Can not Insert With Error 1048 | 
+--------------------------------+ 
1 row in set (0.03 sec) 
In the above section we have seen how we can handle various conditions. Additionally 
MySQL allows us to deIine our own named conditions. But these conditions only be linked to 
SQLSTATE values or mysqlerrorcode. Syntax Ior creating a conditions is as Iollows : 
        DECLRE condition_name CONDITION FOR condition_value  
condition_value can be the SQLSTATE |value| or mysqlerrorcode. In the Iollowing 
example we are describing how we can create a condition and how we can use it within a 
handler. Example :  
mysql delimiter // 
mysql CREATE PRJCEDURE condproc(JUT p 
VARCHAR(35)) 
    - BEGIN 
    -> DECLARE duplicate CONDITION FOR SQLSTATE 
'23000'; 
    -> DECLARE CONTINUE HANDLER FOR duplicate SET 
@b=' With Duplicate Error'; 
    -> INSERT INTO Emp 
VALUES(1,'AAA','Delhi','Manager',20000,568); 
    - SET p=CJNCAT('Can not Insert',@b); 
    - END 
    - // 
Query JK, 0 rows affected (0.12 sec) 
mysql CALL condproc(@c); 
    - // 
Query JK, 0 rows affected (0.14 sec) 
mysql delimiter ; 
mysql CALL condproc(@c); 
Query JK, 0 rows affected (0.00 sec) 
mysql SELECT @c; 
+-------------------------------------+ 
| @c                                  | 
+-------------------------------------+ 
| Can not Insert With Duplicate Error | 
+-------------------------------------+ 
1 row in set (0.00 sec) 
In the Iollowing example we are using error code. Example :  
mysql delimiter // 
mysql CREATE PRJCEDURE condproc(JUT p 
VARCHAR(35)) 
    - BEGIN 
    -> DECLARE not_null CONDITION FOR 1048; 
    -> DECLARE CONTINUE HANDLER FOR not_null SET 
@b=' With Not Null Error'; 
    -> INSERT INTO Emp 
VALUES(11,NULL,'Delhi','Manager',20000,698); 
    - SET p=CJNCAT('Can not Insert',@b); 
    - END 
    - // 
Query JK, 0 rows affected (0.00 sec) 
mysql delimiter ; 
mysql CALL condproc(@c); 
Query JK, 0 rows affected (0.00 sec) 
mysql SELECT @c; 
+------------------------------------+ 
| @c                                 | 
+------------------------------------+ 
| Can not Insert With Not Null Error | 
+------------------------------------+ 
1 row in set (0.00 sec) 
   
 
 
Writing Subqueries 
   A subquery can be deflned as a query wlLhln a query ln oLher words any query resulLs LhaL we reuse ln anoLher 
query Subquery ls known as nesLee querles or subselecLs also Subquerles don?L lnclude any new funcLlonallLy buL 
Lhe querles are more readable  
  A subquery can be deIined as a query within a query. In other words, any query results that we 
reuse in another query. Subquery is known as nestee queries or subselects also. Subqueries 
don`t include any new Iunctionality but the queries are more readable with using subqueries 
rather than oI joins. 
We will describe you the subqueries with the help oI Iollowing tables :    
mysql SELECT  FRJM Client; 
+------+---------------+----------+ 
| C_ID | Name          | City     | 
+------+---------------+----------+ 
| 1    | A K Ltd       | Delhi    | 
| 2    | V K Associate | Mumbai   | 
| 3    | R K India     | Banglore | 
| 4    | R S P Ltd     | Kolkata  | 
| 5    | A T Ltd       | Delhi    | 
| 6    | D T Info      | Delhi    | 
+------+---------------+----------+ 
6 rows in set (0.08 sec) 
mysql SELECT  FRJM Products; 
+---------+-------------+------+----------+ 
| Prod_ID | Prod_Detail | C_ID | price    | 
+---------+-------------+------+----------+ 
| 111     | Monitor     | 1    | 7000.00  | 
| 112     | Processor   | 2    | 11000.00 | 
| 113     | Keyboard    | 2    | 1200.00  | 
| 114     | Mouse       | 3    | 500.00   | 
| 115     | CPU         | 5    | 15500.00 | 
+---------+-------------+------+----------+ 
5 rows in set (0.00 sec) 
There are 3 basic types oI subqueries in SQL:  
O 9recate Subqueres  exLended loglcal consLrucLs ln Lhe WPL8L (and PAvlnC) clause 
O Sca|ar Subqueres  sLandalone querles LhaL reLurn a slngle value Lhey can be used anywhere 
a scalar value ls used 
O @ab|e Subqueres  querles nesLed ln Lhe l8CM clause 
All subqueries must be enclosed in parentheses.  
Predicate Subqueries 
Predicate Subqueries can be used in the HAVING and WHERE clause only because both are 
special logical construct. These subqueries must retrieve one column. 
O - Subquery 
     
1he ln subquery LesLs lf a scalar values maLch wlLh Lhe slngle query column value ln any 
subquery resulL row 1he general synLax ls  
        Ia|ue_1 -@ - %query_1)  
In the Iollowing example we are getting the list oI clients that are available in Products 
table also. Example :  
mysql SELECT  FRJM Client 
WHERE C_ID IN 
    - (SELECT C_ID FRJM 
Products); 
+------+---------------+-------
---+ 
| C_ID | Name          | City   
| 
+------+---------------+-------
---+ 
| 1    | A K Ltd       | Delhi  
| 
| 2    | V K Associate | Mumbai 
| 
| 3    | R K India     | 
Banglore | 
| 5    | A T Ltd       | Delhi  
| 
+------+---------------+-------
---+ 
4 rows in set (0.00 sec) 
 
ln Lhe followlng example we are geLLlng Lhe llsL of cllenLs LhaL are noL avallable ln 9roducLs 
Lable also am|e   
       
mysql SELECT  FRJM Client 
WHERE C_ID NJT IN 
    - (SELECT C_ID FRJM 
Products); 
+------+-----------+---------+ 
| C_ID | Name      | City    | 
+------+-----------+---------+ 
| 4    | R S P Ltd | Kolkata | 
| 6    | D T Info  | Delhi   | 
+------+-----------+---------+ 
2 rows in set (0.01 sec) 
          
O ;uantfe Subqueres  
           
A quanLlfled subquery can use Lhe all comparlson operaLors for several Lypes of LesLs 1he 
general synLax ls  
        Ia|ue_1 ||||| - |  | S, %query_1) 
      
1he comparlson operaLor ls used Lo compare value_1 Lo Lhe slngle query column value from 
each subquery resulL row lf we are uslng ALL clause Lhen musL maLch Lhe all rows ln 
subquery or subquery musL be empLy lf we are uslng An? or SCML clause Lhen musL maLch 
aL leasL one row ln Lhe subquery am|e   
       
mysql SELECT  FRJM Client WHERE C_ID= 
ANY(SELECT C_ID FRJM Products); 
+------+---------------+----------+ 
| C_ID | Name          | City     | 
+------+---------------+----------+ 
| 1    | A K Ltd       | Delhi    | 
| 2    | V K Associate | Mumbai   | 
| 3    | R K India     | Banglore | 
| 5    | A T Ltd       | Delhi    | 
+------+---------------+----------+ 
4 rows in set (0.00 sec) 
       
O Exists Subqueries 
      
The EXISTS subquery is used to tests whether a subquery returns at least one row or a 
qualiIying row exists. The general syntax is : 
        Exists query_1) 
      
Any EXISTS subquery should contain an outer reIerence. It must be a correlated 
subquery. Example :  
mysql SELECT  FRJM Client 
    - WHERE EXISTS 
    - (SELECT  FRJM Products WHERE 
Client.C_ID=Products.C_ID); 
+------+---------------+----------+ 
| C_ID | Name          | City     | 
+------+---------------+----------+ 
| 1    | A K Ltd       | Delhi    | 
| 2    | V K Associate | Mumbai   | 
| 3    | R K India     | Banglore | 
| 5    | A T Ltd       | Delhi    | 
+------+---------------+----------+ 
4 rows in set (0.00 sec) 
Scalar Subqueries 
The Scalar Subquery is a subquery which returns a single value. A Scalar subquery can be 
used almost anywhere a single column value can be used. The subquery have to reIerence 
only one column in the select list. It must not retrieve more than one row. When subquery 
retrieve one row then the value oI select list column becomes the value oI the Scalar 
Subquery. Example :  
mysql SELECT (SELECT Name FRJM Client WHERE 
C_ID=1); 
+----------------------------------------+ 
| (SELECT Name FRJM Client WHERE C_ID=1) | 
+----------------------------------------+ 
| A K Ltd                                | 
+----------------------------------------+ 
1 row in set (0.00 sec) 
mysql SELECT (SELECT C_ID FRJM Products WHERE 
C_ID=2) FRJM Client; 
ERRJR 1242 (21000): Subquery returns more than 1 
row 
mysql SELECT (SELECT C_ID FRJM Products WHERE 
C_ID=1) FRJM Client; 
+------------------------------------------+ 
| (SELECT C_ID FRJM Products WHERE C_ID=1) | 
+------------------------------------------+ 
| 1                                        | 
| 1                                        | 
| 1                                        | 
| 1                                        | 
| 1                                        | 
| 1                                        | 
+------------------------------------------+ 
6 rows in set (0.01 sec) 
Table Subqueries  
Table subqueries are used in the FROM Clause , replace the table name. These subqueries can 
have correlation name also. Example :   
mysql SELECT Client.,Price 
    - FRJM Client, Products 
    - WHERE Client.C_ID=Products.C_ID 
    - AND Price1000; 
+------+---------------+--------+----------+ 
| C_ID | Name          | City   | Price    | 
+------+---------------+--------+----------+ 
| 1    | A K Ltd       | Delhi  | 7000.00  | 
| 2    | V K Associate | Mumbai | 11000.00 | 
| 2    | V K Associate | Mumbai | 1200.00  | 
| 5    | A T Ltd       | Delhi  | 15500.00 | 
+------+---------------+--------+----------+ 
4 rows in set (0.06 sec) 
Using Single 'alue Subqueries 
Firstly we will start with a simple query :  
mysql SELECT MAX(Price) FRJM 
Products; 
+------------+ 
| MAX(Price) | 
+------------+ 
| 15500.00   | 
+------------+ 
1 row in set (0.60 sec) 
The above example retrieve only a single value and its representing the maximum Price oI the 
Product. In this example we used a MySQL Function MAX() that Iinds the greatest values in a 
speciIied column.  
Single  value subqueries is used to return a single column value and then they are typically 
used Ior comparison. For Example :  
mysql> SELECT * FROM Client c,Products p WHERE 
c.C_ID=p.C_ID 
    -> AND p.Price=(SELECT MAX(Price) FROM 
Products); 
+------+---------+-------+---------+-----------
--+------+----------+ 
| C_ID | Name    | City  | Prod_ID | 
Prod_Detail | C_ID | price    | 
+------+---------+-------+---------+-----------
--+------+----------+ 
| 5    | A T Ltd | Delhi | 115     | CPU        
| 5    | 15500.00 | 
+------+---------+-------+---------+-----------
--+------+----------+ 
1 row in set (0.02 sec) 
In the above example we are getting the detail oI products that have the highest price and the 
client details also.