SlideShare a Scribd company logo
1 of 110
UNIT II
SQL and PL/SQL
SQL
• Structured Query Language or SQL is a standard computer
language for accessing and manipulating database systems.
• SQL comprises one of the fundamental building blocks of
modern database architecture. SQL defines methods using
which user can create and manipulate databases on all major
platforms.
• SQL is the standard language for Relational Database System.
All the Relational Database Management Systems (RDMS) like
MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL
Server use SQL as their standard database language.
SQL HISTORY
1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of
relational databases. He described a relational model for
databases.
1974 − Structured Query Language appeared.
1978 − IBM worked to develop Codd's ideas and released a
product named System/R.
1986 − IBM developed the first prototype of relational database
and standardized by ANSI. The first relational database was
released by Relational Software which later came to be known
as Oracle.
Characteristics of SQL
• SQL is an ANSI and ISO standard computer language for
creating and manipulating databases.
• SQL allows the user to create, update, delete, and
retrieve data from a database.
• SQL is very simple and easy to learn.
• SQL works with database programs like DB2, Oracle,
MS Access, Sybase, MS SQL Sever etc.
ADVANTAGES OF SQL
• High speed
• No coding needed
• Well defined standards
• Portability
• Interactive language
• Multiple data view
SQL DATATYPES
SQL Commands
SQL Commands
Data Definition Language (DDL)
• DDL changes the structure of the table like creating a table,
deleting a table, altering a table, etc.
Data Manipulation Language
• DML commands are used to modify the database. It is
responsible for all form of changes in the database.
Data Control Language
• DCL commands are used to grant and take back authority from
any database user.
Transaction Control Language
• TCL commands can only use with DML commands like INSERT,
DELETE and UPDATE only.
Introduction toMySQL
MySQL is the most popular Open Source Relational SQL
Database Management System. MySQL is one of the
best RDBMS being used for developing various web-
based software applications. MySQL is developed,
marketed and supported by MySQL AB, which is a
Swedish company.
MySQLDatabase
• MySQL is an open-source database
• MySQL is customizable because it is an open source database
• MySQL is quicker than other databases so it can work well even
with
the large data set.
• MySQL supports many languages like PHP, PERL, C, C++, JAVA,
etc.
• MySQL uses a standard form of the well-known SQL data
language.
• MySQL supports large databases, up to 50 million rows or more
in a table. The default file size limit for a table is 4GB, but you
can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
MySQL Features
• Relational Database Management System (RDBMS): MySQL is a relational database management
system.
• Easy to use: MySQL is easy to use. You have to get only the basic knowledge of SQL. You can build and
interact with MySQL with only a few simple SQL statements.
• It is secure: MySQL consist of a solid data security layer that protects sensitive data from intruders.
Passwords are encrypted in MySQL.
• Client/ Server Architecture: MySQL follows a client /server architecture. There is a database server
(MySQL) and arbitrarily many clients (application programs), which communicate with the server; that is,
they query data, save changes, etc.
• Free to download: MySQL is free to use and you can download it from MySQL official website.
• It is scalable: MySQL can handle almost any amount of data, up to as much as 50 million rows or more.
The default file size limit is about 4 GB. However, you can increase this number to a theoretical limit of 8
TB of data.
• Compatible on many operating systems: MySQL is compatible to run on many operating systems,
• Allows roll-back: MySQL allows transactions to be rolled back, commit and crash recovery.
• High Performance: MySQL is faster, more reliable and cheaper because of its unique storage engine
architecture.
• High Flexibility: MySQL supports a large number of embedded applications which makes MySQL very
flexible.
• High Productivity: MySQL uses Triggers, Stored procedures and views which allows the developer to give
a higher productivity.
MySQL DataTypes
Categaries Data Types
Numeric Data Type INT, FLOAT(m,d), DOUBLE(m,d),
DECIMAL(m,d)
Date and Time Data Type: DATE, DATETIME,TIME,
TIMESTAMP,YEAR
String Data Types: CHAR,VARCHAR,TEXT,
LONGTEXT,BINARY
Large Object Data Types (LOB)
Data Types:
TINYBLOB, BLOB, MEDIUMBLOB,
LONGTEXT
Command to Install MySQLin
ubuntu
• sudo apt-get install mysql-server
How to startMySQL
• First install mysql then write following command on command
prompt
•mysql -u root –p
• Then Enter Password, it will show you MySQL prompt
• -u -username -p -password
Database relatedcommands-
CREATE
• Syntax to create database
• CREATE DATABASE database_name;
• Example:
• Let's take an example to create a database name "employees"
• CREATE DATABASE employees;
Database relatedcommands-
SHOW & USE
• You can check the created database by the following query:
• SHOW DATABASES;
• You can use SQL command USE to select a particular database.
• Syntax:
• USE database_name;
• Example:
• Let's take an example to use a database name "Students".
• USE customers;
Database relatedcommands-
DROP
• You can drop/delete/remove a MySQL database easily with
the MySQL command. You should be careful while deleting
any database because you will lose your all the data available
in your database.
• Syntax:
• DROP DATABASE database_name;
• Example:
• Let's take an example to drop a database name "employees"
• DROP DATABASE employees;
How to Connect remoteMySQL
server
• To connect remote MySQL server, use the -h (host) with IP
Address of remote machine.
• # mysqladmin -h ip- address -u root -p
Table
RollNo Name Address
1 Sonali Nashik
2 Yug Pune
Table Name: Student
DDL- Data DefinitionLanguage
• DDL statements or commands are used to define and modify
the database structure of your tables or schema.
Some commands of DDL are:
• CREATE – to create table (objects) in the database
• ALTER – alters the structure of the database
• DROP – delete table from the database
• TRUNCATE – remove all records from a table, including all
spaces allocated for the records are removed
• COMMENT – add comments to the data dictionary
• RENAME – rename a table
DDL Commands forTable
•Create table
•Show tables
•Describe table
•Alter table
•Truncate table
•Drop table
•Rename
DDL Commands forTable
•Create table
• Syntax
Create table table_name (Col_name1
data_type(Size) , Col_name2
data_type(Size),…))
• Example
Create table Stud(rno number(4),name
varchar2(20), DOB date));
DDL Commands forTable
•Describe table
•Syntax
desc table_name;
•Example
desc Stud;
DDL Commands forTable
•Show tables
This will list the tables in the current database:
• Syntax
show tables;
• Example
mysql> show tables;
customers
orders
2 rows in set (0.00 sec)
DDL Commands forTable
•Alter table (add or modify)
• Syntax
alter table table_name add/modify/drop
column_name data_type(size)
• Example
• Alter table stud add age int(3);
• Alter table stud modify name varchar2(30);
• Alter table stud modify name char(20);
• Alter table stud drop column age;
DDL Commands forTable
•Truncate Table
used to delete complete data from an existing table.
• Syntax
• TRUNCATE TABLE table_name;
• Example
mysql> TRUNCATE TABLE stud;
DDL Commands forTable
•Rename Table
used to rename table.
• Syntax
• RENAME TABLE tbl_name TO new_tbl_name
• Example
mysql> RENAME TABLE stud TO student ;
Constraints
• Constraints are the set of rules defined on tables to
ensure data integrity.
• Primary key
• Not null
• Default
• Unique
• Check
• Foreign key/reference key
Constraints-Unique
• The UNIQUE constraint in MySQL does not allow to insert a
duplicate value in a column.
• Syntax
CREATE TABLE table_name (col_name data_type (size) Unique);
• Example
• CREATE TABLE Stud (Rno number(4) Unique);
Constraints- NotNull
• A NOT NULL constraint means that a data row must have a value
for the column specified as NOT NULL.
• Syntax
CREATE TABLE table_name
(Col_name Data_type(size)not null, ... );
•Example
Create table stud
(rollno number(4) ,name varchar2(20)not null);
Constraints- Primarykey
• Each table must normally contain a column or set of columns that
uniquely identifies rows of data that are stored in the table. This
column or set of columns is referred to as the primary key.
• A table can have only one primary key.
• Multiple columns can be clubbed under a composite primary key.
• Primary key columns is combination of NOT NULL and UNIQUE.
• Syntax
CREATE TABLE table_name ( Col_name Data_type(size)CONSTRAINT
constraint_name PRIMARY KEY, ... );
• Example
• Create table stud (rollno number(4)constraint pk1 primary key,name…)
• Create table stud (rollno number(4) primary key, name ….)
Constraints-Default
• In a MySQL table, while inserting data into a table, if no value
is supplied to a column, then the column gets the value set as
DEFAULT.
• Syntax
• CREATE TABLE table_name (col_name
data_type(size) DEFAULT ‘default_value’ );
• Example
• CREATE TABLE Stud (rno number(4) ,name varchar2(20), addr
varchar(30) DEFAULT ‘Chandwad’ );
Constraints-Check
• In a MySQL table, A CHECK constraint controls the values in
the associated column. The CHECK constraint determines
whether the value is valid or not.
• Syntax
• CREATE TABLE table_name (col_name data_type(size) Check
(condition) );
• Example
• CREATE TABLE Stud (rno number(4) CHECK (rollno BETWEEN 1
AND 60));
• CREATE TABLE Stud (age number(4) CHECK (age>18));
Constraints- FOREIGNKEY
• A FOREIGN KEY in MySQL creates a link between two tables by
one specific column of both tables. The specified column in one
table must be a PRIMARY KEY and referred by the column of
another table known as FOREIGN KEY.
• Syntax
• Create table table_name(col_name data_type(size)references
table_name(col_name));
• Example
• Createtable stud1 (rollno number(4) references stud(rno));
Constraints- after tablecreation
and dropconstraint
• You can also add constraint after table creation using alter
table option
• Example
• Alter table stud add constraint prk1 primary key(rollno);
• You can also drop constraint using Drop command & name of
constraint
• Example
• Drop constraint prk1;
DDL Commands forTable
•Drop table
•Syntax
Drop table table_name;
•Example
Drop table stud;
Sequence- UsingAUTO_INCREMENT Column
AUTO_INCREMENT
Syntax
• CREATE TABLE table_name ( column1 datatype NOT NULL
AUTO_INCREMENT,….);
• ALTER TABLE table_name AUTO_INCREMENT = start_value;
Example
• CREATE TABLE Bills ( Bill_No INT(11) NOT NULL
AUTO_INCREMENT, name varchar2(20));
• ALTER TABLE Bills AUTO_INCREMENT = 1001;
Solve
• Create one table employee with fields
• Eno –primary key and apply sequence starts with 101
• Ename –not null
• Address –default ‘Pune’
• Joindate
• Post
• Create another table emp_proj with fields
• Eno- forign key
• Project_name
• Loc
• Create Index on Ename field of employee table
• Create View on employee table to show only Employee name, it’s
post and salary.
Insert - INSERTtuplesintoarelation
rollno Name Address
1 Pooja Pune
2 Amit
Where every attribute in the table is given a value
INSERT INTO tablename
VALUES (attr1_value, attr2_value, ... attrn_value)
Where every attribute in the table is has not a value then it considered as NULL.
INSERT INTO tablename (attrx, ... , attry)
VALUES (attrx_value, ... , attry_value)
Example:
•Insert into Stud values (1,’Pooja’, ‘Pune’)
•Insert into Stud (rollno,name) values (2, ‘Amit’)
The output of "Stud" table after inserting above 2 rows
Delete –DELETEtuplesfromrelation
• Syntax
• DELETE FROM tablename <WHERE condition>
• It removes zero, one or many tuples; The WHERE clause is optional;
if it is left out all tuples are removed, but the table still exists; it is
empty.
• Example:
1> DELETE FROM Stud WHERE Address =
'Pune';
( Only delete roes that satisfy the condition)
2> DELETE FROM Stud;
• (Delete all rows)
Update- UPDATEofoneormoreselected tuples
Syntax
UPDATE tablename
SET attrx = new_value,
<WHERE condition>;
Example:
1> Update Stud Set Name= ‘Shruti’ where rollno=1
(Only name field of row having rollno as 1 will be chaged as ‘Shruti’)
2> Update Stud Set Name= ‘Shruti’
(name field of All row will be changed as ‘Shruti’)
Select- SELECTstatement retrieves datafromtable
Syntax
SELECT attribute_list
FROM table_list
<WHERE condition>;
• The attributes are those you want to see in the result,
• the tables are those required for the query,
• the condition is a boolean expression that specifies which tuples are
to be retrieved by the query.
Example:
1. Select * from Stud;
2. Select * from Stud where rno=1;
3. Select Name, Address from Stud;
4. Select Name, Address from Stud where rno=1
5. Select Name from Stud where address=‘Nashik’;
Order By- RetrievalwithorderingAscending/Descending
• The ORDER BY keyword is used to sort the result-set by a specified
column.
• The ORDER BY keyword sort the records in ascending order by
default.
• If you want to sort the records in a descending order, you can use
the DESC keyword.
Syntax
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
Example
1. Select * from Stud order by rno desc;
2. Select * from Stud order by rno ;
3. Select * from Stud order by Name;
LIKE Operator- searchforaspecified
patterninacolumn
Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
SQL Wildcards
• SQL wildcards can substitute for one or more characters
when searching for data in a database.
• SQL wildcards must be used with the LIKE operator.
Wildcard Description
% A substitute for zero or more characters
_ A substitute for exactly one character
LIKE Operator- Example
P_Id LastName Address
1 Heena Pune
2 Savita Pune
3 Sarika Bombay
SELECT LastName from Person where LastName like ‘S%’ ;
LastName
Savita
Sarika
"Persons"table
We use the following SELECT statement:
The result-set will look like this:
DISTINCT Operator
• The DISTINCT keyword can be used to return only distinct
(different) values.
Syntax
• SELECT DISTINCT column_name(s) FROM table_name
Example
• SELECT distinct(Address) from Person
• The result-set will look like this
P_Id Name Address
1 Hansen Pune
2 Svendson Pune
3 Pettersen Bombay
The "Persons" table:
Address
Pune
Bombay
IN Operator- TheINoperatorallowsyouto
specifymultiplevaluesinaWHEREclause.
Syntax
SELECT column_name(s) FROM table_name WHERE
column_name IN (value1,value2,...)
Example
SELECT * FROM Persons WHERE Address IN
('Pune','Bombay') The result-set will look like this
P_Id Name Address
1 Hansen Pune
2 Svendson Nashik
3 Pettersen Bombay
The "Persons" table:
P_Id Name Address
1 Hansen Pune
3 Pettersen Bombay
NULL Operator-
• To test if a value is NULL you cannot use =, because every
NULL is considered distinct from every other one. Must use
"IS NULL" or "IS NOT NULL“
Syntax
SELECT Attr_List FROM table_name
WHERE Attr_name IS NULL;
Example
1. SELECT * FROM Stud WHERE Address is null;
2. SELECT * FROM Stud WHERE Address is not null;
Aggregate Functions
• Aggregate /Group functions are built-in SQL
functions that operate on groups of rows and
return one value for the entire group.
• The Functions are as below:
MIN returns the smallest value in a given column
MAX returns the largest value in a given column
SUM
returns the sum of the numeric values in a given
column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the number of rows in a table
Count()- Syntax
COUNT(column_name)-The COUNT(column_name) function
returns the number of values (NULL values will not be counted)
of the specified column:
Syntax
• SELECT COUNT(column_name) FROM table_name
COUNT(*)-The COUNT(*) function returns the number of
records in a table:
Syntax
• SELECT COUNT(*) FROM table_name
Count()- Example
Consider an employee_tbl table as shown
below
SELECT COUNT(*) FROM employee_tbl ;
SELECT COUNT(*) FROM employee_tbl WHERE name="Zara";
Count(*)
7
Count(*)
2
Avg(),Min(),Max(),Sum()
• Syntax
• SELECT AVG(column_name) FROM table_name
• Example
• SELECT AVG(Marks) FROM Stud
• Syntax
• SELECT Min(column_name) FROM table_name
• Example
• SELECT Min(Marks) FROM Stud
• Syntax of all other functions are similar.
GROUP BY & Having Clause
• The SQL GROUP BY clause is used in collaboration with the
SELECT statement to arrange identical data into groups. This
GROUP BY clause follows the WHERE clause in a SELECT
statement
• Having is similar to where, to give condition, but it can only
work with group by
Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition ;
GROUP BY & Having Clause- Example
id name type price
123451 Park's Great Hits Music 19
123452 Silly Puddy Toy 5
123453 Playstation Toy 89
123454 Men's T-Shirt Clothing 32
123455 Blouse Clothing 34
123456 Electronica 2002 Music 3
SELECT type, MIN(price) FROM
products GROUP BY type
Type Min(Prize)
Music 3
Toy 5
Clothing 32
ProductsTable
OutPut
SELECT type, Min(price) FROM
products GROUP BY type
having Min(price)>4
Type Min(Prize)
Toy 5
Clothing 32
Set Operator: UNION,UNIONALL
UNION operator displays the combined result from
all the compounded SELECT queries, after removing
all duplicates and in sorted order (ascending by
default), without ignoring the NULL values.
UNION ALL gives the result set without removing
duplication and sorting the data.
Set Operator- ExampleUnionandUnionall
ENo Ename Addr
101 Jenny Mumbai
102 Akash Pune
103 Sona Pune
104 Minal Nashik
105 Raksh Jalgoan
PrNo Addr
10 Mumbai
20 Pune
30 Pune
SELECT City FROM Emp
UNION
SELECT City FROM Proj
ORDER BY City;
SELECT City FROM Emp
UNION All
SELECT City FROM Proj
ORDER BY City;
Emp Table
Proj Table
Addr
Jalgoan
Mumbai
Nashik
Pune
Addr
Jalgoan
Mumbai
Mumbai
Nashik
Pune
Pune
Pune
Pune
O/P O/P
solve
Eid EName Address Salary Commision
1 Amit Pune 35000 5000
2 Sneha Pune 25000
3 Savita Nasik 28000 2000
4 Pooja Mumbai 19000
5 Sagar Mumbai 25000 3000
1. Find different locations from where employees belong to?
2. What is maximum and minimum salary?
3. Display the content of employee table according to the ascending order of salary amount.
4. Find the name of employee who lived in Nasik or Pune city.
5. Find the name of employees who does not get commission.
6. Change the city of Amit to Nashik.
7. Find the information of employees whose name starts with ‘A’.
8. Find the count of staff from Mumbai.
9. Find the count of staff from each city
10.Find the address from where employees are belonging as well as where projects are going on.
11.Find city wise minimum salary.
12.Find city wise maximum salary having maximum salary greater than 26000
13.Delete the employee who is having salary greater than 30,000.
Create Employee table, Project table and add rows shown below
PrNo Addr
10 Mumbai
20 Pune
30 Jalgoan
DDL Commands forIndex
•Create Index
•Syntax
1> Create Index index_name on
table_name(column_name)
2> Alter table table_name add index
index_name (column_name)
•Example
1> Create Index n1 on Stud(Name)
2> Alter table Stud add Index n1 (name)
DDL Commands forIndex
•Show Index
• Syntax
Show Index from table_name
• Example
Show Index from Stud;
DDL Commands forIndex
•Drop Index
•Syntax
Alter table table_name drop Index
index_name
•Example
• Alter table Stud drop Index n1;
DDL Commands forView
•Create View
•Show View
•Drop View
DDL Commands forView
•Create View
• Syntax
Create View view_name as select
col_name1,col_name2 from table_name
[where <condition>]
• Example
1>Create view v1 as select name from stud;
2>Create view v2 as select name from stud
where addr=‘Nashik’;
DDL Commands forView
•Show View
•Syntax
Select col_name1,.. from View_name
[where condition]
•Example
Select * from v1;
DDL Commands forView
•Drop View
•Syntax
Drop View view_name
•Example
Drop View v1;
Synonym
• A synonym is an alternative name for objects such as tables,
views, sequences, stored procedures, and other database
objects.
• Eg. Nickname or short name of any person
• Note: Synonyms are not possible in MySQL but
possible with oracle.
MySQLJoins
MySQL Inner JOIN(Simple Join/Natural Join)
• The MySQL INNER JOIN is used to return all rows from
multiple tables where the join condition is satisfied. It is the
most common type of join.
• Syntax 1:
SELECT columns FROM table1 ,table2 Where table1.column
=
table2.column;
• Syntax 2:
SELECT columns FROM table1 INNER JOIN table2
ON table1.column = table2.column;
MySQL Inner JOINExample
RN
o
Name Address
1 Abhay Nashik
2 Sarika Pune
3 Riya Nashik
4 Sachin Manmad
Stud_Info Table
RNo Dbms Toc
1 50 45
2 67 65
3 76 55
5 70 50
Stud_Marks Table
SELECT Stud_Info.Rno,Name,Dbms,Toc FROM
Stud_Info,Stud_Marks
Where Stud_Info.RNo=Stud_Marks.RNo
RNo Name Dbms Toc
1 Abhay 50 45
2 Sarika 67 65
3 Riya 76 55
O/P
MySQL Left OuterJoin
• The LEFT OUTER JOIN returns all rows from the left hand table
specified in the ON condition and only those rows from the
other table where the join condition is fulfilled.
• Syntax:
SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
Left Outer JoinExample
RN
o
Name Address
1 Abhay Nashik
2 Sarika Pune
3 Riya Nashik
4 Sachin Manmad
Stud_Info Table
RNo Dbms Toc
1 50 45
2 67 65
3 76 55
5 70 50
Stud_Marks Table
SELECT Stud_Info.Rno,Name,Dbms,Toc FROM
Stud_Info LEFT JOIN Stud_Marks ON
Stud_Info.RNo= Stud_Marks.RNo
RNo Name Dbms Toc
1 Abhay 50 45
2 Sarika 67 65
3 Riya 76 55
4 Sachin 0 0
O/P
Right OuterJoin
• The MySQL Right Outer Join returns all rows from the RIGHT-
hand table specified in the ON condition and only those rows
from the other table where he join condition is fulfilled.
• Syntax:
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
Right Outer JoinExample
RN
o
Name Address
1 Abhay Nashik
2 Sarika Pune
3 Riya Nashik
4 Sachin Manmad
Stud_Info Table
RNo Dbms Toc
1 50 45
2 67 65
3 76 55
5 70 50
Stud_Marks Table
SELECT Stud_Info.Rno,Name,Dbms,Toc FROM
Stud_Info RIGHT JOIN Stud_Marks ON
Stud_Info.RNo= Stud_Marks.RNo
RNo Name Dbms Toc
1 Abhay 50 45
2 Sarika 67 65
3 Riya 76 55
NULL NULL 70 50
O/P
Right Outer JoinExample
RN
o
Name Address
1 Abhay Nashik
2 Sarika Pune
3 Riya Nashik
4 Sachin Manmad
Stud_Info Table
RNo Dbms Toc
1 50 45
2 67 65
3 76 55
5 70 50
Stud_Marks Table
SELECT Stud_Marks.Rno,Name,Dbms,Toc
FROM Stud_Info RIGHT JOIN Stud_Marks
ON Stud_Info.RNo= Stud_Marks.RNo
RNo Name Dbms Toc
1 Abhay 50 45
2 Sarika 67 65
3 Riya 76 55
5 NULL 70 50
O/P
Full Outer JoinExample
RN
o
Name Address
1 Abhay Nashik
2 Sarika Pune
3 Riya Nashik
4 Sachin Manmad
Stud_Info Table
RNo Dbms Toc
1 50 45
2 67 65
3 76 55
5 70 50
Stud_Marks Table
RNo Name Dbms Toc
1 Abhay 50 45
2 Sarika 67 65
3 Riya 76 55
4 Sachin 0 0
5 NULL 70 50
O/P After Full Outer Join
MySQL CROSSJOIN
• A CROSS JOIN is such a join which specifies the complete cross
product of two tables.
• For each record in the first table, all the records in the second
table are joined, creating a potentially huge result set.
• This command has the same effect as leaving off the join
condition, and its result set is also known as a Cartesian
product.
• Syntax
SELECT Attr_list FROM table_A
CROSS JOIN table_B;
Types ofSubqueries
Single Row Sub Query: Sub query which returns single row output. They mark
the usage of single row comparison operators, when used in WHERE
conditions.
Multiple row sub query: Sub query returning multiple row output. They make
use of multiple row comparison operators like IN, ANY,ALL. There can be sub
queries returning multiple columns also.
Correlated Sub Query: Correlated subqueries depend on data provided by the
outer query.This type of subquery also includes subqueries that use the
EXISTS operator to test the existence of data rows satisfying specified criteria.
MySQLSubqueries-
Single rowUsing Comparisons
Operato
r
Description
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
!= Not equal to
<> Not equal to
<=> NULL-safe equal to
operator
A sub query can be used before or
after any of the comparison
operators.
The subquery can return at
most one value.
The value can be the result of an
arithmetic expression or a column
function.
Subqueries- SingleRow
Examples on EmpTable
Emp-id Ename City Post Salary
1 John Nashik Clerk 5000
2 Seema Aurangabad Developer 20000
3 Amita Nagar Manager 70000
4 Rakesh Pune Analyst 50000
5 Samata Nashik Tester 35000
6 Ankita Chandwad Developer 30000
7 Bhavika Pune Team-LR 50000
8 Deepa Mumbai CEO 90000
9 Nitin Nagpur Clerk 8000
10 Pooja Pune Analyst 45000
• Display the information of employees, paid more than
‘pooja' from emp table
Select * From emp where salary >
(select salary from emp
where name=‘Pooja’) ;
45000
Emp-id Ename City Post Salary
3 Amita Nagar Manager 70000
4 Rakesh Pune Analyst 50000
7 Bhavika Pune Team-LR 50000
8 Deepa Mumbai CEO 90000
Output of Above Query
• List the name of the employees, who live in the same
city as of ‘Rakesh’
Select *
from emp where
city =
(select city from emp where
name=‘Rakesh’) ;
Pune
Emp-id Ename City Post Salary
4 Rakesh Pune Analyst 50000
7 Bhavika Pune Team-LR 50000
10 Pooja Pune Analyst 45000
Output of Above Query
Display the information of employees, paid less salary
than average salary throughout the company.
Select *
from emp
where salary
<
(select avg(salary)
from emp ) ;
40300
Emp-id Ename City Post Salary
1 John Nashik Clerk 5000
2 Seema Aurangabad Developer 20000
5 Samata Nashik Tester 35000
6 Ankita Chandwad Developer 30000
9 Nitin Nagpur Clerk 8000
Output of
Above Query
• Display the information of employees having
•
•
• maximum
salary in company.
Select *
from emp
where salary
=
(select max(salary) from
emp );
90000
Emp-id Ename City Post Salary
8 Deepa Mumbai CEO 90000
Output of Above Query
MySQL Subqueries -Multiplerows
withALL,ANY,INoperator
[> ALL] More than the highest value returned by the subquery
[< ALL] Less than the lowest value returned by the subquery [<
ANY] Less than the highest value returned by the subquery [>
ANY] More than the lowest value returned by the subquery
[= ANY] Equal to any value returned by the subquery (same as IN)
MySQL Subqueries- MultipleRow
Examples on EmpTable
Emp-
id
Ename City Post Salary deptno
1 John Nashik Clerk 5000 10
2 Seema Aurangabad Develope
r
20000 20
3 Amita Nagar Manager 70000 20
4 Rakesh Pune Analyst 8000 10
5 Samata Nashik Tester 20000 10
6 Ankita Chandwad Develope
r
30000 30
7 Bhavika Pune Team-LR 50000 30
8 Deepa Mumbai CEO 90000 10
9 Nitin Nagpur Clerk 8000 30
10 Pooja Pune Analyst 45000 20
IN Example- Displaytheemployeename,salaryand
departmentnoofthoseemployeeswhosesalaryistheminimumsalaryof
thatdepartment.
SELECT Ename, salary, deptno FROM EMP
WHERE salary IN
( SELECT MIN(salary) FROM emp
GROUP BY deptno )
Ename Salary deptno
John 5000 10
Seema 20000 20
Rakesh 8000 10
Samata 20000 10
Nitin 8000 30
(5000,20000,8000)
Output of
Above Query
>All Example- Displaytheemployeename,salaryand
departmentnoofthoseemployeeswhosesalaryishigherthanall developers
salary.
SELECT Ename, salary, deptno FROM EMP
WHERE salary > All
( SELECT salary FROM emp
Where post=‘Developer’)
Ename Salary deptno
Amita 70000 20
Bhavika 50000 30
Deepa 90000 10
Pooja 45000 20
(20000,30000)
Output of
Above Query
<All Example- Displaytheemployeename,salaryand
departmentnoofthoseemployeeswhosesalaryislowerthanall developers
salary.
SELECT Ename, salary, deptno FROM EMP
WHERE salary <All
( SELECT salary FROM emp
Where post=‘Developer’)
Ename Salary deptno
John 5000 10
Rakesh 8000 10
Nitin 8000 30
(20000,30000)
Output of
Above Query
>Any Example- Displaytheemployeename,salary
anddepartmentnoofthoseemployeeswhosesalaryishigherthansalaryof
anydeveloperssalary.
SELECT Ename, salary, deptno FROM EMP
WHERE salary >ANY
(SELECT salary FROM emp
Where post=‘Developer’)
(20000,30000)
Ename Salary deptno
Amita 70000 20
Ankita 30000 30
Bhavika 50000 30
Deepa 90000 10
Output of
Above Query
<Any Example- Displaytheemployeename,salary
anddepartmentnoofthoseemployeeswhosesalaryislessthansalaryof
developerssalary.
SELECT Ename, salary, deptno FROM EMP
WHERE salary <ANY
( SELECT salary FROM
emp
Where post=‘Developer’)
(20000,30000)
Ename Salary deptno
John 5000 10
Seema 20000 20
Rakesh 8000 10
Samata 20000 10
Nitin 8000 30
Output of
Above Query
GROUP BY to group values from a column, and, if you wish,
perform calculations on that column. You can use COUNT,
SUM, AVG, etc., functions on the grouped column.
Cust_Info C_Id Cname City
1 John Nashik
2 Seema Aurangabad
3 Amita Nagar
4 Rakesh Pune
5 Samata Nashik
6 Ankita Mumbai
7 Bhavika Pune
8 Deepa Mumbai
9 Nitin Nagpur
10 Pooja Pune
Acc_Info
SELECT City, COUNT(*) FROM Cust_Info GROUP BY city ;
City Count(*)
Nashik 2
Nagar 1
Pune 2
Mumbai 2
Nagpur 1
SELECT City, COUNT(*) FROM Cust_Info GROUP BY city having City
=‘Pune’;
City Count(*)
Pune 2
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a
subquery.
The EXISTS operator returns true if the subquery returns one or more
records.
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Exists (Set Membership)
Store_Name Sales Txn_Date
Los Angeles 1500 Jan-05-1999
San Diego 250 Jan-07-1999
Los Angeles 300 Jan-08-1999
Boston 700 Jan-08-1999
Region_Name Store_Name
East Boston
East New York
West Los Angeles
West San Diego
Table Geography
Table Store_Information
SELECT SUM(Sales) FROM Store_Information
WHERE EXISTS
(SELECT * FROM Geography
WHERE Region_Name = 'West');
SUM(Sales)
2750
hotel
Hotel_No Name City
H111 Empire Hotel New York
H235 Park Place New York
H432 Brownstone Hotel Toronto
H498 James Plaza Toronto
H193 Devon Hotel Boston
H437 Clairmont Hotel Boston
Room_No Hotel_No Type Price
313 H111 S 145.00
412 H111 N 145.00
1267 H235 N 175.00
1289 H235 N 195.00
876 H432 S 124.00
898 H432 S 124.00
345 H498 N 160.00
467 H498 N 180.00
1001 H193 S 150.00
1201 H193 N 175.00
257 H437 N 140.00
223 H437 N 155.00
room
Hotel_No Guest_No Date_From Date_To Room_No
H111 G256 10-AUG-99 15-AUG-99 412
H111 G367 18-AUG-99 21-AUG-99 412
H235 G879 05-SEP-99 12-SEP-99 1267
H498 G230 15-SEP-99 18-SEP-99 467
H498 G256 30-NOV-99 02-DEC-99 345
H498 G467 03-NOV-99 05-NOV-99 345
H193 G190 15-NOV-99 19-NOV-99 1001
H193 G367 12-SEP-99 14-SEP-99 1001
H193 G367 01-OCT-99 06-OCT-99 1201
H437 G190 04-OCT-99 06-OCT-99 223
H437 G879 14-SEP-99 17-SEP-99 223
Guest_No Name City
G256 Adam Wayne Pittsburgh
G367 Tara Cummings Baltimore
G879 Vanessa Parry Pittsburgh
G230 Tom Hancock Philadelphia
G467 Robert Swift Atlanta
G190 Edward Cane Baltimore
booking
guest
List full details of all hotels.
SELECT * FROM Hotel;
List full details of all hotels in London.
SELECT * FROM Hotel WHERE city = ‘London’;
List the names and addresses of all guests in London, alphabetically
ordered by name.
SELECT guestName, guestAddress FROM Guest WHERE address
LIKE ‘%London%’ ORDER BY guestName;
List all double or family rooms with a price below £40.00 per night,
in ascending order of price.
SELECT * FROM Room WHERE price < 40 AND type IN (‘D’, ‘F’)
ORDER BY price;
What is the average price of a room?
SELECT AVG(price) FROM Room;
List the number of rooms in each hotel.
SELECT hotelNo, COUNT(roomNo) AS count FROM Room GROUP BY
hotelNo;
List the price and type of all rooms at the Grosvenor Hotel. SELECT price,
type FROM Room WHERE hotelNo = (SELECT hotelNo FROM Hotel
WHERE hotelName = ‘Grosvenor Hotel’);
What is the total income from bookings for the Grosvenor Hotel today ?
SELECT SUM(price)
FROM booking b, room r, hotel h
WHERE (b.datefrom <= ‘SYSTEM DATE’
AND b.dateto >= ‘SYSTEM DATE’)
AND r.hotelno = h.hotelno
AND r.hotelno = b.hotelno
AND r.roomno = b.roomno
AND h.hotelname = ‘Grosvenor’
Assignment
C_Id Cname City
1 John Nashik
2 Seema Aurangab
ad
3 Amita Nagar
4 Rakesh Pune
5 Samata Nashik
6 Ankita Mumbai
7 Bhavika Pune
8 Deepa Mumbai
9 Nitin Nagpur
10 Pooja Pune
C_Id Acc_Type Amount
1 Current 5000
2 Saving 20000
3 Saving 70000
4 Saving 50000
6 Current 35000
7 Loan 30000
8 Saving 50000
9 Saving 90000
10 Loan 8000
11 Current 45000
Cust_Info Acc_Info
Assignment
• Show the cname, Acc_Type, amount information of customer
• who is having an saving account.
• Display the data using Natural, left and right join.
• Display the information of customers living in the same city as
• of ‘pooja’.
• Display the information of account, having less amount than
average amount throughout the bank.
• Display the C_id having maximum amount in account.
• Display the amount and acc_type of those customers
whose amount is the minimum amount of that
Acc_type.
• Display the amount of those accounts whose
amount is higher than amount of any saving
• account amount.
DATA CONTROL LANGUAGE
DCL commands are used to enforce database security in a
multiple database environment.
• Two types of DCL commands are
• Grant
• Revoke
• Database Administrator's or owner’s of the database object
can provide/remove privileges on a database object.
Syntax of Grant :
GRANT privileges ON object TO user;
Example :
GRANT SELECT, INSERT, UPDATE, DELETE ON contacts TO
'smithj'@'localhost';
GRANT ALL ON contacts TO 'smithj'@'localhost';
GRANT SELECT ON contacts TO '*'@'localhost';
Syntax
The syntax for revoking privileges on a table in MySQL is:
REVOKE privileges ON object FROM user;
TCL command
Transaction Control Language(TCL) commands are used to
manage transactions in database.These are used to manage the
changes made by DML statements. It also allows statements to
be grouped together into logical transactions.
Commit command
Commit command is used to permanently save any transaction into database.
Following is Commit command's syntax,
commit;
Rollback command
This command restores the database to last commited state. It is also use with
savepoint command to jump to a savepoint in a transaction.
Following is Rollback command's syntax,
rollback to savepoint-name;
Savepoint command
savepoint command is used to temporarily save a transaction
so that you can rollback to that point whenever necessary.
Following is savepoint command's syntax,
savepoint savepoint-name;
Select INTO
• SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
Insert into
• INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Fill in the blanks
1) DCL contain …………………&…………………commands.
2) Primary Key is the combination of…………………&………………….
3) After table command operates on …………………ends.
4) …………………cmd is used to save data in database.
5) The condition in group by clause is given by
…………………clause.
6) A query that include group by clause is
called…………………query.
7) Duplication of data avoid by …………………Keyword.

More Related Content

Similar to unit-ii.pptx

Similar to unit-ii.pptx (20)

Hsqldb tutorial
Hsqldb tutorialHsqldb tutorial
Hsqldb tutorial
 
Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)Database Systems - Introduction to SQL (Chapter 3/1)
Database Systems - Introduction to SQL (Chapter 3/1)
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
Mysql database
Mysql databaseMysql database
Mysql database
 
Object Relational Database Management System
Object Relational Database Management SystemObject Relational Database Management System
Object Relational Database Management System
 
My sql technical reference manual
My sql technical reference manualMy sql technical reference manual
My sql technical reference manual
 
MySQL ppt
MySQL ppt MySQL ppt
MySQL ppt
 
MySQL intro
MySQL introMySQL intro
MySQL intro
 
MySQL intro
MySQL introMySQL intro
MySQL intro
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Sql – pocket guide
Sql – pocket guideSql – pocket guide
Sql – pocket guide
 
Complete first chapter rdbm 17332
Complete first chapter rdbm 17332Complete first chapter rdbm 17332
Complete first chapter rdbm 17332
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
SQL.pptx
SQL.pptxSQL.pptx
SQL.pptx
 
Mysql-overview.pptx
Mysql-overview.pptxMysql-overview.pptx
Mysql-overview.pptx
 
Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)Php, mysq lpart5(mysql)
Php, mysq lpart5(mysql)
 
working with database using mysql
working with database using mysql working with database using mysql
working with database using mysql
 
Relational Database Language.pptx
Relational Database Language.pptxRelational Database Language.pptx
Relational Database Language.pptx
 
SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2SQL Fundamentals - Lecture 2
SQL Fundamentals - Lecture 2
 
SQL.pptx for the begineers and good know
SQL.pptx for the begineers and good knowSQL.pptx for the begineers and good know
SQL.pptx for the begineers and good know
 

More from NilamHonmane

UNIT 1 Web Application Develpoment HTTP and CSS
UNIT 1 Web Application Develpoment HTTP and CSSUNIT 1 Web Application Develpoment HTTP and CSS
UNIT 1 Web Application Develpoment HTTP and CSSNilamHonmane
 
2-background-5g.ppt
2-background-5g.ppt2-background-5g.ppt
2-background-5g.pptNilamHonmane
 
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.pptNilamHonmane
 
Introduction to Investor.pptx
Introduction to Investor.pptxIntroduction to Investor.pptx
Introduction to Investor.pptxNilamHonmane
 

More from NilamHonmane (7)

UNIT 1 Web Application Develpoment HTTP and CSS
UNIT 1 Web Application Develpoment HTTP and CSSUNIT 1 Web Application Develpoment HTTP and CSS
UNIT 1 Web Application Develpoment HTTP and CSS
 
2-background-5g.ppt
2-background-5g.ppt2-background-5g.ppt
2-background-5g.ppt
 
note_vc.ppt
note_vc.pptnote_vc.ppt
note_vc.ppt
 
Unit-3.pptx
Unit-3.pptxUnit-3.pptx
Unit-3.pptx
 
UNIT_4.pptx
UNIT_4.pptxUNIT_4.pptx
UNIT_4.pptx
 
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt
373_23865_CR315_2011_1__2_1_CH09 Mobile Computing.ppt
 
Introduction to Investor.pptx
Introduction to Investor.pptxIntroduction to Investor.pptx
Introduction to Investor.pptx
 

Recently uploaded

Along the Lakefront, "Menacing Unknown"s
Along the Lakefront, "Menacing Unknown"sAlong the Lakefront, "Menacing Unknown"s
Along the Lakefront, "Menacing Unknown"syalehistoricalreview
 
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130Suhani Kapoor
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashikranjana rawat
 
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...Cluster TWEED
 
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...Suhani Kapoor
 
Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Open Access Research Paper
 
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...Suhani Kapoor
 
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...ranjana rawat
 
Soil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresSoil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresvasubhanot1234
 
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...Suhani Kapoor
 
Spiders by Slidesgo - an introduction to arachnids
Spiders by Slidesgo - an introduction to arachnidsSpiders by Slidesgo - an introduction to arachnids
Spiders by Slidesgo - an introduction to arachnidsprasan26
 
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...Amil baba
 
ENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawnitinraj1000000
 

Recently uploaded (20)

Along the Lakefront, "Menacing Unknown"s
Along the Lakefront, "Menacing Unknown"sAlong the Lakefront, "Menacing Unknown"s
Along the Lakefront, "Menacing Unknown"s
 
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
VIP Call Girls Service Bandlaguda Hyderabad Call +91-8250192130
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
 
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
 
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...
VIP Call Girls Mahadevpur Colony ( Hyderabad ) Phone 8250192130 | ₹5k To 25k ...
 
Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...Determination of antibacterial activity of various broad spectrum antibiotics...
Determination of antibacterial activity of various broad spectrum antibiotics...
 
Escort Service Call Girls In Shakti Nagar, 99530°56974 Delhi NCR
Escort Service Call Girls In Shakti Nagar, 99530°56974 Delhi NCREscort Service Call Girls In Shakti Nagar, 99530°56974 Delhi NCR
Escort Service Call Girls In Shakti Nagar, 99530°56974 Delhi NCR
 
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...
VIP Call Girls Moti Ganpur ( Hyderabad ) Phone 8250192130 | ₹5k To 25k With R...
 
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(AISHA) Wagholi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
 
Soil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresSoil pollution causes effects remedial measures
Soil pollution causes effects remedial measures
 
Sustainable Packaging
Sustainable PackagingSustainable Packaging
Sustainable Packaging
 
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...
VIP Call Girls Saharanpur Aaradhya 8250192130 Independent Escort Service Saha...
 
Spiders by Slidesgo - an introduction to arachnids
Spiders by Slidesgo - an introduction to arachnidsSpiders by Slidesgo - an introduction to arachnids
Spiders by Slidesgo - an introduction to arachnids
 
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...
NO1 Famous Kala Jadu specialist Expert in Pakistan kala ilam specialist Exper...
 
E Waste Management
E Waste ManagementE Waste Management
E Waste Management
 
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
 
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls ServicesGandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
Gandhi Nagar (Delhi) 9953330565 Escorts, Call Girls Services
 
Green Banking
Green Banking Green Banking
Green Banking
 
ENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental lawENVIRONMENTAL LAW ppt on laws of environmental law
ENVIRONMENTAL LAW ppt on laws of environmental law
 

unit-ii.pptx

  • 2. SQL • Structured Query Language or SQL is a standard computer language for accessing and manipulating database systems. • SQL comprises one of the fundamental building blocks of modern database architecture. SQL defines methods using which user can create and manipulate databases on all major platforms. • SQL is the standard language for Relational Database System. All the Relational Database Management Systems (RDMS) like MySQL, MS Access, Oracle, Sybase, Informix, Postgres and SQL Server use SQL as their standard database language.
  • 3. SQL HISTORY 1970 − Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He described a relational model for databases. 1974 − Structured Query Language appeared. 1978 − IBM worked to develop Codd's ideas and released a product named System/R. 1986 − IBM developed the first prototype of relational database and standardized by ANSI. The first relational database was released by Relational Software which later came to be known as Oracle.
  • 4. Characteristics of SQL • SQL is an ANSI and ISO standard computer language for creating and manipulating databases. • SQL allows the user to create, update, delete, and retrieve data from a database. • SQL is very simple and easy to learn. • SQL works with database programs like DB2, Oracle, MS Access, Sybase, MS SQL Sever etc.
  • 5. ADVANTAGES OF SQL • High speed • No coding needed • Well defined standards • Portability • Interactive language • Multiple data view
  • 8. SQL Commands Data Definition Language (DDL) • DDL changes the structure of the table like creating a table, deleting a table, altering a table, etc. Data Manipulation Language • DML commands are used to modify the database. It is responsible for all form of changes in the database. Data Control Language • DCL commands are used to grant and take back authority from any database user. Transaction Control Language • TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.
  • 9. Introduction toMySQL MySQL is the most popular Open Source Relational SQL Database Management System. MySQL is one of the best RDBMS being used for developing various web- based software applications. MySQL is developed, marketed and supported by MySQL AB, which is a Swedish company.
  • 10. MySQLDatabase • MySQL is an open-source database • MySQL is customizable because it is an open source database • MySQL is quicker than other databases so it can work well even with the large data set. • MySQL supports many languages like PHP, PERL, C, C++, JAVA, etc. • MySQL uses a standard form of the well-known SQL data language. • MySQL supports large databases, up to 50 million rows or more in a table. The default file size limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a theoretical limit of 8 million terabytes (TB).
  • 11. MySQL Features • Relational Database Management System (RDBMS): MySQL is a relational database management system. • Easy to use: MySQL is easy to use. You have to get only the basic knowledge of SQL. You can build and interact with MySQL with only a few simple SQL statements. • It is secure: MySQL consist of a solid data security layer that protects sensitive data from intruders. Passwords are encrypted in MySQL. • Client/ Server Architecture: MySQL follows a client /server architecture. There is a database server (MySQL) and arbitrarily many clients (application programs), which communicate with the server; that is, they query data, save changes, etc. • Free to download: MySQL is free to use and you can download it from MySQL official website. • It is scalable: MySQL can handle almost any amount of data, up to as much as 50 million rows or more. The default file size limit is about 4 GB. However, you can increase this number to a theoretical limit of 8 TB of data. • Compatible on many operating systems: MySQL is compatible to run on many operating systems, • Allows roll-back: MySQL allows transactions to be rolled back, commit and crash recovery. • High Performance: MySQL is faster, more reliable and cheaper because of its unique storage engine architecture. • High Flexibility: MySQL supports a large number of embedded applications which makes MySQL very flexible. • High Productivity: MySQL uses Triggers, Stored procedures and views which allows the developer to give a higher productivity.
  • 12. MySQL DataTypes Categaries Data Types Numeric Data Type INT, FLOAT(m,d), DOUBLE(m,d), DECIMAL(m,d) Date and Time Data Type: DATE, DATETIME,TIME, TIMESTAMP,YEAR String Data Types: CHAR,VARCHAR,TEXT, LONGTEXT,BINARY Large Object Data Types (LOB) Data Types: TINYBLOB, BLOB, MEDIUMBLOB, LONGTEXT
  • 13.
  • 14.
  • 15.
  • 16.
  • 17. Command to Install MySQLin ubuntu • sudo apt-get install mysql-server
  • 18. How to startMySQL • First install mysql then write following command on command prompt •mysql -u root –p • Then Enter Password, it will show you MySQL prompt • -u -username -p -password
  • 19. Database relatedcommands- CREATE • Syntax to create database • CREATE DATABASE database_name; • Example: • Let's take an example to create a database name "employees" • CREATE DATABASE employees;
  • 20. Database relatedcommands- SHOW & USE • You can check the created database by the following query: • SHOW DATABASES; • You can use SQL command USE to select a particular database. • Syntax: • USE database_name; • Example: • Let's take an example to use a database name "Students". • USE customers;
  • 21. Database relatedcommands- DROP • You can drop/delete/remove a MySQL database easily with the MySQL command. You should be careful while deleting any database because you will lose your all the data available in your database. • Syntax: • DROP DATABASE database_name; • Example: • Let's take an example to drop a database name "employees" • DROP DATABASE employees;
  • 22. How to Connect remoteMySQL server • To connect remote MySQL server, use the -h (host) with IP Address of remote machine. • # mysqladmin -h ip- address -u root -p
  • 23. Table RollNo Name Address 1 Sonali Nashik 2 Yug Pune Table Name: Student
  • 24. DDL- Data DefinitionLanguage • DDL statements or commands are used to define and modify the database structure of your tables or schema. Some commands of DDL are: • CREATE – to create table (objects) in the database • ALTER – alters the structure of the database • DROP – delete table from the database • TRUNCATE – remove all records from a table, including all spaces allocated for the records are removed • COMMENT – add comments to the data dictionary • RENAME – rename a table
  • 25. DDL Commands forTable •Create table •Show tables •Describe table •Alter table •Truncate table •Drop table •Rename
  • 26. DDL Commands forTable •Create table • Syntax Create table table_name (Col_name1 data_type(Size) , Col_name2 data_type(Size),…)) • Example Create table Stud(rno number(4),name varchar2(20), DOB date));
  • 27. DDL Commands forTable •Describe table •Syntax desc table_name; •Example desc Stud;
  • 28. DDL Commands forTable •Show tables This will list the tables in the current database: • Syntax show tables; • Example mysql> show tables; customers orders 2 rows in set (0.00 sec)
  • 29. DDL Commands forTable •Alter table (add or modify) • Syntax alter table table_name add/modify/drop column_name data_type(size) • Example • Alter table stud add age int(3); • Alter table stud modify name varchar2(30); • Alter table stud modify name char(20); • Alter table stud drop column age;
  • 30. DDL Commands forTable •Truncate Table used to delete complete data from an existing table. • Syntax • TRUNCATE TABLE table_name; • Example mysql> TRUNCATE TABLE stud;
  • 31. DDL Commands forTable •Rename Table used to rename table. • Syntax • RENAME TABLE tbl_name TO new_tbl_name • Example mysql> RENAME TABLE stud TO student ;
  • 32. Constraints • Constraints are the set of rules defined on tables to ensure data integrity. • Primary key • Not null • Default • Unique • Check • Foreign key/reference key
  • 33. Constraints-Unique • The UNIQUE constraint in MySQL does not allow to insert a duplicate value in a column. • Syntax CREATE TABLE table_name (col_name data_type (size) Unique); • Example • CREATE TABLE Stud (Rno number(4) Unique);
  • 34. Constraints- NotNull • A NOT NULL constraint means that a data row must have a value for the column specified as NOT NULL. • Syntax CREATE TABLE table_name (Col_name Data_type(size)not null, ... ); •Example Create table stud (rollno number(4) ,name varchar2(20)not null);
  • 35. Constraints- Primarykey • Each table must normally contain a column or set of columns that uniquely identifies rows of data that are stored in the table. This column or set of columns is referred to as the primary key. • A table can have only one primary key. • Multiple columns can be clubbed under a composite primary key. • Primary key columns is combination of NOT NULL and UNIQUE. • Syntax CREATE TABLE table_name ( Col_name Data_type(size)CONSTRAINT constraint_name PRIMARY KEY, ... ); • Example • Create table stud (rollno number(4)constraint pk1 primary key,name…) • Create table stud (rollno number(4) primary key, name ….)
  • 36. Constraints-Default • In a MySQL table, while inserting data into a table, if no value is supplied to a column, then the column gets the value set as DEFAULT. • Syntax • CREATE TABLE table_name (col_name data_type(size) DEFAULT ‘default_value’ ); • Example • CREATE TABLE Stud (rno number(4) ,name varchar2(20), addr varchar(30) DEFAULT ‘Chandwad’ );
  • 37. Constraints-Check • In a MySQL table, A CHECK constraint controls the values in the associated column. The CHECK constraint determines whether the value is valid or not. • Syntax • CREATE TABLE table_name (col_name data_type(size) Check (condition) ); • Example • CREATE TABLE Stud (rno number(4) CHECK (rollno BETWEEN 1 AND 60)); • CREATE TABLE Stud (age number(4) CHECK (age>18));
  • 38. Constraints- FOREIGNKEY • A FOREIGN KEY in MySQL creates a link between two tables by one specific column of both tables. The specified column in one table must be a PRIMARY KEY and referred by the column of another table known as FOREIGN KEY. • Syntax • Create table table_name(col_name data_type(size)references table_name(col_name)); • Example • Createtable stud1 (rollno number(4) references stud(rno));
  • 39. Constraints- after tablecreation and dropconstraint • You can also add constraint after table creation using alter table option • Example • Alter table stud add constraint prk1 primary key(rollno); • You can also drop constraint using Drop command & name of constraint • Example • Drop constraint prk1;
  • 40. DDL Commands forTable •Drop table •Syntax Drop table table_name; •Example Drop table stud;
  • 41. Sequence- UsingAUTO_INCREMENT Column AUTO_INCREMENT Syntax • CREATE TABLE table_name ( column1 datatype NOT NULL AUTO_INCREMENT,….); • ALTER TABLE table_name AUTO_INCREMENT = start_value; Example • CREATE TABLE Bills ( Bill_No INT(11) NOT NULL AUTO_INCREMENT, name varchar2(20)); • ALTER TABLE Bills AUTO_INCREMENT = 1001;
  • 42. Solve • Create one table employee with fields • Eno –primary key and apply sequence starts with 101 • Ename –not null • Address –default ‘Pune’ • Joindate • Post • Create another table emp_proj with fields • Eno- forign key • Project_name • Loc • Create Index on Ename field of employee table • Create View on employee table to show only Employee name, it’s post and salary.
  • 43. Insert - INSERTtuplesintoarelation rollno Name Address 1 Pooja Pune 2 Amit Where every attribute in the table is given a value INSERT INTO tablename VALUES (attr1_value, attr2_value, ... attrn_value) Where every attribute in the table is has not a value then it considered as NULL. INSERT INTO tablename (attrx, ... , attry) VALUES (attrx_value, ... , attry_value) Example: •Insert into Stud values (1,’Pooja’, ‘Pune’) •Insert into Stud (rollno,name) values (2, ‘Amit’) The output of "Stud" table after inserting above 2 rows
  • 44. Delete –DELETEtuplesfromrelation • Syntax • DELETE FROM tablename <WHERE condition> • It removes zero, one or many tuples; The WHERE clause is optional; if it is left out all tuples are removed, but the table still exists; it is empty. • Example: 1> DELETE FROM Stud WHERE Address = 'Pune'; ( Only delete roes that satisfy the condition) 2> DELETE FROM Stud; • (Delete all rows)
  • 45. Update- UPDATEofoneormoreselected tuples Syntax UPDATE tablename SET attrx = new_value, <WHERE condition>; Example: 1> Update Stud Set Name= ‘Shruti’ where rollno=1 (Only name field of row having rollno as 1 will be chaged as ‘Shruti’) 2> Update Stud Set Name= ‘Shruti’ (name field of All row will be changed as ‘Shruti’)
  • 46. Select- SELECTstatement retrieves datafromtable Syntax SELECT attribute_list FROM table_list <WHERE condition>; • The attributes are those you want to see in the result, • the tables are those required for the query, • the condition is a boolean expression that specifies which tuples are to be retrieved by the query. Example: 1. Select * from Stud; 2. Select * from Stud where rno=1; 3. Select Name, Address from Stud; 4. Select Name, Address from Stud where rno=1 5. Select Name from Stud where address=‘Nashik’;
  • 47. Order By- RetrievalwithorderingAscending/Descending • The ORDER BY keyword is used to sort the result-set by a specified column. • The ORDER BY keyword sort the records in ascending order by default. • If you want to sort the records in a descending order, you can use the DESC keyword. Syntax SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC Example 1. Select * from Stud order by rno desc; 2. Select * from Stud order by rno ; 3. Select * from Stud order by Name;
  • 48. LIKE Operator- searchforaspecified patterninacolumn Syntax SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern SQL Wildcards • SQL wildcards can substitute for one or more characters when searching for data in a database. • SQL wildcards must be used with the LIKE operator. Wildcard Description % A substitute for zero or more characters _ A substitute for exactly one character
  • 49. LIKE Operator- Example P_Id LastName Address 1 Heena Pune 2 Savita Pune 3 Sarika Bombay SELECT LastName from Person where LastName like ‘S%’ ; LastName Savita Sarika "Persons"table We use the following SELECT statement: The result-set will look like this:
  • 50. DISTINCT Operator • The DISTINCT keyword can be used to return only distinct (different) values. Syntax • SELECT DISTINCT column_name(s) FROM table_name Example • SELECT distinct(Address) from Person • The result-set will look like this P_Id Name Address 1 Hansen Pune 2 Svendson Pune 3 Pettersen Bombay The "Persons" table: Address Pune Bombay
  • 51. IN Operator- TheINoperatorallowsyouto specifymultiplevaluesinaWHEREclause. Syntax SELECT column_name(s) FROM table_name WHERE column_name IN (value1,value2,...) Example SELECT * FROM Persons WHERE Address IN ('Pune','Bombay') The result-set will look like this P_Id Name Address 1 Hansen Pune 2 Svendson Nashik 3 Pettersen Bombay The "Persons" table: P_Id Name Address 1 Hansen Pune 3 Pettersen Bombay
  • 52. NULL Operator- • To test if a value is NULL you cannot use =, because every NULL is considered distinct from every other one. Must use "IS NULL" or "IS NOT NULL“ Syntax SELECT Attr_List FROM table_name WHERE Attr_name IS NULL; Example 1. SELECT * FROM Stud WHERE Address is null; 2. SELECT * FROM Stud WHERE Address is not null;
  • 53. Aggregate Functions • Aggregate /Group functions are built-in SQL functions that operate on groups of rows and return one value for the entire group. • The Functions are as below: MIN returns the smallest value in a given column MAX returns the largest value in a given column SUM returns the sum of the numeric values in a given column AVG returns the average value of a given column COUNT returns the total number of values in a given column COUNT(*) returns the number of rows in a table
  • 54. Count()- Syntax COUNT(column_name)-The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: Syntax • SELECT COUNT(column_name) FROM table_name COUNT(*)-The COUNT(*) function returns the number of records in a table: Syntax • SELECT COUNT(*) FROM table_name
  • 55. Count()- Example Consider an employee_tbl table as shown below SELECT COUNT(*) FROM employee_tbl ; SELECT COUNT(*) FROM employee_tbl WHERE name="Zara"; Count(*) 7 Count(*) 2
  • 56. Avg(),Min(),Max(),Sum() • Syntax • SELECT AVG(column_name) FROM table_name • Example • SELECT AVG(Marks) FROM Stud • Syntax • SELECT Min(column_name) FROM table_name • Example • SELECT Min(Marks) FROM Stud • Syntax of all other functions are similar.
  • 57. GROUP BY & Having Clause • The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement • Having is similar to where, to give condition, but it can only work with group by Syntax SELECT column_name(s) FROM table_name WHERE condition GROUP BY column_name(s) HAVING condition ;
  • 58. GROUP BY & Having Clause- Example id name type price 123451 Park's Great Hits Music 19 123452 Silly Puddy Toy 5 123453 Playstation Toy 89 123454 Men's T-Shirt Clothing 32 123455 Blouse Clothing 34 123456 Electronica 2002 Music 3 SELECT type, MIN(price) FROM products GROUP BY type Type Min(Prize) Music 3 Toy 5 Clothing 32 ProductsTable OutPut SELECT type, Min(price) FROM products GROUP BY type having Min(price)>4 Type Min(Prize) Toy 5 Clothing 32
  • 59. Set Operator: UNION,UNIONALL UNION operator displays the combined result from all the compounded SELECT queries, after removing all duplicates and in sorted order (ascending by default), without ignoring the NULL values. UNION ALL gives the result set without removing duplication and sorting the data.
  • 60. Set Operator- ExampleUnionandUnionall ENo Ename Addr 101 Jenny Mumbai 102 Akash Pune 103 Sona Pune 104 Minal Nashik 105 Raksh Jalgoan PrNo Addr 10 Mumbai 20 Pune 30 Pune SELECT City FROM Emp UNION SELECT City FROM Proj ORDER BY City; SELECT City FROM Emp UNION All SELECT City FROM Proj ORDER BY City; Emp Table Proj Table Addr Jalgoan Mumbai Nashik Pune Addr Jalgoan Mumbai Mumbai Nashik Pune Pune Pune Pune O/P O/P
  • 61. solve Eid EName Address Salary Commision 1 Amit Pune 35000 5000 2 Sneha Pune 25000 3 Savita Nasik 28000 2000 4 Pooja Mumbai 19000 5 Sagar Mumbai 25000 3000 1. Find different locations from where employees belong to? 2. What is maximum and minimum salary? 3. Display the content of employee table according to the ascending order of salary amount. 4. Find the name of employee who lived in Nasik or Pune city. 5. Find the name of employees who does not get commission. 6. Change the city of Amit to Nashik. 7. Find the information of employees whose name starts with ‘A’. 8. Find the count of staff from Mumbai. 9. Find the count of staff from each city 10.Find the address from where employees are belonging as well as where projects are going on. 11.Find city wise minimum salary. 12.Find city wise maximum salary having maximum salary greater than 26000 13.Delete the employee who is having salary greater than 30,000. Create Employee table, Project table and add rows shown below PrNo Addr 10 Mumbai 20 Pune 30 Jalgoan
  • 62. DDL Commands forIndex •Create Index •Syntax 1> Create Index index_name on table_name(column_name) 2> Alter table table_name add index index_name (column_name) •Example 1> Create Index n1 on Stud(Name) 2> Alter table Stud add Index n1 (name)
  • 63. DDL Commands forIndex •Show Index • Syntax Show Index from table_name • Example Show Index from Stud;
  • 64. DDL Commands forIndex •Drop Index •Syntax Alter table table_name drop Index index_name •Example • Alter table Stud drop Index n1;
  • 65. DDL Commands forView •Create View •Show View •Drop View
  • 66. DDL Commands forView •Create View • Syntax Create View view_name as select col_name1,col_name2 from table_name [where <condition>] • Example 1>Create view v1 as select name from stud; 2>Create view v2 as select name from stud where addr=‘Nashik’;
  • 67. DDL Commands forView •Show View •Syntax Select col_name1,.. from View_name [where condition] •Example Select * from v1;
  • 68. DDL Commands forView •Drop View •Syntax Drop View view_name •Example Drop View v1;
  • 69. Synonym • A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects. • Eg. Nickname or short name of any person • Note: Synonyms are not possible in MySQL but possible with oracle.
  • 71. MySQL Inner JOIN(Simple Join/Natural Join) • The MySQL INNER JOIN is used to return all rows from multiple tables where the join condition is satisfied. It is the most common type of join. • Syntax 1: SELECT columns FROM table1 ,table2 Where table1.column = table2.column; • Syntax 2: SELECT columns FROM table1 INNER JOIN table2 ON table1.column = table2.column;
  • 72. MySQL Inner JOINExample RN o Name Address 1 Abhay Nashik 2 Sarika Pune 3 Riya Nashik 4 Sachin Manmad Stud_Info Table RNo Dbms Toc 1 50 45 2 67 65 3 76 55 5 70 50 Stud_Marks Table SELECT Stud_Info.Rno,Name,Dbms,Toc FROM Stud_Info,Stud_Marks Where Stud_Info.RNo=Stud_Marks.RNo RNo Name Dbms Toc 1 Abhay 50 45 2 Sarika 67 65 3 Riya 76 55 O/P
  • 73. MySQL Left OuterJoin • The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON condition and only those rows from the other table where the join condition is fulfilled. • Syntax: SELECT columns FROM table1 LEFT [OUTER] JOIN table2 ON table1.column = table2.column;
  • 74. Left Outer JoinExample RN o Name Address 1 Abhay Nashik 2 Sarika Pune 3 Riya Nashik 4 Sachin Manmad Stud_Info Table RNo Dbms Toc 1 50 45 2 67 65 3 76 55 5 70 50 Stud_Marks Table SELECT Stud_Info.Rno,Name,Dbms,Toc FROM Stud_Info LEFT JOIN Stud_Marks ON Stud_Info.RNo= Stud_Marks.RNo RNo Name Dbms Toc 1 Abhay 50 45 2 Sarika 67 65 3 Riya 76 55 4 Sachin 0 0 O/P
  • 75. Right OuterJoin • The MySQL Right Outer Join returns all rows from the RIGHT- hand table specified in the ON condition and only those rows from the other table where he join condition is fulfilled. • Syntax: SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.column;
  • 76. Right Outer JoinExample RN o Name Address 1 Abhay Nashik 2 Sarika Pune 3 Riya Nashik 4 Sachin Manmad Stud_Info Table RNo Dbms Toc 1 50 45 2 67 65 3 76 55 5 70 50 Stud_Marks Table SELECT Stud_Info.Rno,Name,Dbms,Toc FROM Stud_Info RIGHT JOIN Stud_Marks ON Stud_Info.RNo= Stud_Marks.RNo RNo Name Dbms Toc 1 Abhay 50 45 2 Sarika 67 65 3 Riya 76 55 NULL NULL 70 50 O/P
  • 77. Right Outer JoinExample RN o Name Address 1 Abhay Nashik 2 Sarika Pune 3 Riya Nashik 4 Sachin Manmad Stud_Info Table RNo Dbms Toc 1 50 45 2 67 65 3 76 55 5 70 50 Stud_Marks Table SELECT Stud_Marks.Rno,Name,Dbms,Toc FROM Stud_Info RIGHT JOIN Stud_Marks ON Stud_Info.RNo= Stud_Marks.RNo RNo Name Dbms Toc 1 Abhay 50 45 2 Sarika 67 65 3 Riya 76 55 5 NULL 70 50 O/P
  • 78. Full Outer JoinExample RN o Name Address 1 Abhay Nashik 2 Sarika Pune 3 Riya Nashik 4 Sachin Manmad Stud_Info Table RNo Dbms Toc 1 50 45 2 67 65 3 76 55 5 70 50 Stud_Marks Table RNo Name Dbms Toc 1 Abhay 50 45 2 Sarika 67 65 3 Riya 76 55 4 Sachin 0 0 5 NULL 70 50 O/P After Full Outer Join
  • 79. MySQL CROSSJOIN • A CROSS JOIN is such a join which specifies the complete cross product of two tables. • For each record in the first table, all the records in the second table are joined, creating a potentially huge result set. • This command has the same effect as leaving off the join condition, and its result set is also known as a Cartesian product. • Syntax SELECT Attr_list FROM table_A CROSS JOIN table_B;
  • 80. Types ofSubqueries Single Row Sub Query: Sub query which returns single row output. They mark the usage of single row comparison operators, when used in WHERE conditions. Multiple row sub query: Sub query returning multiple row output. They make use of multiple row comparison operators like IN, ANY,ALL. There can be sub queries returning multiple columns also. Correlated Sub Query: Correlated subqueries depend on data provided by the outer query.This type of subquery also includes subqueries that use the EXISTS operator to test the existence of data rows satisfying specified criteria.
  • 81. MySQLSubqueries- Single rowUsing Comparisons Operato r Description = Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to != Not equal to <> Not equal to <=> NULL-safe equal to operator A sub query can be used before or after any of the comparison operators. The subquery can return at most one value. The value can be the result of an arithmetic expression or a column function.
  • 82. Subqueries- SingleRow Examples on EmpTable Emp-id Ename City Post Salary 1 John Nashik Clerk 5000 2 Seema Aurangabad Developer 20000 3 Amita Nagar Manager 70000 4 Rakesh Pune Analyst 50000 5 Samata Nashik Tester 35000 6 Ankita Chandwad Developer 30000 7 Bhavika Pune Team-LR 50000 8 Deepa Mumbai CEO 90000 9 Nitin Nagpur Clerk 8000 10 Pooja Pune Analyst 45000
  • 83. • Display the information of employees, paid more than ‘pooja' from emp table Select * From emp where salary > (select salary from emp where name=‘Pooja’) ; 45000 Emp-id Ename City Post Salary 3 Amita Nagar Manager 70000 4 Rakesh Pune Analyst 50000 7 Bhavika Pune Team-LR 50000 8 Deepa Mumbai CEO 90000 Output of Above Query
  • 84. • List the name of the employees, who live in the same city as of ‘Rakesh’ Select * from emp where city = (select city from emp where name=‘Rakesh’) ; Pune Emp-id Ename City Post Salary 4 Rakesh Pune Analyst 50000 7 Bhavika Pune Team-LR 50000 10 Pooja Pune Analyst 45000 Output of Above Query
  • 85. Display the information of employees, paid less salary than average salary throughout the company. Select * from emp where salary < (select avg(salary) from emp ) ; 40300 Emp-id Ename City Post Salary 1 John Nashik Clerk 5000 2 Seema Aurangabad Developer 20000 5 Samata Nashik Tester 35000 6 Ankita Chandwad Developer 30000 9 Nitin Nagpur Clerk 8000 Output of Above Query
  • 86. • Display the information of employees having • • • maximum salary in company. Select * from emp where salary = (select max(salary) from emp ); 90000 Emp-id Ename City Post Salary 8 Deepa Mumbai CEO 90000 Output of Above Query
  • 87. MySQL Subqueries -Multiplerows withALL,ANY,INoperator [> ALL] More than the highest value returned by the subquery [< ALL] Less than the lowest value returned by the subquery [< ANY] Less than the highest value returned by the subquery [> ANY] More than the lowest value returned by the subquery [= ANY] Equal to any value returned by the subquery (same as IN)
  • 88. MySQL Subqueries- MultipleRow Examples on EmpTable Emp- id Ename City Post Salary deptno 1 John Nashik Clerk 5000 10 2 Seema Aurangabad Develope r 20000 20 3 Amita Nagar Manager 70000 20 4 Rakesh Pune Analyst 8000 10 5 Samata Nashik Tester 20000 10 6 Ankita Chandwad Develope r 30000 30 7 Bhavika Pune Team-LR 50000 30 8 Deepa Mumbai CEO 90000 10 9 Nitin Nagpur Clerk 8000 30 10 Pooja Pune Analyst 45000 20
  • 89. IN Example- Displaytheemployeename,salaryand departmentnoofthoseemployeeswhosesalaryistheminimumsalaryof thatdepartment. SELECT Ename, salary, deptno FROM EMP WHERE salary IN ( SELECT MIN(salary) FROM emp GROUP BY deptno ) Ename Salary deptno John 5000 10 Seema 20000 20 Rakesh 8000 10 Samata 20000 10 Nitin 8000 30 (5000,20000,8000) Output of Above Query
  • 90. >All Example- Displaytheemployeename,salaryand departmentnoofthoseemployeeswhosesalaryishigherthanall developers salary. SELECT Ename, salary, deptno FROM EMP WHERE salary > All ( SELECT salary FROM emp Where post=‘Developer’) Ename Salary deptno Amita 70000 20 Bhavika 50000 30 Deepa 90000 10 Pooja 45000 20 (20000,30000) Output of Above Query
  • 91. <All Example- Displaytheemployeename,salaryand departmentnoofthoseemployeeswhosesalaryislowerthanall developers salary. SELECT Ename, salary, deptno FROM EMP WHERE salary <All ( SELECT salary FROM emp Where post=‘Developer’) Ename Salary deptno John 5000 10 Rakesh 8000 10 Nitin 8000 30 (20000,30000) Output of Above Query
  • 92. >Any Example- Displaytheemployeename,salary anddepartmentnoofthoseemployeeswhosesalaryishigherthansalaryof anydeveloperssalary. SELECT Ename, salary, deptno FROM EMP WHERE salary >ANY (SELECT salary FROM emp Where post=‘Developer’) (20000,30000) Ename Salary deptno Amita 70000 20 Ankita 30000 30 Bhavika 50000 30 Deepa 90000 10 Output of Above Query
  • 93. <Any Example- Displaytheemployeename,salary anddepartmentnoofthoseemployeeswhosesalaryislessthansalaryof developerssalary. SELECT Ename, salary, deptno FROM EMP WHERE salary <ANY ( SELECT salary FROM emp Where post=‘Developer’) (20000,30000) Ename Salary deptno John 5000 10 Seema 20000 20 Rakesh 8000 10 Samata 20000 10 Nitin 8000 30 Output of Above Query
  • 94. GROUP BY to group values from a column, and, if you wish, perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column. Cust_Info C_Id Cname City 1 John Nashik 2 Seema Aurangabad 3 Amita Nagar 4 Rakesh Pune 5 Samata Nashik 6 Ankita Mumbai 7 Bhavika Pune 8 Deepa Mumbai 9 Nitin Nagpur 10 Pooja Pune
  • 95. Acc_Info SELECT City, COUNT(*) FROM Cust_Info GROUP BY city ; City Count(*) Nashik 2 Nagar 1 Pune 2 Mumbai 2 Nagpur 1 SELECT City, COUNT(*) FROM Cust_Info GROUP BY city having City =‘Pune’; City Count(*) Pune 2
  • 96. The SQL EXISTS Operator The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns true if the subquery returns one or more records. SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name FROM table_name WHERE condition);
  • 97. Exists (Set Membership) Store_Name Sales Txn_Date Los Angeles 1500 Jan-05-1999 San Diego 250 Jan-07-1999 Los Angeles 300 Jan-08-1999 Boston 700 Jan-08-1999 Region_Name Store_Name East Boston East New York West Los Angeles West San Diego Table Geography Table Store_Information SELECT SUM(Sales) FROM Store_Information WHERE EXISTS (SELECT * FROM Geography WHERE Region_Name = 'West'); SUM(Sales) 2750
  • 98. hotel Hotel_No Name City H111 Empire Hotel New York H235 Park Place New York H432 Brownstone Hotel Toronto H498 James Plaza Toronto H193 Devon Hotel Boston H437 Clairmont Hotel Boston Room_No Hotel_No Type Price 313 H111 S 145.00 412 H111 N 145.00 1267 H235 N 175.00 1289 H235 N 195.00 876 H432 S 124.00 898 H432 S 124.00 345 H498 N 160.00 467 H498 N 180.00 1001 H193 S 150.00 1201 H193 N 175.00 257 H437 N 140.00 223 H437 N 155.00 room Hotel_No Guest_No Date_From Date_To Room_No H111 G256 10-AUG-99 15-AUG-99 412 H111 G367 18-AUG-99 21-AUG-99 412 H235 G879 05-SEP-99 12-SEP-99 1267 H498 G230 15-SEP-99 18-SEP-99 467 H498 G256 30-NOV-99 02-DEC-99 345 H498 G467 03-NOV-99 05-NOV-99 345 H193 G190 15-NOV-99 19-NOV-99 1001 H193 G367 12-SEP-99 14-SEP-99 1001 H193 G367 01-OCT-99 06-OCT-99 1201 H437 G190 04-OCT-99 06-OCT-99 223 H437 G879 14-SEP-99 17-SEP-99 223 Guest_No Name City G256 Adam Wayne Pittsburgh G367 Tara Cummings Baltimore G879 Vanessa Parry Pittsburgh G230 Tom Hancock Philadelphia G467 Robert Swift Atlanta G190 Edward Cane Baltimore booking guest
  • 99. List full details of all hotels. SELECT * FROM Hotel; List full details of all hotels in London. SELECT * FROM Hotel WHERE city = ‘London’; List the names and addresses of all guests in London, alphabetically ordered by name. SELECT guestName, guestAddress FROM Guest WHERE address LIKE ‘%London%’ ORDER BY guestName; List all double or family rooms with a price below £40.00 per night, in ascending order of price. SELECT * FROM Room WHERE price < 40 AND type IN (‘D’, ‘F’) ORDER BY price; What is the average price of a room? SELECT AVG(price) FROM Room;
  • 100. List the number of rooms in each hotel. SELECT hotelNo, COUNT(roomNo) AS count FROM Room GROUP BY hotelNo; List the price and type of all rooms at the Grosvenor Hotel. SELECT price, type FROM Room WHERE hotelNo = (SELECT hotelNo FROM Hotel WHERE hotelName = ‘Grosvenor Hotel’); What is the total income from bookings for the Grosvenor Hotel today ? SELECT SUM(price) FROM booking b, room r, hotel h WHERE (b.datefrom <= ‘SYSTEM DATE’ AND b.dateto >= ‘SYSTEM DATE’) AND r.hotelno = h.hotelno AND r.hotelno = b.hotelno AND r.roomno = b.roomno AND h.hotelname = ‘Grosvenor’
  • 101. Assignment C_Id Cname City 1 John Nashik 2 Seema Aurangab ad 3 Amita Nagar 4 Rakesh Pune 5 Samata Nashik 6 Ankita Mumbai 7 Bhavika Pune 8 Deepa Mumbai 9 Nitin Nagpur 10 Pooja Pune C_Id Acc_Type Amount 1 Current 5000 2 Saving 20000 3 Saving 70000 4 Saving 50000 6 Current 35000 7 Loan 30000 8 Saving 50000 9 Saving 90000 10 Loan 8000 11 Current 45000 Cust_Info Acc_Info
  • 102. Assignment • Show the cname, Acc_Type, amount information of customer • who is having an saving account. • Display the data using Natural, left and right join. • Display the information of customers living in the same city as • of ‘pooja’. • Display the information of account, having less amount than average amount throughout the bank. • Display the C_id having maximum amount in account. • Display the amount and acc_type of those customers whose amount is the minimum amount of that Acc_type. • Display the amount of those accounts whose amount is higher than amount of any saving • account amount.
  • 103. DATA CONTROL LANGUAGE DCL commands are used to enforce database security in a multiple database environment. • Two types of DCL commands are • Grant • Revoke • Database Administrator's or owner’s of the database object can provide/remove privileges on a database object. Syntax of Grant : GRANT privileges ON object TO user; Example : GRANT SELECT, INSERT, UPDATE, DELETE ON contacts TO 'smithj'@'localhost'; GRANT ALL ON contacts TO 'smithj'@'localhost'; GRANT SELECT ON contacts TO '*'@'localhost';
  • 104. Syntax The syntax for revoking privileges on a table in MySQL is: REVOKE privileges ON object FROM user;
  • 105. TCL command Transaction Control Language(TCL) commands are used to manage transactions in database.These are used to manage the changes made by DML statements. It also allows statements to be grouped together into logical transactions. Commit command Commit command is used to permanently save any transaction into database. Following is Commit command's syntax, commit; Rollback command This command restores the database to last commited state. It is also use with savepoint command to jump to a savepoint in a transaction. Following is Rollback command's syntax, rollback to savepoint-name;
  • 106. Savepoint command savepoint command is used to temporarily save a transaction so that you can rollback to that point whenever necessary. Following is savepoint command's syntax, savepoint savepoint-name;
  • 107.
  • 108. Select INTO • SELECT column1, column2, column3, ... INTO newtable [IN externaldb] FROM oldtable WHERE condition;
  • 109. Insert into • INSERT INTO table2 SELECT * FROM table1 WHERE condition;
  • 110. Fill in the blanks 1) DCL contain …………………&…………………commands. 2) Primary Key is the combination of…………………&…………………. 3) After table command operates on …………………ends. 4) …………………cmd is used to save data in database. 5) The condition in group by clause is given by …………………clause. 6) A query that include group by clause is called…………………query. 7) Duplication of data avoid by …………………Keyword.

Editor's Notes

  1. 97