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

1. SQLClassRoom (1)

Uploaded by

Pawan Chavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

1. SQLClassRoom (1)

Uploaded by

Pawan Chavan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 126

SQL and PLSQL

-----------------------------------
SQL -
What is the SQL
- Structure Query Language.

Relational database
-----------------------------------

Tabular
Columns and row
Column Fixed
Rows unlimited
Data Rows operation perform
1. Add data
2. Change info data
3. erase, delete
4. Get data fetch extract

SQL -
its single line query.
------------------------------
What is PL SQL
- Provide interface for programming language and RDMS.
- Procedure language extension
- We can write the block of code for database.
- Its multi-line block of code

if - decision making
switch - we choose single thing from multiple
loop - iteration single statement multiple time with specific limit

trigger
view
function
procedure
-------------------------------------------
I am a programmer.
-------------------------------------------
Types of software’s
1. System SW - OS Compilers MS, Mac, Linux,
2. Utility SW - Drivers Audio, Printer
3. Application SW - Website, calculator, Spredsheet, Notepad, BookMySho

World SW - Application SW
Data - Any useful information.
Processed, meaningful information is data.
-----------------------------------------------------------------------------
What is the Database

1. It is a meaningful data, its collection of related data.

pg. 1
2. Systematic collection of data.
3. A database is related systematic or orgnized stored information, that can easily access and
manage.

Components of database
1. Hardware - Server disk space, RAM, Screen
2. Software - To manage the data
3. Data - Information
4. Procedure - Method, Way (SOP)
5. Databae access language - SQL
---------------------------------------------------------------------------
Time - 08.00 PM
Day 2 - 04-04-2023

What is the use of the database


Why to use the database
What is the benifits of the databse

1) To store the information. To store the data.


2) Database for business.
Scale, Suply demand, Track on customer, track on goods.
3) Secure the information.
To provide the role base access.
4) Database for education.
5) Helthcare
6) Managing the data.
7) Retrive or get the data.
8) Orgnization and data mgmt.
9) Data consistency.
10) Performance (get, change-ipdate, delete)
11) Search specific information.
12) Client server architecture support.
13) Control
14) Inegrity

--------------------------------------------------------
Types of the database
1. Relational database - Table
2. Network databse - nw data model related databse
3. Graph database -
4. Hierachical database -
5. Non relational - NO SQL key value - Data scientist
6. object oriented database - complex data model
--------------------------------------------------------
File system vs DBMS

1. RDBMS supports to client server architecture


1. File system is Specifi for the users.

2. DBMS easy - Serch operation


2. FS - deficult serch operation

pg. 2
3. DBMS - Sorting easy
3. FS - Is very hard

4. Attribute base search

5. Concurrency - Work at a time with multiple users.

6. Avoid duplicate.
------------------------------------------------------------
Day 3 - Installation MySQL DBMS

MySQL - Database or Database Management System, Provide by Oracle.

Website visit

Types or Data types


-------------------
DataTypes means to define the nature of data.
A DataType is an attribute to specify the Type of Data that the value can hold.

DataTypeare used to define the variable and columns in SQL.

Data types is the using for to declare the variable.


To sort the nature of information or data.
Type Variable;
data types;

Create database.
Carete table - Column

SQL and MySQL


SQL - Structure Query language
SQL is used for RDBMS - Relational database MS

Arc- crete, alter


Data - insert, update, delete
---------------------------------------
SQL 90 %

Oracle - MySQL - Free - Opensource

Oracle - Oracle -- Paid


IBM - DB2 -- Paid
Microsoft MS SQL Server -- Paid

Community version free

80443

pg. 3
Client - Server

------------------------------------------

Databse - Tables

Name - text, Charaters


Email - text, char + symbols
Mobile - DigitsNumber
Address - charactrs, symbols, numbers
Terms conditions - truefalse

SQL Mejor three types of the data types avialble in SQL


1. String (Character and byte)
2. Numeric
3. Date
4. JSON
5. Special Types

Charates Types

char - char(size) - 0-255 bytes


varchar - varchar(size) - 0-65535 bytes
binary - binary(size) - 0-255 bytes
text - text - 1677215 char
mediumtext - 8 git
longtext - 10 digit
-------------------------------------------------------
Numeric data types
MySQL supports all standard SQL numeric data types.
These types include the exact numeric data types (INTEGER, SMALLINT, DECIMAL, and NUMERIC),
as well as the approximate numeric data types

1. boolean - truefalse - (non zero true , zero false)


2. tinyint - -128 to 127 - 1 byte
3. smallint - -32768 to 32767 - 2 bytes
4. intinteger - 2147483648 to 2147483647 4 byte
5. bigint - 19 digit 8 bytes 9223372036854775808
6. float(p) - 4 bytes
7. double(size, d) - d- after decimal 8 bytes
8. Decimal(size, d) - maximu 65, after decimal 30 , default 10 digit

DATE, TIME, DATETIME, TIMESTAMP, and YEAR.


Date
date - YYYY-MM-DD - 1000-01-01 max 9999-12-31
datetime - YYYY-MM-DD HH-mm-ss
datetimestamp YYYY-MM-DD hh-mm-ssffffff

fsp - Fractional Second precision

pg. 4
----------------------------------------------------------------------------------------
Day 4 - SQL Commands [Statement]

Database - Table - coulumn


DATABASE and SCHEMA in MySQL is equvlant;

What is caommads
Command is instruction to the computer system.
SQL Command is executable statement for database.
SQL Commands are use to communicate with the database.
SQL commands used to perform the operations on database.
SQL command is SQL query.

Prog C- C compilor
SQL statment is execute by MySQL databse engine;

What is use of SQL statememt


To communicate with the database.
To perform the operation on the database. [insert,update,delete,select]

Command- Stetement - Query;


-------------------------------------------
Different types of SQL commands
In SQL there are four types of commands

1. DML - Data manuplation language


2. DDL - Data defination language
3. TCL - Transaction control language
4. DCL - Data control language

1. DML - Data manipulation language


Used to perform the operation on table.
[insert,update,delete,select]

2. DDL - Data defination language


Perform the operatoin on database
CREATE, ALTER, DROP, TRUNCATE

3. TCL - Transaction control language


To control the transaction.
COMMIT, ROLLBACK, SAVE POINT
Bank account -
RAMA fees - Dr - Class - cr
SP
100 - 0

4. DCL - Data control language


Role Base access control
GRANT, REVOKE

pg. 5
Admin - Higher
Teaching staff - Course
HR - Recrutment
Other - Viewr

------------------------------------------------------------
SELECT CRATE

------------------------------------------------------------
Query to Show database list.
SHOW DATABASES;

Query to Create databse


Systax CREATE DATABASE Database_Name;
E.g CREATE DATABASE DB_NAME;

How to check current selected database


SELECT DATABASE();

DATABASE() is mysql function to provide the current selected database.

Switch on Database.
Sysntax USE Database_Name;
E.g USE GTH;

Create table;
Sysntax CREATE TABLE Table_Name (col_name data_type constraint, col2 name data type
constraint);
E.g
1.CREATE TABLE teachers (Name varchar(50) NOT NULL, MobileNumber varchar(10), Address
varchar(250));
2.CREATE TABLE COURSE_MASTER (COURSE_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
COURSER_NAME VARCHAR(64) NOT NULL, DESCRIPTION VARCHAR(128), CREATED_DATE DATETIME
NOT NULL DEFAULT NOW());

How to check table architecture or table description.


Sysntax DESC TableName;
E.g DESC COURSE_MASTER;

How to check Table list


SHOW TABLES;
-----
INSERT INTO COURSE_MASTER (COURSER_NAME, DESCRIPTION) VALUES ('JAVA FULL STACK', 'JAva
full stack developer course offers to students, all subject will cover from scratch');
INSERT INTO COURSE_MASTER (COURSER_NAME, DESCRIPTION) VALUES ('C Programming', 'C
PRogramming');
-----

Different DDL Operation's on table.


1. Create table
Syntax CREATE TABLE TableName (ColumnName DataType Constraint, Col2 Datatype constrant);

pg. 6
Constraint is optional
1. CREATE TABLE teachers (Name varchar(50) NOT NULL, MobileNumber varchar(10), Address
varchar(250));

2. Add new column in table


Syntax ALTER TABLE TableName ADD col data type constraints;
ALTER TABLE TableNAme ADD (Col1 data type constraint, col2 data type constraint);

E.g
1. ALTER TABLE teachers ADD DOJ DATETIME DEFAULT NOW();
2. ALTER TABLE teachers ADD (EMAIL varchar(80), SUBJECT varcahr(50), TEACHER_ID INT NOT
NULL);
3. ALTER TABLE COURSE_MASTER ADD (COURSE_DURATION TINYINT NOT NULL DEFAULT 0,
COURSE_FEES DECIMAL(6, 2) NOT NULL DEFAULT 0);

3. Rename the table


Syntax ALTER TABLE TableName RENAME TO NewTableName;
e.g 1. ALTER TABLE STUDENT_MASTER RENAME TO STUDENT_DATA;
2. ALTER TABLE subject RENAME TO COURES;

4. Rename column name


syntax ALTER TABLE TableName RENAME COLUMN ExistingC TO NewName;
1. ALTER TABLE STUDENT_DATA RENAME COLUMN STUDENT_NAME TO NAME;
2. ALTER TABLE COURES RENAME COLUMN SUBJECT_NAME TO COURSE_NAME;

5. Alter the column data type


Syntax ALTER TABLE TableName MODIFY Colname NewDataType;
1. ALTER TABLE STUDENT_DATA MODIFY NAME VARCHAR(256);
2. ALTER TABLE coures MODIFY COLUMN COURSE_NAME VARCHAR(100) NOT NULL;

7. Drop the column


Syntax ALTER TABLE TableName DROP COLUMN ColumnName;
ALTER TABLE STUDENT_DATA DROP COLUMN MOBILE_NUMBER;
ALTER TABLE coures DROP COLUMN DESCRIPTION;

8. Drop the table delete the tabel


Syntax DROP TABLE TableName;
DROP TABLE STUDENT_DATA;
DROP TABLE coures;
---------------------------------------------------------------------
Day 5 - 10-04-23

Today we are goning to perform basics the operations on table


DML Oerations on table (DML - Data manuplation language)
1. Insert data into table
2. Get data from table
3. Update data from table
4. Delete data from table

1. Insert data into table


Syntax INSERT INTO TableName

pg. 7
Using specific columns
e.g. INSERT INTO teachers
(TeacherName, MobileNumber, Address, SUBJECT, TEACHER_ID)
VALUES
(SACHIN GIRI, 9087658765, Hivra manjalgaon Beed, SQL, 1);

Using all columns


INSERT INTO teachers VALUES (NAMDEV, '9988776655', 'Pune', '2023-04-10', 'SQL', 2);

2. Get data from table


1. Get all data from table
Syntax SELECT FROM TableName;
SELECT FROM teachers;

2. Get specific data from table


Syntax SELECT colNem, Col2, Col3 FROM TableName;
SELECT TEACHER_ID, TeacherName FROM teachers;

3. Update data from table


Syntax UPDATE TableName SET col='value', col2='value' WHERE condition;
UPDATE teachers SET TeacherName='AJAY DESHMUKH' WHERE TEACHER_ID=2;
UPDATE teachers SET TEACHER_ID=4, TeacherName='Viswajeet Swami'
WHERE DOJ='2023-04-10 210011';

4. Delete data from table


Syntax DELETE FROM TableName WHERE Condition;
E.G. DELETE FROM teachers WHERE TEACHER_ID=4;

----------------------------------------------------------------------
Day 7 - 12-04-2023
Delete DML - WHERE - SPECIFIC
Truncate - ALL table records remove
Drop - Table structure + records.

CREATE TABLE Departments (D_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME
VARCHAR(50) NOT NULL, DESCRIPTION VARCHAR(250), CREATED_ON DATETIME NOT NULL DEFAULT
CURRENT_TIMESTAMP());
Query OK, 0 rows affected (0.02 sec)

INSERT INTO departments (NAME, DESCRIPTION) VALUES ('HR', 'Human Resource');


INSERT INTO departments (NAME, DESCRIPTION)
VALUES ('HR', 'Human Resource'),
('Training', 'Training teachers'),
('IT', 'Information Technologiy');

mysql INSERT INTO departments (NAME, DESCRIPTION)


- VALUES ('HR', 'Human Resource'),
- ('Training', 'Training teachers'),
- ('IT', 'Information Technologiy');

pg. 8
Query OK, 3 rows affected (0.00 sec)
Records 3 Duplicates 0 Warnings 0

CREATE TABLE courses (C_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(100)
NOT NULL, FEES DECIMAL(10,2) NOT NULL DEFAULT 0, DURATION INT NOT NULL, DESCRIPTION
VARCHAR(250) ,LAUNCHED_ON DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP());
Query OK, 0 rows affected (0.03 sec)

1. Delete is a DML operation.


Using delete we can remove the records from table.
We can remove all or soecific targated records from table.

Syntax for delete


1. Delete all records
DELETE FROM TableName;

2. Delete specofic record - selected -targated


DELETE FROM TableName WHERE condition;
e.g. DELETE FROM course WHERE C_ID = 3;

2. TRUNCATE
Truncate is DDL command.
We use truncate to remove all records from table.
Truncate dosent impact on table structure.
We cannot use WHERE clause in truncate.

3. DROP
DROP is DDL command
Drop caommad remove all table data as well as remove the table structure.

---------------
Clone means to create the rplaca of table either includeing data or not.
There are three ways to clone the table in MySQL

1. Simple cloning.
2. Shallow cloning.
3. Deep cloning.

1. Simple cloning.
In simple cloning we can clone the data as well as table structure,
but we can not clone the Primary key and default constraint.

Synstax CREATE TABLE tableName SELECT FROM TagateTable;


e.g. CREATE TABLE courses_new SELECT FROM courses;

2. Shallow cloning.
In shallo cloning we can copy the table structure only.
In shallow cloning table structure will get clone as it is.
In shallo cloning we cannot copy the data.
Sysntax CREATE TABLE NewTableName LIKE OldTableNAme;
CREATE TABLE courses_shallo_clone LIKE courses;

pg. 9
3. Deep cloning.
In deep cloning we can copy table structure as it is and table data also.

Syntax
CREATE TABLE NewTableName LIKE oldTableName;
INSERT INTO NewTableName SELECT FROM oldTableName;
E.g.
CREATE TABLE courses_deep_clone LIKE courses;
INSERT INTO courses_deep_clone SELECT FROM courses;

Table clone
1. Simple clone
2. Shallow clone
3. Deep clone

1. Simple clone - structure and data but not index, Auto increment,
CREATE TABLE simple_clone SELECT FROM COURSE_MASTER;

2. Shallow clone - structure with constraints not data.


CREATE TABLE shallow_clone LIKE COURSE_MASTER;

3. Deep clone - structure, constraint, data.


CREATE TABLE deep_clone LIKE COURSE_MASTER;
INSERT INTO deep_clone SELECT FROM COURSE_MASTER;

-----------------------------------------------------------------------
Day 8 - 12-04-2023
Ajenda for upcoming few days

1. SQL Query Execution order


2. What is clause in SQL
3. SELECT clause
4. FROM clause
5. WHERE clause
6. ORDER BY clause
7. GROUP BY cluse
8. HAVING cluse
9. LIMIT clause
10. ALies in SQL

1. SQL Query Execution order


- Execution order means, the sequence of query execution, which clause will execute first.
SQL query clauses execution sequentinal order.

2. What is clause in SQL


Types of clauses and its use.
1. A clause is built is function that helps us to fetch the required records from database table.
2. SQL clause helps to retrive the specific records from table.
3. SQL clause are helpsto deal with data easily store, retrice, update, delete, filter, anlyze.
4. Using SQL clause we can perform the conditinal operation during get data.

pg. 10
SQL clause list SELECT, FROM, WHERE, ORDER BY , GROUP BY, HAVING, LIMIT, etc.

------------------------------------------------------------------------------------------------------

3. SELECT clause
To specify the columns of table
To get limited data.
To get required data.
SELECT FROM TableName
SELECT col, col, col FROM TableName;

SELECT FROM courses;


SELECT C_ID, NAME FROM courses;

4. FROM clause
- To specify the table we uses FORM clause.
- FORM clause is used in SQL, tells to the compilor from which table data to fetch.
- We cannot use FORM clause alone, we need to use at least SELECT clause.
Synatx to use FROM caluse.

SELECT FROM TableName;


SELECT FROM TableName WHERE Condition ;
SELECT FROM TableName, TableName;

e.g.SELECT FROM courses;


select from courses where c_id=2;
SELECT FROM departments, employees where departments.d_id=employees.d_id;

5. WHERE clause
- We use WHERE caluse in few DML operations. (SELECT, UPDATE, DELETE)
- In WHERE caluse we need to use comparison operators.
- Where is useful for filter the base data or base table.

Syntax SELECT col.. FROM TableName WHERE Condition ;


e.g SEELCT FROM courses WHERE c_id=1;

What is the condition


The combination of = (col + comparison operator + value);
e.g. C_ID = 1;

In SQL condition we can use use comparison operators and some other operators.
Like
= equal to

or != not equal to
gretor than
less than
= gretor than equal to
= Less than equal to
AND
OR

pg. 11
NOT
BETWEEN
IN

= equal to
SELECT FROM employees WHERE BLOOD_GROUP = 'O';

or != not equal to
SELECT FROM employees WHERE BLOOD_GROUP != 'O';
SELECT FROM employees WHERE BLOOD_GROUP 'O';

gretor than
SELECT FROM employees WHERE SALARY 15000;

less than
SELECT FROM employees WHERE SALARY 15000;

= gretor than equal to


SELECT FROM employees WHERE SALARY = 13000;

= Less than equal to


SELECT FROM employees WHERE SALARY = 13000;

AND
SELECT FROM employees WHERE (e_id = 9) AND (SALARY 14000);

OR
SELECT FROM employees WHERE Blood_group = 'O' OR SALARY = 13000;

IS-NOT
SELECT FROM departments where description IS NOT NULL;

BETWEEN
select from employees where salary BETWEEN 12000 AND 15000;
select from employees WHERE DATE_OF_BIRTH BETWEEN '1981-01-01' AND '1990-12-31';

IN
SELECT FROM employees where e_id IN (1,2,3,11,12,13);
-----------------------------------------------------------------------------------------

LIKE operator.
What is the use of LIKE operator.
To fetch data in pattern.
Used to find the correlated pattern. (matchin or similar)
In LAIKE we can use two wild card characters.
% - Percent -
_ - Underscore -

Syntax for LIKE


SELECT FROM TableName WHERE ColumnName LIKE 'wild card characters';
SELECT FROM courses WHERE NAME LIKE '%a%';

pg. 12
%A% - To find the records lives A character in any position.
%A - To fin the record ends with a.

6. ORDER BY clause
- ORDER BY clause helps us sort the records of a column in a table using the ASC and DESC
keywords.
- To sort the values in Ascending or Decending order.
- We can perform this cluse with all kind of data tyes.
- Default order is ASC;
- We can sort the data column position number.

Syntax. SELECT FROM TableName ORDER BY col ASCDESC;


mysql SELECT FROM departments ORDER BY CREATED_ON ASC;
SELECT FROM departments ORDER BY 1 ASC;

7. GROUP BY cluse
What is the group by
- Group by is SQL query, used to group the data row based on the column.
- Group by clause is used, to orgnized similar types of data in to groups.

What is the use of group by clause


Get grouped data for analysis. OR reporting.
Businness decision.

Syntax SELECT cols..., FUNCTION() FROM TableName


WHERE condition
GROUP BY Col
ORDER BY col

E.g. SELECT COUNT(), D_ID FROM employees GROUP BY D_ID;


SELECT COUNT(), D_ID FROM employees GROUP BY D_ID ORDER BY D_ID;
SELECT COUNT(), D_ID, BLOOD_GROUP FROM employees GROUP BY D_ID,
BLOOD_GROUP ORDER BY 1;
mysql SELECT BLOOD_GROUP,D_ID, COUNT() FROM employees GROUP BY
BLOOD_GROUP, D_ID ORDER BY D_ID;
mysql SELECT SUM(SALARY), D_ID FROM employees GROUP BY D_ID;
SELECT MIN(SALARY), D_ID FROM employees GROUP BY D_ID;
mysql SELECT DURATION, COUNT(DURATION) FROM courses GROUP BY DURATION;

mysql SELECT DURATION, COUNT(1) FROM courses GROUP BY DURATION;

What is the aggrigate functions


An aggregate function performs a calculation on a set of values, and returns a single value.
Except for COUNT()

Aggrigate functions.
SUM(col);
AVG(col);
COUNT(col), count ()

pg. 13
MIN(col)
MAX(col)
mysql SELECT count(), D_ID FROM employees WHERE SALARY 12000 GROUP BY D_ID;

8. HAVING cluse
- The HAVING clause in SQL is used to filter the results obtained by the GROUP BY clause
based on some specific conditions.
- But the WHERE clause can not be used with aggregate functions which is why the HAVING clause is
needed.
- The HAVING clause is generally used along with the GROUP BY clause.

SELECT col...., AG FUNCTION() FROM tabel


WHERE condition
GROUP BY col...
HAVING condition
ORDER BY col

mysql SELECT COUNT(), D_ID FROM employees GROUP BY D_ID HAVING COUNT() =
6;
mysql SELECT COUNT(), D_ID FROM employees GROUP BY D_ID HAVING COUNT() 5;

9. LIMIT clause
mysql SELECT FROM CITY LIMIT 20;
mysql SELECT FROM CITY WHERE CITY LIKE 'A%';

10. Alies in SQL


- Alias in SQL is basically a temporary name that is given to a table or a column while writing a query.
Alis exists durion execution of the query.
After giving alies the actual tabl eor column name does not affetct.
Alies make column or table name more readable.

Syntax for table SEELCT col AS 'TOP RECORDS' FROM TableName;


Syntax for table SELECT col FROM TableName AS 'SENUIOUR_EMPLOYEE';

mysql select COUNT() EMP COUNT, D_ID AS DEPARTMENTS FROM employees GROUP BY D_ID;
mysql select COUNT() AS EMP COUNT, D_ID AS DEPARTMENTS FROM employees GROUP BY D_ID;
mysql select e_id AS 'EMPLOYEE ID', name 'EMPLOYEE NAME', salary 'MONTHLY SALARY' from
employees;
----------------------------------------------------------------------------------------------
18042022

Today we are going to star the new chapter, lesson.


Operators in SQL.

What is the operator


- Operators is special symbols we can perform the some specific operation.

What is the SQL operator?


- Operator is a Special Symbols and Keywords it has special meanings,

pg. 14
the can perform the operations on operands such as arithmetic, comparison operators.

What is operands
Operands is constant and columns in SQL.

What is the use of operators in SQL


- Operators are mostly used in WHERE condition, To get targeted or specific data, from large amount
of data.
- To get data from stored data, by performining specific logical, arithmatic or computational
operation,
we use operators.
- To filter the data.

Types of the operators.


1. Arithmatic
2. Comparision
3. Logical operators

1. Arithmatic
1. The SQL Arithmetic operator is used to perform arithmetic computations and operations on the
two operands
or the numerical data present in the tables of the database.
2. Arithmetic operations like addition, subtraction, multiplication, division, and modulus on the
operands of the operator.
3. The SQL Comparison Operators are used with the WHERE clause.

+ - Addtion operator - To add values


- - Substration operator - To subtract the values
- Multiplication - To multiply
- Division - To devide and get division
% - Modulas - To get remender
select from employees WHERE e_id = (1+10
select E_ID, NAME, SALARY+123 from employees;
select d_id3, NAME from departments;
select 10015;
select 100+15;
select 100-15;
select 10015;
select 100%15;

2. Comparision operator
Comparision operator is relational operators.
The have check the relation between two operands or columns.
SQL comparision operators is used to compare the two operands or the two values presen in
the table.
e.g. 1020;
20=20;

Comparision operator compre the expression.


What is the expression
(10 = 20 AND 30 = 30)

pg. 15
We use comparision operator in WHERE Condition.
= Equal to
!= Not equal to
Not equal to
Greter than
less than
= Greter than equal to
= Less tha equal to

= Equal to
SELECT FROM courses WHERE FEES = 9000;
mysql SELECT FROM courses WHERE DURATION = 11;
mysql SELECT FROM courses WHERE DURATION != 11;

!= Not equal to
mysql SELECT FROM courses WHERE DURATION != 11;

Not equal to
mysql SELECT FROM courses WHERE DURATION 11;

Greter than
mysql SELECT FROM courses WHERE DURATION 10;

less than
mysql SELECT FROM courses WHERE DURATION 10;

= Greter than equal to


mysql SELECT FROM courses WHERE DURATION = 10;

= Less tha equal to


mysql SELECT FROM courses WHERE DURATION = 10;

3. Logical operators
hese are used to combine or negate multiple conditions in SQL queries.
SQL logical operators are used to perform the boolean operation on the operands or two
data values.
Logical operators are used in the WHERE condition.

1. AND
2. OR
3. NOT

Special Logical operators


1. ALL
2. ANY
3. EXISTS
4. BETWEEN
5. IN
6. LIKE
-------------------------------------------------------------------------------

pg. 16
1. AND
We use AND operator when our all criteries should match with condition.
mysql SELECT FROM courses WHERE c_id = 2 AND duration = 10;
mysql SELECT FROM employees WHERE salary = 13000 AND BLOOD_GROUP = 'A';
mysql SELECT FROM employees WHERE salary = 13000 AND BLOOD_GROUP = 'A' AND
GENDER = 'MALE';
mysql SELECT FROM employees WHERE salary = 13000 AND BLOOD_GROUP = 'A' AND
GENDER = 'FMALE';
mysql SELECT FROM employees WHERE d_id=4 AND salary 10000;

2. OR
OR operators gives us result when any one condition matches.
When do not match with any condition return empty result set.

mysql select E_ID, NAME, SALARY, BLOOD_GROUP, EMAIL_ID from employees WHERE
BLOOD_GROUP= 'A' OR BLOOD_GROUP = 'N';
mysql select E_ID, NAME, SALARY, BLOOD_GROUP, EMAIL_ID from employees WHERE
BLOOD_GROUP= 'D' OR BLOOD_GROUP = 'N' OR SALARY = 10;
mysql select E_ID, NAME, SALARY, BLOOD_GROUP, EMAIL_ID from employees WHERE
BLOOD_GROUP= 'A' OR BLOOD_GROUP = 'N' OR SALARY = 14000;
mysql select E_ID, NAME, SALARY, BLOOD_GROUP, EMAIL_ID, D_ID from employees WHERE
BLOOD_GROUP= 'A' OR D_ID=3;

3. NOT
mysql SELECT FROM COURSES WHERE DESCRIPTION = NULL;
mysql SELECT FROM COURSES WHERE DESCRIPTION IS NULL;
mysql SELECT FROM COURSES WHERE DESCRIPTION IS NOT NULL;
mysql SELECT FROM COURSES WHERE NOT c_id=12;

Special Logical operators


1. ALL
2. ANY
3. EXISTS

4. BETWEEN
To get data in the form of range.

mysql SELECT FROM city WHERE city_id BETWEEN 40 AND 50;


mysql SELECT FROM employees WHERE DATE_OF_BIRTH BETWEEN '199-01-01' AND '1995-12-31';
mysql SELECT FROM employees WHERE SALARY BETWEEN 10000 AND 12000;

5. IN
To find the data form of list.
mysql SELECT FROM city where city_id IN(12, 13 , 14 , 15, 16, 17, 17, 18, 88,77,55,44);
mysql SELECT FROM city where city_id IN(12, 13 , 14 , 15, 16, 17, 17, 18, 88,77,55,44) OR
CITY='Vancouver';
mysql SELECT FROM city where CITY IN ('Vancouver', 'Tokat', 'Urawa');

6. LIKE
Search data in pattern format.

pg. 17
Find the records where length is 9 char.
mysql select from courses where name like '_________';

Find the course name where third character is s.


mysql select from courses where name like '__S%';
---------------------------------------------------------------------

21-04-2023
Integrity Constraints.
---------------------------------------
Keys in DBMS.

Some alternative name from DBMS.


1. Table => Relation
2. Column => Attribute
3. Row => Tuple, Record

Table: Students
SID RollNo Name Branch Mobile emailid Year
908765432
1
1 Anand CS 1 [email protected] 1
908765432
2
2 manish Mech 2 [email protected] 2
908765432
3
3 suman IT 3 [email protected] 3
Shures 908765432
4
2 h Civil 4 [email protected] 4
908765432
5
1 Vikas Eletric 5 [email protected] 3
Eletronic 908765432
6
4 Nilesh s 6 [email protected] 2
908765432
7
5 Vivek ATC 7 [email protected] 1

What is the Key?


-> Key is a set of attributes uniquely identify record in the relation.
-> Key are used to uniquely identify any record or row of data from the table.
-> Key are the basic requirement of the RDBMS.

What is the use of Keys?


-> To maintain the relationship between tables.
-> To maintain unique data.
-> To avoid data redundancy. Repeated.

There are different types of Keys in DBMS.


1. Super Key
2. Candidate Key
3. Primary Key
4. Alternate Key
5. Foreign Key
6. Composite Key

pg. 18
Keys in DBMS

DBMS concepts about the database.

Table -> relation


Column -> field -> attribute
Row -> record -> tuple

What is the key?


What is use of key?
What is the need of key?
How many types of Keys in DBMS?

What is the key?

1. Keys are used to uniquely identify any record from the table.
2. Key is an attribute or set of attribute that uniquely identify each record of relation.

Table: Student

SID Name Mobile emailed Course


1 Sachin T 9998877665 [email protected] CS
2 Sachin G 9988776654 [email protected] IT
3 Ajit A 9988776653 [email protected] CE
4 Saurav G 9988776652 [email protected] ME

Table: School
RollNo Name Class Address
1 Sachin 1 Pune
1 Suraj 2 Mumbai
1 Sushant 3 Kolhapur
2 Sneha 1 Dharashiv
2 Shubham 2 Nashik
3 Santosh 3 Sangli

What is use of key?


What is the need of key?

1. Keys in DBMS are introduced to avoid the data redundancy. (to avoid the duplicate entries)
2. Keys are used to established the relationship between tables.
3. Keys are basic requirement for the RDBMS.

How many types of Keys in DBMS?


There are many types are available in DBMS, but we are going to learn few important types.
1. Super Key

pg. 19
2. Candidate Key
3. Primary Key
4. Alternate – Secondary key
5. Foreign key
6. Composite key

1. Super Key
a. Super key is the set of all keys which can uniquely identify the records of the table.
b. Super key is a collection of unique attribute form the relation.
c. Super key is a combination of columns that uniquely identifies any row within the table.
d. Super key is a theoretical concept.

Home Work: How many possible super keys on table.

Examples of super key above table


1. {SID}
2. {Mobile}
3. {Email}
4. {SID, NAME}
5. {SID, COURSE}
6. {RollNo, Class}
7. {Name, class, address}

2. Candidate Key
a. The candidate key is the minimal set of attribute that can uniquely identify a tuple.
b. Minimal -> as minimum as
c. Candidate key is super key whose proper subset is not a super key. (Home work -> set,
subset, proper subset)
d. Is super key with no repeated data as called as candidate key.
e. Candidate key can contain null value
f. Every table must have single candidate key
g. There can one or more candidate keys in a table.
h. Every candidate key is super key but every super key is not candidate key.

Examples of candidate key


a. {SID}
b. {Mobile}
c. {Email}
d. {SID, NAME}

3. Primary Key
a. One candidate key with no null value called primary key.
b. It is unique value
c. It cannot contain null value
d. It can identify only one tuple at a time
e. Primary key can have multiple columns on the table
f. We can assign only one primary key in a table.

e.g email, mobile, aadhaar, PAN, SID

pg. 20
4. Alternate – Secondary key
a. The candidate key other than primary key called alternate key.
b. The alternate key is the key that has not been selected as primary key.
c. Alternate key is called secondary key.
d. Alternate keys accept repeated values.
e. It contains one or multiple columns

5. Foreign key

Table: Department
DID (PK) NAME
1 Civil
2 Mechanical
3 Information Technology
4 Computer Science

Table: Student
SID Name Mobile emailed DID (FK)
1 Sachin T 99988776655 [email protected] 2
2 Sachin G 9988776654 [email protected] 3
3 Ajit A 9988776653 [email protected] 1
4 Saurav G 9988776652 [email protected] 1

a. Column can only accept the values which are present as a values some another table.
b. Foreign is a key, act as primary key in one table and act as reference key in another table.
c. Foreign key establishes the relationship between tables.
d. Foreign can null
e. Foreign key can duplicate values

6. Composite key
a. Unique combination of multiple tuple.
b. A composite key is the key having two or more attributes that together can uniquely identify
the tuple in relation.
c. It act as primary key if there is not primary key.

Table: School
RollNo Name Class Address
1 Sachin 1 Pune
1 Suraj 2 Mumbai
1 Sishant 3 Kolhapur
2 Sneha 1 Dharashiv
2 Shubham 2 Nashik
3 Santosh 3 Sangli

Super -> composite key -> Primary key

pg. 21
Tomorrow
Integrity Constraints.

25/04/2023

1. What is the Constraints in SQL?


2. What is the need of constraint?
3. Why should we use the constraints?
4. How many types of SQL constraints?
5. How to implement the constraints?

1. What is the Constraints in SQL?

 Constraints are a set of rules imposed on the tables of relational databases.


 Constraint means restriction or rule for the data on table.
 Constraints are the rules that we can apply on the type of data in a table.
 While inserting, updating or deleting the records, if we don't follow the rules, we will get the
error.

2. What is the need of constraint?


Why should we use the constraints?

 Constraints mainly used for data integrity.


a. Data integrity means the data contained in the database is accurate, consistent,
and reliable.
 Restrict the insertion unwanted data in database.
e.g. Check
 Constraints also help to enforce limits on the input so that the operation does not lead to
any kind of failure or abortion.

3. How to implement the constraints?

 Constraints can be imposed at the time of the creation of the table or after its creation as
well.
 We can create constraint single or multiple columns of a table.
 We can impose the constraints on the table two different ways
a. Column level

pg. 22
b. Table level
Note: We cannot apply NOT NULL constraint table level.

Understand the NULL


a. NULL is the representation absence of the values.
b. NULL is neither zero nor empty.
c. When you don’t have any value you have to put NULL value.

For more understanding we will see the example.


e.g 1
CREATE TABLE Std (SID INT NOT NULL, SNAME VARCHAR (100), ROLLNO INT);

INSERT INTO Std (SID, SNAME, ROLLNO) VALUES (1, 'AJAY', 21);
INSERT INTO Std (SID, SNAME, ROLLNO) VALUES (2,'', 12);
INSERT INTO Std (SID, SNAME, ROLLNO) VALUES (3, 'SOHAM',0);
INSERT INTO Std (SID, SNAME) VALUES (4, 'RAHUL');
INSERT INTO Std (SID, ROLLNO) VALUES (5, 11);
INSERT INTO Std (SID) VALUES (6);
INSERT INTO Std (SID, SNAME) VALUES (7, NULL);

e.g 2
CREATE TABLE Student (SID INT NOT NULL, SNAME VARCHAR (120), SADDRESS VARCHAR (120));

4. How many types of SQL constraints?


MySQL supports below six types of constraints.
1. NOT NULL
2. UNIQUE
3. DEFAULT
4. CHECK
5. PRIMARY KEY
6. FOREIGN KEY

Let’s see the implementation of Constraints.


1. NOT NULL
 Database column stores the value null when we do not have any value to store.

pg. 23
 Defining NOT NULL, we prevent the storing NULL value in column.
 Can define NOT NULL constraint on any type of column.

e.g.
1. During table creation
a. Column level constraint impose
CREATE TABLE Student (S_ID INT NOT NULL, S_NAME VARCHAR (100) NOT NULL, S_ADDRESS
VARCHAR (100) NOT NULL, COURSE VARCHAR (50));

b. Table level constraint impose


We cannot apply NOT NULL constraint table level.

2. After table creation


ALTER TABLE Student MODIFY COLUMN COURSE VARCHAR (5) NOT NULL;

If you try to impose NOT NULL constraint on table but, table contain the null records you will get
below error.

mysql> alter table book modify column price decimal (8,2) NOT NULL;
ERROR 1138 (22004): Invalid use of NULL value

pg. 24
What is the solution?
1. Delete the all records from table and impose NOT NULL key
2. Set any default value for all records and then impose the NOT NULL KEY

1. Set any default value for all records and then impose the NOT NULL KEY
mysql> update book set price=0 where price is null;
mysql> alter table book modify column price decimal (8,2) NOT NULL;

2. Delete the all records from table and impose NOT NULL key
mysql> delete from table book;
mysql> alter table book modify column price decimal (8,2) NOT NULL;

26-04-2023

2.DEFULT constraint

What is the default constraint?


What is the use of default constraints?
How to apply this constraint?

pg. 25
What is the default constraint?
1. Default constraint are used to set default value to the column
2. When you haven’t pass or add the value to the column default selected value will reflect in
the record.

What is the use of default constraints?


1. When you haven’t pass or add the value to the column default selected value will reflect in
the record.

How to apply this constraint?


1. We can apply DEFAULT constraint two ways.
a. At the time of table creation
b. After table created

a. At the time of table creation


1. Row level
Syntax: CREATE TABLE <TableName> (col DT DEFAULT <DefaultValue>,
Col2 DT DEFAULR <DefaultValue>);
Example :
mysql> CREATE TABLE Std ( SID INT, SNAME VARCHAR(100), SGENDER VARCHAR(10) DEFAULT
'MALE', SCITY VARCHAR(50) DEFAULT 'PUNE' );

mysql> INSERT INTO std (SID, SNAME) VALUES (1, 'SACHIN');


mysql> INSERT INTO std (SID, SNAME, SGENDER) VALUES (2, 'BHAGYASHREE', 'FEMALE');
mysql> INSERT INTO std (SID, SNAME, SGENDER, SCITY) VALUES (3, 'MANDAR', 'MALE', 'MUMBAI');

b. After table created


Add new column

pg. 26
ALTER TABLE std ADD (DOB DATE DEFAULT '1990-01-01' , DOJ DATETIME );

Existing column:
ALTER TABLE std ALTER SNAME SET DEFAULT 'A';

How to drop the default constraint?

Syntax:
ALTER TABLE <TableName> ALTER COLUMN <ColName> DROP DEFAULT;
Eg: ALTER TABLE std ALTER COLUMN SNAME DROP DEFAULT;

UNIQUE constraint

Table: Employee

Sr. No. EMPID DEPT F_NAME M_NAME L_NAME Mobile Email Address
123 1 A B C
124 2 A B D

What is the unique constraint?


1. The unique constraint ensures that all values in columns are different.
2. Unique constraint we can apply single unique on multiple column.
3. Unique constraint restricts the duplicate values.
4. Unique constraint accepts the null values.
5. In single table we can apply unique constrain more than one column.

How to impose the unique constraint?

Unique constraint we can apply two ways.


1. At the time of table creation
2. After the table created.

1. At the time of table creation, we can apply two level


a. First is the Row level
Syntax:
CREATE TABLE <TableName> ( col1 DT UNIQUE, col2 DT UIQUE );

pg. 27
Example:
CREATE TABLE Person (PID INT UNIQUE, NAME VARCHAR(100), EMAIL VARCHAR(100) UNIQUE);

b. Table level
Example:
CREATE TABLE people
( PID INT,
PNAME VARCHAR(12),
PAADHAAR VARCHAR(12),
CONSTRAINT uk_pid UNIQUE(PID),
UNIQUE(PAADHAAR)
);

pg. 28
2.Unique constraint after table created.
Alter table

1. NEW column add

2. Existing column

pg. 29
3. Add with constraint name

27-04-2023

Composite Unique Key – Constraint

Table : student

FNAME MNAME LNAME


A B C
A D C
B D C
B D

Last won’t work, because duplicate record found.

pg. 30
Syntax for the composite key.
We can assign composite key using two ways
1. Time of table creation
Syntax:
CREATE TABLE <TableName>(
COL1 DT,
COL2 DT,
COL3 DT,
UNIQUE (COL1, COL2, …..)
);

Provide the constraint name


CREATE TABLE <TableName>(
COL1 DT,
COL2 DT,
COL3 DT,
CONSTRAINT uk_c_name UNIQUE (COL1, COL2, …..)
);

Example:
CREATE TABLE std (
ROLLNO INT,
FNAME VARCHAR(30),
LNAME VARCHAR(30),
EMAIL VARCHAR(100),
UNIQUE(FNAME, LNAME)
);

mysql> CREATE TABLE std (ROLLNO INT, FNAME VARCHAR(30), LNAME VARCHAR(30), EMAIL
VARCHAR(100), UNIQUE(FNAME, LNAME) );

CREATE TABLE emp(


EID INT,
ENAME VARCHAR(30),
MOBILE VARCHAR(30),
EMAIL VARCHAR(100),
CONSTRAINT uk_emp_mob_eml UNIQUE(MOBILE, EMAIL)
);

2. Table alter
CREATE TABLE DEPARTMENT (DID INT, DCODE VARCHAR(2), DNAME VARCHAR(100));

pg. 31
Added records.

ALTER TABLE <tableName> ADD UNIQUE(col1, col2,…);


Example:
ALTER TABLE department ADD UNIQUE(DID, DCODE);

In the above case, we need to delete the record and maintain the unique key rule.

pg. 32
How to drop Unique constraint

Syntas:
ALTER TABLE <TableName>
DROP INDEX <constrainName>;

How to get Index name?


Execute below query.
SHOW INDEX FROM <TableName>;
Example:
SHOW INDEX FROM employees;

pg. 33
Date: 28-04-2023

4. CHECK
a. The MySQL CHECK constraint is used to force the data.
b. MySQL CHECK constraint is maintaining the Data integrity.
Data integrity means the values that are going to store in a data column, must be
followed by some defined rules, such as range, type or format or data set or list.
c. The check constraint can be applied one or more than one column of a table.

d. How to apply CHECK constraint in MySQL?


1. During the table creation
2. After table created.

1. During the table creation


Syntax:
CREATE TABLE <TableName>
(
Col1 DT,
Col2 DT CHECK (condition)
);

Example:
CREATE TABLE emp
( EID INT CHECK (EID > 0) ,
NAME VARCHAR(100),
GENDER VARCHAR(10) CHECK (GENDER = 'MALE' OR GENDER = 'FEMALE' OR
GENDER = 'OTRHER' )
);

Assign constraint name by user and table level


CREATE TABLE emp1
( EID INT,
NAME VARCHAR(100),
GENDER VARCHAR(10),
CHECK (EID > 0),
CONSTRAINT ck_gender CHECK (GENDER = 'MALE' OR GENDER = 'FEMALE' OR
GENDER = 'OTRHER' )
);

pg. 34
pg. 35
2. After table created assign the constraint.
Syntax:
ALTER TABLE <tableName>
ADD CHECK (condition);

Syntax:
ALTER TABLE <TableName>
ADD CONSTRAINT <ConstraintName> CHECK(Condition);

Example:
ALTER TABLE std
ADD CHECK (SID < 100 AND SID > 0);

ALTER TABLE std ADD CONSTRAINT ch_divisin CHECK(DIVISION = 'A' OR DIVISION =


'B' OR DIVISION = 'C' OR DIVISION = 'D' );

Compare two different columns in single check condition


ALTER TABLE emp ADD CHECK (CONTACT1 <> CONTACT2);

pg. 36
5. PRIMARY KEY
 What is the primary key?
 How to implement the primary key on table?
 How to drop the primary key?

What is the primary key?

 Primary key is the combination of NOT NULL and UNIQUE constrains.


 Primary key not allow duplicate data and not allow null value.
 Primary key helps us to uniquely identify each record.
 A table can contain only one primary key which can be either one column or multiple
columns.
 When primary key contains multiple column is called composite primary key.
 The primary key constraint can be applied to numeric and string data type.

Benefits of primary key


 Prevent duplicate data
 Prevent null values
 Helps to update and delete the record
 Helps set up the relation between tables.
 Primary key gets the index automatically; Index helps to faster record access.

How to implement the primary key on table?

1. At the time of table creation


2. After table created – Alter table
3. Composite Primary key

1. At the time of table creation


a. Row level
Syntax:
CREATE TABLE <tableName>
(
Col1 DT PRIMARY KEY,
Col2 DT,
Col3 DT
)
Example:
CREATE TABLE Dept
(
D_ID INT PRIMARY KEY,
DEPT_NAME VARCHAR(120) NOT NULL,
DEPT_INFO VARCHAR(120) ,
CREATED_DATE TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

pg. 37
INSERT INTO dept (D_ID, DEPT_NAME, DEPT_INFO) VALUES (1, 'HR', 'Human Resorce');

INSERT INTO dept (D_ID, DEPT_NAME, DEPT_INFO) VALUES (2, 'Admin', 'Administration');

b. Table level
Syntax:
CREATE TABLE <tableName>
(
Col 1 DT,
Col2 DT,
Col3 DT,
PRIMARY KEY(ColName)
);

Example:
CREATE TABLE collage
(
C_ID INT,
C_NAME VARCHAR(100),
C_ADDRESS VARCHAR(100),

pg. 38
PRIMARY KEY(C_ID)
);

Second way to create table level primary key with user defined Primary Key Name.

CREATE TABLE <tableName>


(
Col 1 DT,
Col2 DT,
Col3 DT,
CONSTRAINT <PKConstraintName> PRIMARY KEY(ColName)
);

pg. 39
Example:
CREATE TABLE std
(
S_ID INT,
NAME VARCHAR(100),
D_ID INT,
CONSTRAINT pk_std_sid PRIMARY KEY (S_ID)
);

Auto increment on Primary key column

pg. 40
Syntax:
CREATE TABLE <tableName>
(
ID DT PRIMARY KEY AUTO_INCREMENT,
Col2 DT,
Col3 DT
..
);
Example:
CREATE TABLE bank
( BankID INT PRIMARY KEY AUTO_INCREMENT,
BankName VARCHAR(120) NOT NULL,
BankAddress VARCHAR(400)
);

AUTO Increment by user defined initialization

pg. 41
CREATE TABLE bank
( BankID INT PRIMARY KEY AUTO_INCREMENT,
BankName VARCHAR(120) NOT NULL,
BankAddress VARCHAR(400)
);

ALTER TABLE Bank AUTO_INCREMENT=100;

2. Alter table
We can impose Primary key on existing table, but table should follw the all rules for
Primary key.
Such as Column should unique values and column should not null.

Syntax:
ALTER TABLE <TableName>
ADD PRIMARY KEY(colName);

Example:
ALTER TABLE property
ADD PRIMARY KEY(PID);

pg. 42
3. Composite Primary Key
We can apply Primary Key on two or more columns together.

a. At the time of table create


Syntax:
CREATE TABLE <tableName>
(
Col1 DT,
Col2 DT,
Col3 DT,
PRIMARY KEY(col1,col2,col..)
);

Example:
CREATE TABLE product
(
YEAR VARCHAR(4),
BATCH VARCHAR(20),
DESCRIPTION VARCHAR(250) ,
PRIMARY KEY (YEAR, BATCH)
);

pg. 43
YEAR BATCH DESCRIPTIOM
2023 JAN
2023 FEB
2022 JAN
2022 FEB
2022 FEB

pg. 44
b. After table created or Alter

CREATE TABLE laptops


(
BRAND VARCHAR(20),
MODEL VARCHAR(20),
DESCRIPTION VARCHAR(250)
);

Syntax:
ALTER TABLE <TableName>
ADD PRIMARY KEY(Col1, col2,…);

Example:
ALTER TABLE laptops
ADD PRIMARY KEY(BRAND,MODEL);

ALTER TABLE laptop


ADD CONSTRAINT pk_laptops PRIMARY KEY(BRAND, MODEL);

pg. 45
How to drop the primary key?
Syntax:
ALTER TABLE <TableName>
DROP PRIMARY KEY;
Example:
ALTER TABLE std
DROP PRIMARY KEY;

pg. 46
pg. 47
6. FOREIGN KEY

What is the Foreign Key?


What is the use of Foreign key?
How to implement Foreign key?
(Composite Foreign) Home work.
How to drop foreign key?
What is the difference between Primary Key and Foreign Key?

What is the Foreign Key?


1. Attribute can only take the values which are present as value some another attribute.
2. A column value can only accept, which is present in the another column, is called foreign key.
3. Foreign key is the key, act as a primary key in one table and foreign key is another table.
4. The table contain Primary Key column called parent table,
the table contain foreign key called child table.
5. Foreign key can accept null values.
6. Multiple foreign keys are possible on one table.

pg. 48
What is the use of Foreign key?
1. Foreign key establish relationship between tables.
2. Foreign Key constraint in MySQL is used for binding two tables with each other.
3. The foreign key constraints are basically used to enforce referential integrity.

Rules for foreign key


1. Both the referencing and the referenced tables should be in the same datatype. (PK/UK and FK)
2. Both the referencing and the referenced tables should be in the same database.
3. The referenced (PK) table should contain unique value.
4. Primary key value in parent table must match with foreign key table.
5. As foreign reference column should Primary Key or Unique Key.

Basic Rules to use foreign key.


1. Both referencing and referred column should same data type.
2. Both referencing and referred tables should present in same database.
3. The referencing table column should contain unique value.
4. Primary key value in parent table must match with foreign key table column.
5. As referencing column should primary key or unique key column.

How to implement Foreign Key?


There are two ways to impose the Foreign Key on any table
Consider below table is already exists in database.
create table branch (BID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(100));
INSERT INTO branch (NAME) VALUES ('IT');
INSERT INTO branch (NAME) VALUES ('CS');
INSERT INTO branch (NAME) VALUES ('CIVIL');
INSERT INTO branch (NAME) VALUES ('ELECTRICAL');

pg. 49
1. At the time of table creation
2. After table created – Alter table

1. At the time of table creation


Syntax:

CREATE TABLE <TableName>


(
Col1 DT Constraint,
Col2 DT Constraint,
Col2 DT Constraint,
Col2 DT Constraint,
FOREIGN KEY (ColName) REFERENCES <BaseTableName> (PK-UK ColumnName)
);

HomeWork
CREATE TABLE <TableName>
(
Col1 DT Constraint,
Col2 DT Constraint,
Col2 DT Constraint,
Col2 DT Constraint,
CONSTRAINT <FK_Name> FOREIGN KEY (ColName) REFERENCES <BaseTableName> (PK-UK
ColumnName)
);

CREATE TABLE std


(
S_ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(100),
MOBILE VARCHAR(10),
BID INT,
FOREIGN KEY(BID) REFERENCES branch(BID)
);

pg. 50
pg. 51
2. After the table creation – Alter table

CREATE TABLE student1


(
S_ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(100),
MOBILE VARCHAR(10),
BRANCH INT
);

Rules: Already exists table should follow the all rules for Foreign key.
Syntax:
ALTER TABLE <TableName>
ADD FOREIGN KEY(BaseColNAme) REFERENCES < ParentTable >(ColumnName);

ALTER TABLE <tableName>


ADD CONSTRANT<ConstraintName>
FOREIGN KEY(BaseColNAme) REFERENCES<ParentTable>(ColumnName);

pg. 52
Example:
ALTER TABLE student
ADD FOREIGN KEY(BRANCH) REFERENCES branch(BID);

pg. 53
Syntax 2
ALTER TABLE student1
ADD CONSTRAINT FK_std_branch_id
FOREIGN KEY(BRANCH) REFERENCES branch(BID);

Important rules about Foreign key


1. We cannot insert value into foreign key column if that value is not present in the reference
(parent) key column, of the parent table.
2. We cannot update reference (parent) key value of a parent table if that the value has a
corresponding child record in the child table without addressing what to with the child
record.
3. We cannot delete record from reference (parent) table provided that the records reference
key value has a child record in the child table without addressing what to do with child
records.

How to delete or drop Foreign key?

pg. 54
Syntax:
ALTER TABLE <TableName>
DROP FOREIGN KEY <FKConstraintName>;

Suppose we do not know the foreign key constraint name, then how to get the Foreign Key
name.
Execute the below query to get the table structure and all keys names.

SHOW CREATE TABLE <TableName>;

Example:
SHOW CREATE TABLE std;

Drop the foreign key.

ALTER TABLE std


DROP FOREIGN KEY std_ibfk_1 ;

pg. 55
Difference between Foreign key and Primary key.

Sr. No. Primary Key Foreign Key


1 Not accept the duplicate value and Foreign key accepts the duplicate and null
null values values
2 PK is uniquely identify the records Not uniquely identify the records.
FK has duplicate values
3 Primary key has only one on a table We can create multiple foreign keys on a
table.

Compost foreign key.


Before apply foreign key we need existing table.

Syntax:
CREATE TABLE <TableName>
( Col1 DT ..,
Col2 DT ..,
Col3 DT ..,

pg. 56
FOREIGN KEY (colName, colName,..) REFERENCES <ParentTableName>(ColName, ColName,..)
);

Example:
CREATE TABLE Student
( SID INT PRIMARY KEY AUTO_INCREMENT,
SNAME VARCHAR (100) NOT NULL,
BID INT,
BNAME VARCHAR(25),
FOREIGN KEY (BID, BNAME) REFERENCES branch(BID, BNAME)
);

pg. 57
pg. 58
Interview questions
1). What are the type of data integrity?

In relational database, there are three type of integrity


1. Domain Integrity ( data type, check constraints)
2. Entity Integrity (primary key, unique constraints)
3. Referential Integrity (handled by foreign key constraints)

Referential integrity (Foreign Key)


Action on Foreign key

After imposing FK we are facing challenges during the update and delete (Reference) parent records.
So we need to assign the appropriate action on the foreign key.

1. NO ACTION / RESTRICT
2. SET DEFAULT (Not working in MySQL)
3. CASCADE
4. SET NULL

 SET NULL
Delete or update the parent table record set null value at foreign key table.

 CASCADE
Delete or update the parent table record all records should get delete or update from
referenced (child) table

 NO ACTION / RESTRICT
Don’t allow the delete or update action (commands).

 SET DEFAULT (Not working with MySQL)

1. SET NULL
For set null action your column should accept null value.

pg. 59
pg. 60
CREATE TABLE Branches (BranchId INT PRIMARY KEY AUTO_INCREMENT, BranchName
VARCHAR(120) NOT NULL, IFSC VARCHAR(11) NOT NULL, BankId INT DEFAULT 1, FOREIGN
KEY(BankID) REFERENCES BankMaster(BankId) ON DELETE SET NULL ON UPDATE SET NULL);

INSERT INTO Branches (BranchName, IFSC, BankId) VALUES ('Karve Nagar', 'UOBI0000001', 2);
INSERT INTO Branches (BranchName, IFSC, BankId) VALUES ('Shivaji Nagar', 'UOBI0000002', 2);
INSERT INTO Branches (BranchName, IFSC, BankId) VALUES ('Warje Nagar', 'UOBI0000032', 2);
INSERT INTO Branches (BranchName, IFSC, BankId) VALUES ('Shivaji Nagar', 'UOBI0000003', 3);
INSERT INTO Branches (BranchName, IFSC, BankId) VALUES ('WarjeNagar', 'UOBI0000006', 3);

pg. 61
pg. 62
2. ON DELETE CASCADE - ON UPDATE CASCADE

CREATE TABLE branhes (BranchId INT PRIMARY KEY AUTO_INCREMENT, BranchName Varchar(100),
BankId INT, FOREIGN KEY (BankId) REFERENCES bankmaster(BankId) ON DELETE CASCADE ON
UPDATE CASCADE);

INSERT INTO branhes (BranchName, BankId) VALUES ('Karve Nagar', 12);


INSERT INTO branhes (BranchName, BankId) VALUES ('Shivaji Nagar', 12);
INSERT INTO branhes (BranchName, BankId) VALUES ('Warje Nagar', 13);
INSERT INTO branhes (BranchName, BankId) VALUES ('Shivaji Nagar', 14);

pg. 63
INSERT INTO branhes (BranchName, BankId) VALUES ('WarjeNagar', 14);

update bankmaster set bankid=25 where bankid=12;

delete from bankmaster where bankid=25;

pg. 64
pg. 65
3. NO ACTION / RESTRICT
Don’t allow the delete or update action (commands).
This is the default action.
Raised the error message.

CREATE TABLE `emp` (


`E_ID` int NOT NULL AUTO_INCREMENT,
`NAME` varchar(56) NOT NULL,
`MOBILE_NUMBER` varchar(10) NOT NULL,
`D_ID` int NOT NULL,
PRIMARY KEY (`E_ID`),
FOREIGN KEY (`D_ID`) REFERENCES `dept` (`D_ID`)
);
insert into emp (NAME, MOBILE_NUMBER, D_ID) VALUES ('Bhagyashree', '9988776655', 1);
insert into emp (NAME, MOBILE_NUMBER, D_ID) VALUES ('Ashok', '9988776656', 2);
insert into emp (NAME, MOBILE_NUMBER, D_ID) VALUES ('Sachin', '9988776657', 3);
insert into emp (NAME, MOBILE_NUMBER, D_ID) VALUES ('Mandar', '9988776658', 4);
insert into emp (NAME, MOBILE_NUMBER, D_ID) VALUES ('Rama', '9988776659', 5);

pg. 66
Add NO ACTION/RESTRICT action on table

1. NO ACTION - RESTRICT

pg. 67
2. SET NULL

1. NO ACTION - RESTRICT
-> This action is by default action for foreign key.
-> You cannot do the delete or update in parent table which is for related records.

----------------------------------------------------------------------------------------------------

2. SET NULL
-> This action will set the null value in child table, when parent record will update or delete.

How to use the action in foreign key?

1. Suppose we have already parent table exists. which is dept.


Syntax :
CREATE TABLE <TableName>
(
Col1 DT Constraint,
Col2 DT Constraint,
Col3 DT Constraint,
FOREIGN KEY (ColName) REFERENCES <ParentTable>(ColumnName) ON DELETE SET NULL ON
UPDATE SET NULL
);

CREATE TABLE emp


(
EID INT PRIMARY KEY AUTO_INCREMENT,
ENAME VARCHAR(100) NOT NULL,
MOBILE VARCHAR(10) NOT NULL,
DID INT,
FOREIGN KEY(DID) REFERENCES dept(D_ID) ON DELETE SET NULL ON UPDATE SET NULL
);

mysql> select * from dept;


+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 7 | Marketing | NULL | 2023-04-14 15:58:50 |
| 8 | Business Aliance | NULL | 2023-04-14 15:59:00 |
+------+---------------------+-------------------------+---------------------+

mysql> CREATE TABLE emp


-> (

pg. 68
-> EID INT PRIMARY KEY AUTO_INCREMENT,
-> ENAME VARCHAR(100) NOT NULL,
-> MOBILE VARCHAR(10) NOT NULL,
-> DID INT,
-> FOREIGN KEY(DID) REFERENCES dept(D_ID) ON DELETE SET NULL ON UPDATE SET NULL
-> );
Query OK, 0 rows affected (0.05 sec)

mysql> desc emp;


+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| EID | int | NO | PRI | NULL | auto_increment |
| ENAME | varchar(100) | NO | | NULL | |
| MOBILE | varchar(10) | NO | | NULL | |
| DID | int | YES | MUL | NULL | |
+--------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> select * from dept;


+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 7 | Marketing | NULL | 2023-04-14 15:58:50 |
| 8 | Business Aliance | NULL | 2023-04-14 15:59:00 |
+------+---------------------+-------------------------+---------------------+

mysql> select * From emp;


+-----+-------------+------------+------+
| EID | ENAME | MOBILE | DID |
+-----+-------------+------------+------+
| 2 | SACHIN G | 9988776655 | 8 |
| 3 | Pallavi G | 9988776656 | 7 |
| 4 | Bhagyashree | 9988776657 | 6 |
+-----+-------------+------------+------+

mysql> UPDATE dept SET D_ID=17 WHERE D_ID=7;


Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * From emp;


+-----+-------------+------------+------+
| EID | ENAME | MOBILE | DID |
+-----+-------------+------------+------+

pg. 69
| 2 | SACHIN G | 9988776655 | 8 |
| 3 | Pallavi G | 9988776656 | NULL |
| 4 | Bhagyashree | 9988776657 | 6 |
+-----+-------------+------------+------+
3 rows in set (0.00 sec)

mysql> select * from dept;


+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 8 | Business Aliance | NULL | 2023-04-14 15:59:00 |
| 17 | Marketing | NULL | 2023-04-14 15:58:50 |
+------+---------------------+-------------------------+---------------------+

mysql> select * from emp;


+-----+-------------+------------+------+
| EID | ENAME | MOBILE | DID |
+-----+-------------+------------+------+
| 2 | SACHIN G | 9988776655 | 8 |
| 3 | Pallavi G | 9988776656 | NULL |
| 4 | Bhagyashree | 9988776657 | 6 |
+-----+-------------+------------+------+
3 rows in set (0.00 sec)

mysql> select * from dept;


+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 8 | Business Aliance | NULL | 2023-04-14 15:59:00 |
| 17 | Marketing | NULL | 2023-04-14 15:58:50 |
+------+---------------------+-------------------------+---------------------+
8 rows in set (0.00 sec)

mysql> DELETE FROM dept WHERE D_ID=8;


Query OK, 1 row affected (0.01 sec)

pg. 70
mysql> select * from dept;
+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 17 | Marketing | NULL | 2023-04-14 15:58:50 |
+------+---------------------+-------------------------+---------------------+
7 rows in set (0.00 sec)

mysql> select * from emp;


+-----+-------------+------------+------+
| EID | ENAME | MOBILE | DID |
+-----+-------------+------------+------+
| 2 | SACHIN G | 9988776655 | NULL |
| 3 | Pallavi G | 9988776656 | NULL |
| 4 | Bhagyashree | 9988776657 | 6 |
+-----+-------------+------------+------+
3 rows in set (0.00 sec)

------------------------------------------------------------------------------------
1. NO ACTION - RESTRICT
-> This action is by default action for foregin key.
-> You can not do the delete or update in parent table which is for related records.

Syntax:
CREAET TABLE <TableName>
(
Col1 DT constraint,
Col2 DT constraint,
Col3 DT constraint,
FOREIGN KEY (ConName) REFERENCES <ParentTable>(ColName)
);

Used defined:
CREAET TABLE <TableName>
(
Col1 DT constraint,
Col2 DT constraint,
Col3 DT constraint,
FOREIGN KEY (ConName) REFERENCES <ParentTable>(ColName) ON DELETE NO ACTION ON
UPDATE NO ACTION
);

CREAET TABLE <TableName>

pg. 71
(
Col1 DT constraint,
Col2 DT constraint,
Col3 DT constraint,
FOREIGN KEY (ConName) REFERENCES <ParentTable>(ColName) ON DELETE RESTRICT ON UPDATE
RESTRICT
);

Examples:

CREATE TABLE Managers


(
MID INT PRIMARY KEY AUTO_INCREMENT,
MNAME VARCHAR(100) NOT NULL,
MMOBILE VARCHAR(10) NOT NULL,
MDID INT,
FOREIGN KEY (MDID) REFERENCES dept(D_ID)
);

mysql> CREATE TABLE Managers


-> (
-> MID INT PRIMARY KEY AUTO_INCREMENT,
-> MNAME VARCHAR(100) NOT NULL,
-> MMOBILE VARCHAR(10) NOT NULL,
-> MDID INT,
-> FOREIGN KEY (MDID) REFERENCES dept(D_ID)
-> );
Query OK, 0 rows affected (0.02 sec)

mysql> desc managers;


+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| MID | int | NO | PRI | NULL | auto_increment |
| MNAME | varchar(100) | NO | | NULL | |
| MMOBILE | varchar(10) | NO | | NULL | |
| MDID | int | YES | MUL | NULL | |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> select * from managers;


+-----+-------+------------+------+
| MID | MNAME | MMOBILE | MDID |
+-----+-------+------------+------+
| 1 | ABC | 9988776655 | 6 |
| 2 | DEF | 9988776656 | 17 |
| 3 | GHI | 9988776657 | 17 |
| 4 | OPQ | 9988776657 | 6 |
+-----+-------+------------+------+
4 rows in set (0.00 sec)

pg. 72
mysql> select * from dept;
+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 17 | Marketing | NULL | 2023-04-14 15:58:50 |
+------+---------------------+-------------------------+---------------------+
7 rows in set (0.00 sec)

mysql> delete from dept where d_id=17;


ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`gth`.`managers`, CONSTRAINT `managers_ibfk_1` FOREIGN KEY (`MDID`) REFERENCES `dept`
(`D_ID`))

mysql> update dept set d_id=27 where d_id=17;


ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`gth`.`managers`, CONSTRAINT `managers_ibfk_1` FOREIGN KEY (`MDID`) REFERENCES `dept`
(`D_ID`))

Examples user defined NO ACTION :

CREATE TABLE people


(
PID INT PRIMARY KEY AUTO_INCREMENT,
PNAME VARCHAR(100) NOT NULL,
PMOBILE VARCHAR(10) NOT NULL,
PDID INT,
FOREIGN KEY (PDID) REFERENCES dept(D_ID) ON DELETE NO ACTION ON UPDATE RESTRICT
);

mysql> CREATE TABLE people


-> (
-> PID INT PRIMARY KEY AUTO_INCREMENT,
-> PNAME VARCHAR(100) NOT NULL,
-> PMOBILE VARCHAR(10) NOT NULL,
-> PDID INT,
-> FOREIGN KEY (PDID) REFERENCES dept(D_ID) ON DELETE NO ACTION ON UPDATE RESTRICT
-> );
Query OK, 0 rows affected (0.02 sec)

mysql> desc people;

pg. 73
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| PID | int | NO | PRI | NULL | auto_increment |
| PNAME | varchar(100) | NO | | NULL | |
| PMOBILE | varchar(10) | NO | | NULL | |
| PDID | int | YES | MUL | NULL | |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> select * from dept;


+------+---------------------+-------------------------+---------------------+
| D_ID | NAME | DESCRIPTION | CREATED_ON |
+------+---------------------+-------------------------+---------------------+
| 1 | Administrator | Admin department | 2023-04-12 19:18:05 |
| 2 | HR | Human Resource | 2023-04-12 19:20:05 |
| 3 | Training | Training teachers | 2023-04-12 19:20:05 |
| 4 | IT | Information Technologiy | 2023-04-12 19:20:05 |
| 5 | TEST | NULL | 2023-04-11 00:00:00 |
| 6 | Account and Finance | NULL | 2023-04-14 15:58:38 |
| 17 | Marketing | NULL | 2023-04-14 15:58:50 |
+------+---------------------+-------------------------+---------------------+
7 rows in set (0.00 sec)

INSERT INTO people (PNAME, PMOBILE, PDID) VALUES ('ABC', '9988776655', 6);
INSERT INTO people (PNAME, PMOBILE, PDID) VALUES ('DEF', '9988776656', 17);
INSERT INTO people (PNAME, PMOBILE, PDID) VALUES ('GHI', '9988776657', 17);
INSERT INTO people (PNAME, PMOBILE, PDID) VALUES ('OPQ', '9988776657', 6);

mysql> select * from people;


+-----+-------+------------+------+
| PID | PNAME | PMOBILE | PDID |
+-----+-------+------------+------+
| 1 | ABC | 9988776655 | 6 |
| 2 | DEF | 9988776656 | 17 |
| 3 | GHI | 9988776657 | 17 |
| 4 | OPQ | 9988776657 | 6 |
+-----+-------+------------+------+
4 rows in set (0.00 sec)

mysql> DELETE FROM dept WHERE D_ID=17;


ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`gth`.`managers`, CONSTRAINT `managers_ibfk_1` FOREIGN KEY (`MDID`) REFERENCES `dept`
(`D_ID`))

mysql> UPDATE dept SET D_ID=29 WHERE D_ID=17;


ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails
(`gth`.`managers`, CONSTRAINT `managers_ibfk_1` FOREIGN KEY (`MDID`) REFERENCES `dept`
(`D_ID`))

pg. 74
--------------------------END REFERENTIAL INTIGRITY------------------------------------------------
mysql> CREATE TABLE pallaviDoubt (ID INT PRIMARY KEY AUTO_INCREMENT, J_YEAR YEAR, J_TIME
TIME, J_DATE DATE, J_DT DATETIME, NAME VARCHAR(100))
-> ;
Query OK, 0 rows affected (0.02 sec)

mysql> desc pallavidoubt;


+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| ID | int | NO | PRI | NULL | auto_increment |
| J_YEAR | year | YES | | NULL | |
| J_TIME | time | YES | | NULL | |
| J_DATE | date | YES | | NULL | |
| J_DT | datetime | YES | | NULL | |
| NAME | varchar(100) | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql> ALTER TABLE pallavidoubt add J_TT TIMESTAMP;


Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> desc pallavidoubt;


+--------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------+------+-----+---------+----------------+
| ID | int | NO | PRI | NULL | auto_increment |
| J_YEAR | year | YES | | NULL | |
| J_TIME | time | YES | | NULL | |
| J_DATE | date | YES | | NULL | |
| J_DT | datetime | YES | | NULL | |
| NAME | varchar(100) | YES | | NULL | |
| J_TT | timestamp | YES | | NULL | |
+--------+--------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

mysql> insert into pallavidoubt (J_YEAR, J_TIME, J_DATE, J_DT, J_TT) VALUES ('2023', '11:10:30',
'2023-05-10', '2023-05-10 13:23:45', '2023-05-10 23:34:45');
Query OK, 1 row affected (0.00 sec)

mysql> select * from pallavidoubt;


+----+--------+----------+------------+---------------------+------+---------------------+
| ID | J_YEAR | J_TIME | J_DATE | J_DT | NAME | J_TT |
+----+--------+----------+------------+---------------------+------+---------------------+
| 1 | 2023 | 11:10:30 | 2023-05-10 | 2023-05-10 13:23:45 | NULL | 2023-05-10 23:34:45 |
+----+--------+----------+------------+---------------------+------+---------------------+
1 row in set (0.00 sec)

11/05/2023 New Topic

pg. 75
Joins in SQL.
What is the join.
1. Joins are used with select statement.
2. A SQL join statement combines the data row from two or more tables based on common
fields between them.
3. The joins in MySQL basically used to fetch the rows from two or more related tables.
(Related tables means relation between table PK and FK or common fields between tables)

Where are useful the joining?


Why should we join?
1. SQL join are mostly used when a user tried to get data from multiple tables at one time (In a
single query).
2. To generate the reports.
3. To show the consolidated information.
4. To get the readable information.

Syntax:
SELECT col,col,col FROM <table>,<Table>,<Tabl>;
SELECT col,col,col FROM <table> JOIN <Table> JOIN<Tabl>;

Example:
SELECT * FROM cities, states;
SELECT * FROM states JOIN countries;

Types of Join
 Inner Join
a. Equi join
b. Non-Equi join
 Outer Join
a. Left outer join / Left join
b. Right outer join / Right join
 Cross Join / Cartesian product
 Self-Join

Table: Departments
DID Name Information
1 Admin Administration
2 HR Human Resource
3 IT Information
Technology

Table: People
PID Name Gender Mobile DID
1 Ashok Male 9988776655 1
2 Sachin Male 9988776656 2
3 Pallavi FEMALE 9988776666 3

Suppose we executed the JOIN on above tables.

pg. 76
JOIN keyword merger two or more tables temporarily, and then show the records based on the
condition. After showing the data dumped the temporary created table.

DID Name Information PID NAME GENDER DID


1 Admin Administration 1 Ashok Male 9988776655
2 HR Human Resource 2 Sachin Male 9988776656
3 IT Information 3 Pallavi FEMALE 9988776666
Technology

There are different types of Joins.


 Inner Join - Return the common rows between tables.
 Outer Join – Return the matching and non-matching rows from the table.
 Cross Join / Cartesian product – Join without the condition
 Self-Join – Apply the join on same table

1. Inner join
1. This join used the INNER JOIN keyword in query.
2. The inner join in MySQL is used to return only the matching records from all tables involved
in join operation.
3. Inner join is default join in MySQL.
4. Inner join can be used with various SQL clauses/conditions. Like, Group By, Order by, and
various operators.

Syntax:
SELECT col, col2,col3……
FROM <TableName>
INNER JOIN <TableName> ON <Condition>
INNER JOIN <TableName> ON <Condition>;

Example:
SELECT e.NAME, MOBILE_NUMBER, EMAIL_ID, d.NAME AS DEPARTMENT
FROM employees e

pg. 77
INNER JOIN departments d ON d.D_ID=e.D_ID;

SELECT e.ID, e.name, p.projectid, p.title from projects p


inner join employee e ON e.id=p.employeeid;

SELECT e.SALARY, e.NAME, MOBILE_NUMBER, EMAIL_ID, d.NAME AS DEPARTMENT


FROM employees e
INNER JOIN departments d ON d.D_ID=e.D_ID
WHERE salary < 15000;

SELECT e.SALARY, e.NAME, MOBILE_NUMBER, EMAIL_ID, d.NAME AS DEPARTMENT


FROM employees e
INNER JOIN departments d ON d.D_ID=e.D_ID
WHERE d.d_id = 1;

1. Write a query to show the date those employees who has department. ()Show the dept name
SELECT E_ID, employees.NAME, SALARY, EMAIL_ID, MOBILE_NUMBER, departments.NAME, MANAGER
FROM Employees INNER JOIN departments USING(D_ID);

PS: Write a query to display the state, country name and country code from the tables.

SELECT s.NAME AS STTE_NAME, c.NAME AS COUNTRY_NAME, c.COUNTRYCODE FROM states s


INNER JOIN countries c ON c.id=s.country_id;

PS: Write the query to show the data as below from the tables;

CityID CityName StateName CountryName CountryCode

pg. 78
SELECT c.city, s.name as state, cc.name as country, cc.countrycode
FROM cities c
INNER JOIN states s ON s.id=c.state_id
INNER JOIN countries cc ON cc.id=s.country_id;

SELECT c.city, s.name as state, cc.name as country, cc.countrycode


FROM cities c
INNER JOIN states s ON s.id=c.state_id
INNER JOIN countries cc ON cc.id=s.country_id
WHERE s.NAME='MAHARASHTRA';

pg. 79
2. Write a query to display the cities count state wise.
Maharashtra 35,
Himachal Pradesh 30

SELECT s.NAME AS STATE, count(*) NO_OF_CITIES


FROM states s
INNER JOIN cities c ON c.state_id=s.id
GROUP BY s.NAME;

3. Write a query to display the states who having more than 30 cities. (less than 50 cities.)
SELECT s.NAME AS STATE, count(*) NO_OF_CITIES
FROM states s
INNER JOIN cities c ON c.state_id=s.id
GROUP BY s.NAME
HAVING COUNT(*) > 30;

pg. 80
Consider below database and write the below queries.

CREATE TABLE `customer` (


`Mobile` varchar(10) NOT NULL,
`NAME` varchar(100) NOT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`Mobile`)
);

CREATE TABLE Addresses


(
AddressId INT PRIMARY KEY AUTO_INCREMENT,
Mobile VARCHAR(10),
Address VARCHAR(250) NOT NULL,
PIN VARCHAR(6) NOT NULL,
FOREIGN KEY(Mobile) REFERENCES customer(Mobile)
);

CREATE TABLE `orders` (


`OID` int NOT NULL AUTO_INCREMENT,
`OrderedBy` varchar(10) DEFAULT NULL,
`OrderDate` date NOT NULL,
`TotalAmount` decimal(10,2) DEFAULT NULL,
`DeleveryStatus` varchar(30) DEFAULT 'Preparing',
`AddressId` INT,
PRIMARY KEY (`OID`),
KEY `OrderedBy` (`OrderedBy`),
FOREIGN KEY (`OrderedBy`) REFERENCES `customer` (`Mobile`),
FOREIGN KEY (`AddressId`) REFERENCES `Addresses` (`AddressId`)
);

CREATE TABLE OrderItemDetails


(
OID_ID INT PRIMARY KEY AUTO_INCREMENT,
ItemName Varchar(120) NOT NULL,

pg. 81
ItemPrice decimal(10,2) NOT NULL ,
ItemQuentity int NOT NULL DEFAULT 1,
OrderId INT,
FOREIGN KEY(OrderId) REFERENCES orders(OID)
);

insert into customer values ('9988776655','Sachin','[email protected]');


insert into customer values ('9988776656','Namdev S','[email protected]');
insert into customer values ('9988776657','Bhagyashree S','[email protected]');
insert into customer values ('9988776658','Pallavi B','[email protected]');
insert into customer values ('9988776659','Sachin u','[email protected]');
insert into customer values ('9988776660','Mandar','[email protected]');
insert into customer values ('9988776661','rama','[email protected]');
insert into customer values ('9988776662','Mahesh','[email protected]');
insert into customer values ('9988776663','Shyam','[email protected]');
insert into customer values ('9988776664','ganesh','[email protected]');
insert into customer values ('9988776665','pankaj','[email protected]');
insert into customer values ('9988776666','mangesh','[email protected]');
insert into customer values ('9988776667','Sangeeta','[email protected]');

insert into addresses (Mobile,Address,PIN) VALUES ('9021488209','Warje, Pune', 412208);


insert into addresses (Mobile,Address,PIN) VALUES ('9988776656','Karve nagar, Pune', 412200);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776656','Kothrud, Pune', 412201);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776657','Kothrud, Pune', 412201);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776657','Shivaji Nagar, Pune', 411101);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776658','Karve Nagar, Pune', 412200);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776659','Warje, Pune', 412208);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776660','Nagar', 412505);
insert into addresses (Mobile,Address,PIN) VALUES ('9988776661','Shirur, Nagar', 412345);

INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9021488209','2023-


05-10','2000', 1);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9021488209','2023-
05-11','2000', 2);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776656','2023-
05-09','5000', 3);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776656','2023-
05-13','12000', 4);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776659','2023-
05-10','2000', 7);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776659','2023-
05-11','4000', 7);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776659','2023-
05-12','700', 7);
INSERT INTO orders (OrderedBy, OrderDate, TotalAmount, AddressId) VALUES ('9988776661','2023-
05-12','2300', 9);

INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES


('Parle',100,20,1);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES ('Good
Day',150,10,2);

pg. 82
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('parle',50,10,2);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('Suger',30,10,3);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('Almond',500,7,3);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('Dates',400,3,3);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('Icecream',1000,12,4);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('Parle',100,20,5);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES
('GoogDay',150,20,6);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES ('Tenis
ball',100,7,7);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES ('Let us c -
Books',350,6,8);
INSERT INTO OrderItemDetails (ItemName, ItemPrice, ItemQuentity, OrderId) VALUES ('Exp C-
Books',200,1,8);

pg. 83
1. Write a query to show customers and its address list.
SELECT c.MOBILE, c.NAME, c.EMAIL, a.ADDRESS, a.PIN FROM customer c INNER JOIN addresses
a ON a.Mobile=c.Mobile;

2. Write a query to get below customer details. (Customer order details)


Name, Mobile, OrderId, Address, Amount, DeleveryStatus, OrderDate.
(Note: To show above output we need to join with multiple tables such as customers, orders and
addresses)

pg. 84
SELECT c.Name, C.Mobile, o.OID, o.OrderDate, o.TotalAmount, o.DeleveryStatus, a.Address
FROM customer c
INNER JOIN orders o ON o.OrderedBy=c.Mobile
INNER JOIN addresses a ON a. AddressId=o. AddressId;

3. Write a query to display orders and its items details.


SELECT o.OID, o.OrderedBy , oid.OID_ID, oid.ItemName, oid.ItemPrice, oid.ItemQuentity
FROM orders o
INNER JOIN orderitemdetails oid ON oid.OrderId=o.OID;

4. Write a query to display orders lists, those order item count is more than 2.

SELECT o.OID, COUNT(*)


FROM orders o
INNER JOIN orderitemdetails oid ON oid.OrderId=o.OID
GROUP BY o.OID
HAVING count(*) > 2;

pg. 85
Equi Join and Non-Equi Joins in MySQL

1. Equi join and Non-equi joins in SQL are types of INNER JOIN.
2. Equi JOINS in SQL is used to retrieve the data from multiple table using equality (=)
conditions with the WHERE clause.
3. Non-Equi JOINS is used to retrieve the data from multiple table using any other operator
except the equality (=) condition.
4. You can use Non-equi join to check duplicate record or to get data in range.

Examples:
Equi join
SELECT c.id , c.city, s.name StateName FROM cities c
INNER JOIN states s ON s.id=c.state_id
WHERE s.id=10;

SELECT d.NAME AS DEPARTMENT, d.D_ID, e.NAME AS EMP_NAME, e.SALARY,


e.DATE_OF_JOINING FROM employees e
INNER JOIN departments d ON d.D_ID=e.D_ID
WHERE d.D_ID=3;

Non-equi join
SELECT c.id , c.city, s.name StateName FROM cities c
INNER JOIN states s ON s.id=c.state_id
WHERE s.id<>10;

SELECT c.id , c.city, s.name StateName FROM cities c


INNER JOIN states s ON s.id=c.state_id
WHERE s.id<2;

SELECT d.NAME AS DEPARTMENT, d.D_ID, e.NAME AS EMP_NAME, e.SALARY,


e.DATE_OF_JOINING FROM employees e
INNER JOIN departments d ON d.D_ID=e.D_ID
WHERE d.D_ID > 3;

pg. 86
Practice Examples

mysql> create database cbd;


use cbd;
mysql> CREATE TABLE company (C_ID INT PRIMARY KEY AUTO_INCREMENT, C_NAME
VARCHAR(100) NOT NULL);

CREATE TABLE employee


(
E_ID INT PRIMARY KEY AUTO_INCREMENT,
E_NAME VARCHAR(100) NOT NULL,
E_EMAIL VARCHAR(100) NOT NULL UNIQUE,
E_CONTACT VARCHAR(10) NOT NULL UNIQUE,
E_DESIGNATION VARCHAR(25) NOT NULL,
E_SALARY INT NOT NULL CHECK(E_SALARY > 5000)
);

CREATE TABLE csjoin


(
C_ID INT ,
E_ID INT ,
FOREIGN KEY(C_ID) REFERENCES company(C_ID),
FOREIGN KEY(E_ID) REFERENCES employee(E_ID)
);

INSERT INTO company (C_NAME) VALUES ('Tata Consultancy Serveces');


INSERT INTO company (C_NAME) VALUES ('Infosys');
INSERT INTO company (C_NAME) VALUES ('Congnizant');
INSERT INTO company (C_NAME) VALUES ('Persistant System');
INSERT INTO company (C_NAME) VALUES ('L and T');

INSERT INTO company (C_NAME) VALUES ('WIPRO');


INSERT INTO company (C_NAME) VALUES ('GOOGLE');
INSERT INTO company (C_NAME) VALUES ('Cap Geminai');
INSERT INTO company (C_NAME) VALUES ('Amezon');

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Mandar', '[email protected]', '9922886677', 'EVELOPER', 25000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Sunil', '[email protected]', '9922886678', 'Business Analyst', 21000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Anil', '[email protected]', '9922886688', 'Product Manager', 14000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Sachin U', '[email protected]', '9922886611', 'QA', 29000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Sachin G', '[email protected]', '9922881111', 'Developer', 31000);

pg. 87
INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)
VALUES ('pallavi', '[email protected]', '9922881511', 'Developer', 31000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Bhagyashree', '[email protected]', '9922886633', 'Product Manager', 14000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Ganesh', '[email protected]', '9944886633', 'Product Manager', 14000);

INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)


VALUES ('Namdev', '[email protected]', '9944886533', 'Product Manager', 35000);

INSERT INTO csjoin (C_ID, E_ID) VALUES (1, 7);


INSERT INTO csjoin (C_ID, E_ID) VALUES (2, 6);
INSERT INTO csjoin (C_ID, E_ID) VALUES (3, 5);
INSERT INTO csjoin (C_ID, E_ID) VALUES (4, 4);
INSERT INTO csjoin (C_ID, E_ID) VALUES (5, 3);
INSERT INTO csjoin (C_ID, E_ID) VALUES (6, 2);
INSERT INTO csjoin (C_ID, E_ID) VALUES (1, 1);
INSERT INTO csjoin (C_ID, E_ID) VALUES (2, 1);

You’re Task:
1. Write A Query to show the employee whose name start with g and ends with sh
2. Write A SQL Query to show the count of employee who is taking same salary
3. Write A SQL Query to show the employee list whose salary is 10000, 20000 and 30000
4. Write A SQL Query to show the second highest salary of employee
5. Write A SQL Query to show the company wise employee list.
6. Write A SQL Query to show the employee name who is working in more than one company
7. Write A SQL Query to show the company names who having no employee
8. Write A SQL Query to show the employee whose designation is DEV and name start with p

1. Write A Query to show the employee whose name start with g and ends with sh
mysql> SELECT * FROM employee WHERE E_NAME LIKE 'g%sh';
+------+--------+------------------+------------+-----------------+----------+
| E_ID | E_NAME | E_EMAIL | E_CONTACT | E_DESIGNATION | E_SALARY |
+------+--------+------------------+------------+-----------------+----------+
| 7 | Ganesh | [email protected] | 9944886633 | Product Manager | 14000 |
+------+--------+------------------+------------+-----------------+----------+

mysql> SELECT * FROM employee WHERE E_NAME LIKE 'b%e';


+------+-------------+------------------+------------+-----------------+----------+
| E_ID | E_NAME | E_EMAIL | E_CONTACT | E_DESIGNATION | E_SALARY |
+------+-------------+------------------+------------+-----------------+----------+
| 6 | Bhagyashree | [email protected] | 9922886633 | Product Manager | 14000 |
+------+-------------+------------------+------------+-----------------+----------+

2. Write A SQL Query to show the count of employee who is taking same salary;
mysql> SELECT E_SALARY, COUNT(*) FROM employee GROUP BY E_SALARY ;
+----------+----------+
| E_SALARY | COUNT(*) |

pg. 88
+----------+----------+
| 25000 | 1|
| 21000 | 1|
| 14000 | 3|
| 29000 | 1|
| 31000 | 2|
+----------+----------+
5 rows in set (0.00 sec)

3. Write A SQL Query to show the employee list whose salary is 10000, 20000 and 30000
SELECT * FROM employee WHERE E_SALARY IN (14000, 21000, 31000);

mysql> SELECT * FROM employee WHERE E_SALARY IN (14000, 21000, 31000);


+------+-------------+-------------------+------------+------------------+----------+
| E_ID | E_NAME | E_EMAIL | E_CONTACT | E_DESIGNATION | E_SALARY |
+------+-------------+-------------------+------------+------------------+----------+
| 2 | Sunil | [email protected] | 9922886678 | Business Analyst | 21000 |
| 3 | Anil | [email protected] | 9922886688 | Product Manager | 14000 |
| 5 | Sachin G | [email protected] | 9922881111 | Developer | 31000 |
| 6 | Bhagyashree | [email protected] | 9922886633 | Product Manager | 14000 |
| 7 | Ganesh | [email protected] | 9944886633 | Product Manager | 14000 |
| 8 | pallavi | [email protected] | 9922881511 | Developer | 31000 |
+------+-------------+-------------------+------------+------------------+----------+
6 rows in set (0.00 sec)

4. Write A SQL Query to show the second highest salary of employee


SELECT E_ID, E_NAME, E_SALARY
FROM
(SELECT E_ID, E_NAME, E_SALARY FROM employee ORDER BY E_SALARY DESC LIMIT
2) e
ORDER BY E_SALARY LIMIT 1;

When miltiple records are same (Mupltiple employee salary are same)

SELECT E_SALARY FROM


(SELECT E_SALARY, COUNT(*) FROM employee group by E_SALARY ORDER BY E_SALARY DESC
LIMIT 2) e
ORDER BY E_SALARY LIMIT 1;

5. Write A SQL Query to show the company wise employee list.


mysql> SELECT c.C_ID, c.C_NAME, e.E_ID, e.E_NAME FROM csjoin cs
INNER JOIN company c ON c.C_ID = cs.C_ID
INNER JOIN employee e ON e.E_ID = cs.E_ID;
+------+---------------------------+------+-------------+
| C_ID | C_NAME | E_ID | E_NAME |
+------+---------------------------+------+-------------+
| 1 | Tata Consultancy Serveces | 7 | Ganesh |
| 1 | Tata Consultancy Serveces | 1 | Mandar |
| 2 | Bajaj Finserv | 6 | Bhagyashree |
| 3 | Infosys | 5 | Sachin G |

pg. 89
| 4 | Congnizant | 4 | Sachin U |
| 5 | Persistant System | 3 | Anil |
| 6 | L and T | 2 | Sunil |
+------+---------------------------+------+-------------+

6. Write A SQL Query to show the employee name who is working in more than one company
SELECT e.E_NAME, COUNT(*) FROM csjoin cs
INNER JOIN employee e ON e.E_ID=cs.E_ID
GROUP BY e.E_NAME
HAVING COUNT(*) > 1;

mysql> SELECT e.E_NAME, COUNT(*) FROM csjoin cs


INNER JOIN employee e ON e.E_ID=cs.E_ID
GROUP BY e.E_NAME
HAVING COUNT(*) > 1;
+--------+----------+
| E_NAME | COUNT(*) |
+--------+----------+
| Mandar | 2|
+--------+----------+

7. Write A SQL Query to show the company names who having no employee

SELECT c.C_NAME, COUNT(*)


FROM csjoin cs
LEFT JOIN company c ON c.C_ID=cs.C_ID
GROUP BY c.C_NAME;

SELECT c.C_NAME, e.E_NAME


FROM csjoin cs
RIGHT JOIN employee e ON e.E_ID = cs.E_ID
RIGHT JOIN company c ON c.C_ID=cs.C_ID
WHERE e.E_NAME IS NULL;

7. Write A SQL Query to show the employee whose designation is DEV and name start with p

pg. 90
2. OUTER JOIN

MySQL outer join gives the both matched and unmatched records of data depending on the type of
outer join.

Types of outer join


1. LEFT OUTER JOIN / LEFT JOIN
2. RIGHT OUTER JOIN / RIGHT JOIN

1.LEFT OUTER JOIN-LEFT JOIN


The Left outer join keyword returns all records from the left table (table1) and the matching records
from right table (table2).

 The Left outer join in MYSQL is used to retrieve all the matching records from both tables as
well as non-matching records from the left side (first) table
 LEFT OUTER JOIN = LEFT JOIN

Syntax:
SELECT col1, col2, col3, …..
FROM table1
LEFT JOIN table2 ON condition;

Example:
SELECT e.NAME AS EMP_NAME, e.E_ID, e.SALARY, d.NAME AS DEPARTMENT
FROM employees e
LEFT JOIN departments d ON d.D_ID=e.D_ID;

pg. 91
When do we use LEFT JOIN?
 If you want to retrieve all the matchings row from the tables involved in the join as well as all the non-
matching rows from the left side table in the result set, then you need to use LEFT JOIN.

Practice queries:
1. Write a query to display the all employees with department name, who have department or not.

SELECT e.NAME AS EMP_NAME, e.E_ID, e.SALARY, d.NAME AS DEPARTMENT


FROM employees e
LEFT JOIN departments d ON d.D_ID=e.D_ID;

2. Write a query to show the all customers data as well as customer address.
Note: who has address or not, all customer should display.

SELECT c.MOBILE, c.NAME, c.EMAIL, a.ADDRESS, a.PIN


FROM customer c
LEFT JOIN addresses a ON a.Mobile=c.Mobile;

SELECT c.MOBILE, c.NAME, c.EMAIL, a.ADDRESS, a.PIN


FROM customer c
LEFT JOIN addresses a ON a.Mobile=c.Mobile
WHERE c.MOBILE='9988776663';

SELECT c.MOBILE, c.NAME, c.EMAIL, a.ADDRESS, a.PIN


FROM customer c
LEFT JOIN addresses a ON a.Mobile=c.Mobile
WHERE a.PIN='412201';

3. Write a query to show the company and employee list, display all company names who has employee or not.

SELECT c.C_ID, c.C_NAME, e.E_NAME, e.E_EMAIL, e.E_SALARY


FROM company c
LEFT JOIN csjoin cs ON cs.C_ID=c.C_ID
LEFT JOIN employee e ON e.E_ID=cs.E_ID;

2.RIGHT OUTER JOIN

Crate below table as CityMaster

Sr. No. Column Name DataType Other details

1 PIN_CODE INT NOT NULL, PRIMARY KEY (Number should be 6 digits


only)

2 AREA VARCHAR(56) NOT NULL

3 CITY_NAME VARCHAR(56) NOT NULL

CREATE TABLE CityMaster


(
PIN_CODE INT PRIMARY KEY CHECK(PIN_CODE > 100000 AND PIN_CODE<999999) ,
AREA VARCHAR(56) NOT NULL,
CITY_NAME VARCHAR(56) NOT NULL
);

Write a query to insert 10 pin code above the table


INSERT INTO CityMaster VALUES (411019,'CHINCHWAD EAST','Pune');
INSERT INTO CityMaster VALUES (411015,'DHANORI','Pune');
INSERT INTO CityMaster VALUES (411026,'INDRAYANINAGAR','Pune');

pg. 92
INSERT INTO CityMaster VALUES (411019,'MPHULENAGAR','Pune');
INSERT INTO CityMaster VALUES (411018,'PIMPRI P F','Pune');
INSERT INTO CityMaster VALUES (411033,'PUNAWALE','Pune');
INSERT INTO CityMaster VALUES (411022,'SRPF','Pune');
INSERT INTO CityMaster VALUES (411037,'TV NAGAR','Pune');
INSERT INTO CityMaster VALUES (411014,'VADGAON SHERI','Pune');
INSERT INTO CityMaster VALUES (411006,'YERWADA','Pune');
INSERT INTO CityMaster VALUES (411003,'AMMUNITION FACTORY KHADKI','Pune');

Write the DDL command to create the below table as Addresses

Sr. No. Column Name DataType Other details

1 A_ID INT NOT NULL, PRIMARY KEY, AUTO INCREMENT

2 E_ID INT NOT NULL, FOREIGN KEY

3 ADDRESS VARCHAR(256) NOT NULL

4 PIN_CODE INT NOT NULL, FOREIGN KEY

CREATE TABLE Addresses


(
A_ID INT PRIMARY KEY AUTO_INCREMENT,
E_ID INT NOT NULL,
ADDRESS VARCHAR(250) NOT NULL,
PIN_CODE INT,
FOREIGN KEY (E_ID) REFERENCES employees(E_ID),
FOREIGN KEY (PIN_CODE) REFERENCES CityMaster(PIN_CODE)
);

Write a DML statement to Insert 10 employee addresses in the Addresses table


INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (12, 'Near GTH office', 411058);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (13, 'Katraj tunnel', 411046);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (14, 'Talwade', 411062);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (15, 'Ubale nagar lohegaon', 411047);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (16, 'Near PCCOE college', 411035);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (17, 'Dhanori first village', 411015);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (18, 'Chinchwad east railway station',
411019);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (19, 'Yerwada, near bund gardan bridge',
411006);
INSERT INTO Addresses (E_ID, ADDRESS, PIN_CODE) VALUES (20, 'Wadgaon Sheri', 411014);

What is the Right join or Right outer join?


Right outer join in MySQL is used to retrieve all matching records from both tables as well as all non-matching records from
right table.

Non-matching cases it will take null values.

RIGHT OUTER JOIN and RIGHT JOIN both are same

pg. 93
Syntax:
SELECT col1, col2, col3, ……
FROM table1
RIGHT OUTER JOIN table2 ON <condition>;

SELECT col1, col2, col3, …..


FROM table1
RIGHT JOIN table2 ON <Condition>;

Examples:
1. Write the query to show employees, employee has assigned departments or not.

SELECT E_ID, e.NAME, BLOOD_GROUP, EMAIL_ID, MOBILE_NUMBER, GENDER, MANAGER, d.D_ID,


d.NAME AS DEPARTMENT
FROM departments d
RIGHT JOIN employees e ON e.D_ID = d.D_ID;

2.Write a query to display the employee and its address.

SELECT e.E_ID, e.NAME, e.GENDER, a.PIN_CODE, a.ADDRESS


FROM addresses a
RIGHT JOIN employees e ON e.E_ID = a.E_ID ;

3.Write the query to show all female employee with address, who does not have address it should display.

SELECT e.E_ID, e.NAME, e.GENDER, a.PIN_CODE, a.ADDRESS


FROM addresses a
RIGHT JOIN employees e ON e.E_ID = a.E_ID
WHERE e.GENDER='FEMALE';

4.Write a query to display the projects and associated employee.


SELECT p.projectid, p.projectname, e.employeeid, e.fullname, e.technology
FROM employee e
RIGHT JOIN projects p ON p.employeeid=e.employeeid;

pg. 94
Self-Join
 Self-Join in MySQL is a nothing but joining the table by itself.
 We need to self-join in MySQL when we have some relation between the columns of same table.
 During implementation of self-join we need to use the table alias.
 Table alias is temporary name for table.

Syntax:
SELECT col1. Col2, col3….
FROM table1 alias, table1 alias
WHERE CONDITION;

SELECT col1, col2,col3,…


FROM table alias
JOIN table alias ON condition;

Examples:

Q.1 Write a query to display the employee information with it’s a manager.
SELECT e.E_ID, e.NAME, e.MOBILE_NUMBER, ee.NAME AS MANAGER
FROM employees e
LEFT JOIN employees ee ON ee.E_ID = e.MANAGER ;

Q. Refer the below table and find out those students who choose multiple courses

S_ID C_ID S_NAME SINCE


1001 1 PALLAVI 2020
1002 2 MANDAR 2021
1003 2 SACHIN 2021
1001 2 PALLAVI 2023
1002 1 MANDAR 2023

CREATE TABLE admisions (S_ID INT, C_ID INT, S_NAME VARCHAR(10), SINCE INT);

INSERT INTO admisions values (1001, 1, 'SACHIN', 2020);


INSERT INTO admisions values (1001, 2, 'SACHIN', 2020);
INSERT INTO admisions values (1002, 1, 'PALLAVI', 2021);
INSERT INTO admisions values (1002, 2, 'PALLAVI', 2022);
INSERT INTO admisions values (1003, 1, 'MANDAR', 2023);
INSERT INTO admisions values (1004, 1, 'BHAGYASHREE', 2023);

pg. 95
SELECT a.S_ID, a.S_NAME, a.C_ID, a.SINCE
FROM admisions a
JOIN admisions aa ON a.S_ID=aa.S_ID
AND a.C_ID <> aa.C_ID;

4. CROSS JOIN – Cartesian Product

 Cross join is nothing but join on multiple tables without any condition.
 Cross join is also known as Cartesian product.
 Cross join produces the lengthy out.
 table1 rows * table2 rows;

Simple query
SELECT E_ID, NAME, BLOOD_GROUP, EMAIL_ID, MOBILE_NUMBER, D_ID, GENDER, MANAGER FROM employees;
select * from departments;

Cross join query


select * from employees, departments;
select * from employees join departments;

Query with condition (Filtered output)


select E_ID, e.NAME, BLOOD_GROUP, EMAIL_ID, d.NAME
from employees e
join departments d ON d.D_ID=e.D_ID;

One day We will see all the types of joining.

pg. 96
Classroom assignment solution.

mysql> CREATE TABLE course (C_ID INT PRIMARY KEY AUTO_INCREMENT, CourseName VARCHAR(100), FEES INT );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE student (S_ID INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(100), Email VARCHAR(100)
NOT NULL UNIQUE, Contact VARCHAR(10) NOT NULL UNIQUE, Address VARCHAR(200) NOT NULL );
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE Placement (P_ID INT PRIMARY KEY AUTO_INCREMENT, CompName VARCHAR(100) NOT NULL,
Package INT NOT NULL, P_Date DATE);
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE csjoin (C_ID INT, S_ID INT, P_ID INT, FOREIGN KEY(C_ID) REFERENCES course(C_ID), FOREIGN
KEY(S_ID) REFERENCES student(S_ID), FOREIGN KEY(P_ID) REFERENCES placement(P_ID));
Query OK, 0 rows affected (0.05 sec)

mysql> INSERT INTO course (CourseName,FEES) VALUES ('Java', 32000);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO course (CourseName,FEES) VALUES ('.NET', 31000);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO course (CourseName,FEES) VALUES ('PHP', 28000);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO course (CourseName,FEES) VALUES ('TESTING', 29000);


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO course (CourseName,FEES) VALUES ('Aptitude and Communication', 9000);

mysql> INSERT INTO student (Name, Email, Contact, Address) VALUES ('Baban', '[email protected]',
'9988776656','Dharashiv');
INSERT INTO student (Name, Email, Contact, Address) VALUES ('Bhagyashree', '[email protected]',
'9988776655','Ahmadnager');
mysql> INSERT INTO student (Name, Email, Contact, Address) VALUES ('Rama', '[email protected]', '9988776657','C.S.
Nagar');
mysql> INSERT INTO student (Name, Email, Contact, Address) VALUES ('Shyam', '[email protected]', '9988776658','C.S.
Nagar');
mysql> INSERT INTO student (Name, Email, Contact, Address) VALUES ('Sachin', '[email protected]', '9988776659','Beed');

mysql> INSERT INTO placement (CompName, Package, P_Date) VALUES ('TCS', 360000, '2023-05-01');
mysql> INSERT INTO placement (CompName, Package, P_Date) VALUES ('Infosys', 300000, '2023-05-05');
mysql> INSERT INTO csjoin VALUES (1,1,1);
mysql> INSERT INTO csjoin VALUES (1,3,1);

pg. 97
mysql> INSERT INTO csjoin VALUES (2,3,2);
mysql> INSERT INTO csjoin VALUES (2,5,2);
mysql> INSERT INTO csjoin VALUES (1,6,2);
mysql> INSERT INTO csjoin VALUES (2,5,1);

Q. Write SQL Query to display the course wise student list?


SELECT s.NAME, c.CourseName from csjoin cs
INNER JOIN student s ON s.S_ID=cs.S_ID
INNER JOIN course c ON c.C_ID=cs.C_ID;

pg. 98
09/06/2023
MySQL Predefined Functions

 MySQL functions are used to perform calculation on data.


 To manipulate the output from group of rows.
 Function can format the data or numbers for display.
 It can also be used for modifying individual data items.
 MySQL functions are accepting the arguments and return the values.

There are two categories of inbuilt functions.


1. Single row function – Single row functions work on single row and return single result.
2. Multi row function or group functions – A group functions returns result based on a group of rows.

Single row functions types


1. Date functions
2. String functions
3. Match Functions
4. Control flow functions
Multi row functions
1. Aggregate functions.

Multi row functions


1. Aggregate functions.
 The aggregate function performs the calculations on multiple values and returns single value.
 The aggregate functions are used with GROUP BY clause.

Below is the list of aggregate functions.
i. SUM()
j. AVG()
k. COUNT()
l. MIN()
m. MAX()

12-06-2023
Single row functions.
Date functions
1. NOW() – Get the current date and time. Format of YYYY-MM-DD hh:mm:ss

mysql> SELECT NOW();


+---------------------+
| NOW() |
+---------------------+
| 2023-06-12 19:52:13 |
+---------------------+
1 row in set (0.00 sec)

mysql> SELECT NOW(), NOW()+0;


+---------------------+----------------+
| NOW() | NOW()+0 |
+---------------------+----------------+
| 2023-06-12 19:54:25 | 20230612195425 |
+---------------------+----------------+
1 row in set (0.01 sec)

mysql> SELECT NOW(), NOW() + INTERVAL 1 HOUR 'ADDED_1_HOUR';


+---------------------+---------------------+
| NOW() | ADDED_1_HOUR |

pg. 99
+---------------------+---------------------+
| 2023-06-12 19:56:31 | 2023-06-12 20:56:31 |
+---------------------+---------------------+
1 row in set (0.01 sec)

mysql> SELECT NOW(), NOW() + INTERVAL 1 HOUR 'ADDED_1_HOUR', NOW() + INTERVAL 1 YEAR;
+---------------------+---------------------+-------------------------+
| NOW() | ADDED_1_HOUR | NOW() + INTERVAL 1 YEAR |
+---------------------+---------------------+-------------------------+
| 2023-06-12 19:56:48 | 2023-06-12 20:56:48 | 2024-06-12 19:56:48 |
+---------------------+---------------------+-------------------------+
1 row in set (0.00 sec)

mysql> SELECT NOW(), NOW() + INTERVAL 1 HOUR 'ADDED_1_HOUR', NOW() - INTERVAL 2 MINUTE;
+---------------------+---------------------+---------------------------+
| NOW() | ADDED_1_HOUR | NOW() - INTERVAL 2 MINUTE |
+---------------------+---------------------+---------------------------+
| 2023-06-12 19:57:25 | 2023-06-12 20:57:25 | 2023-06-12 19:55:25 |
+---------------------+---------------------+---------------------------+

mysql> SELECT NOW(), NOW() + INTERVAL 1 HOUR 'ADDED_1_HOUR', NOW() - INTERVAL 2 MINUTE, NOW() +
INTERVAL 20 SECOND;
+---------------------+---------------------+---------------------------+----------------------------+
| NOW() | ADDED_1_HOUR | NOW() - INTERVAL 2 MINUTE | NOW() + INTERVAL 20 SECOND |
+---------------------+---------------------+---------------------------+----------------------------+
| 2023-06-12 19:57:52 | 2023-06-12 20:57:52 | 2023-06-12 19:55:52 | 2023-06-12 19:58:12 |
+---------------------+---------------------+---------------------------+----------------------------+

mysql> SELECT NOW(), NOW() + INTERVAL 1 MONTH, NOW() - INTERVAL 3 YEAR;


+---------------------+--------------------------+-------------------------+
| NOW() | NOW() + INTERVAL 1 MONTH | NOW() - INTERVAL 3 YEAR |
+---------------------+--------------------------+-------------------------+
| 2023-06-12 19:59:11 | 2023-07-12 19:59:11 | 2020-06-12 19:59:11 |
+---------------------+--------------------------+-------------------------+

Note: CURRENT_TIMESTAMP, CURRENT_TIMESTAMP both are synonyms for NOW();

mysql> SELECT NOW(), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP();


+---------------------+---------------------+---------------------+
| NOW() | CURRENT_TIMESTAMP | CURRENT_TIMESTAMP() |
+---------------------+---------------------+---------------------+
| 2023-06-12 20:00:30 | 2023-06-12 20:00:30 | 2023-06-12 20:00:30 |
+---------------------+---------------------+---------------------+
1 row in set (0.00 sec)

2. CURDATE() – Return date – YYYY-MM-DD

mysql> SELECT CURDATE();


+------------+
| CURDATE() |
+------------+
| 2023-06-12 |
+------------+
1 row in set (0.00 sec)

To get date in simple numeric form

mysql> SELECT CURDATE() + 0;


+---------------+
| CURDATE() + 0 |
+---------------+
| 20230612 |
+---------------+

pg. 100
1 row in set (0.00 sec)
Note: CURRENT_DATE, CURRENT_DATE() both functions are synonyms for CURDATE();

mysql> SELECT CURRENT_DATE, CURRENT_DATE(), CURDATE();


+--------------+----------------+------------+
| CURRENT_DATE | CURRENT_DATE() | CURDATE() |
+--------------+----------------+------------+
| 2023-06-12 | 2023-06-12 | 2023-06-12 |
+--------------+----------------+------------+

mysql> SELECT CURDATE(), CURDATE() + INTERVAL 1 YEAR, CURDATE() - INTERVAL 1 MONTH, CURDATE() + INTERVAL 3
DAY;

+------------+-----------------------------+------------------------------+----------------------------+

| CURDATE() | CURDATE() + INTERVAL 1 YEAR | CURDATE() - INTERVAL 1 MONTH | CURDATE() + INTERVAL 3 DAY |

+------------+-----------------------------+------------------------------+----------------------------+

| 2023-06-12 | 2024-06-12 | 2023-05-12 | 2023-06-15 |

+------------+-----------------------------+------------------------------+----------------------------+

1 row in set (0.00 sec)

3. SYSDATE(fsp)

fsp: Fractional second precision

mysql> SELECT SYSDATE(), SYSDATE(6);

+---------------------+----------------------------+

| SYSDATE() | SYSDATE(6) |

+---------------------+----------------------------+

| 2023-06-12 20:09:10 | 2023-06-12 20:09:10.460255 |

+---------------------+----------------------------+

1 row in set (0.00 sec)

pg. 101
4. DATEDIFF – To find the difference between date in DAYS

SELECT DATEDIFF(biger_date, smaller_date);

pg. 102
5. DATE_FORMAT – TO display the formatted date

DATE_FORMAT(date, format);

6. DAY, MONTH, YEAR

pg. 103
7. WEEK – get week from the year.

8. DAYNAME – Display day

9. DAYOFWEEK

pg. 104
2. STRING FUNCTION
1. UPPER(str) – to get string in upper case.
2. LOWER(str) – To get string in lower case.
3. CONCAT(str,str…) – Concatenate the string.

4. LENGTH(str)/CHAR_LENGTH(str) – To get the length of string

5. LEFT – To get Specified number of left most characters from string.


6. RIGHT – To get specified number of right most characters from string.

pg. 105
7. TRIM() – Remove the trailing spaces.
8. LTRIM() –
9. RTRIM() –

10. SUBSTRING(str, len) – Extract the substring from position with specified length.

3. MATH FUNCTIONS
1. PI – To get the value of PI

pg. 106
2. POW() Return the argument specified power

3. SQRT() - return the square root of argument.

4. MOD() - Return the reminder

pg. 107
5. ROUND() – Round a number to specified number of decimal spaces.

6. TRUNCATE ()

pg. 108
4. Comparison Functions
1. COALESCE – COALESCE (………) – Return the first non-null value
2. GREATEST – GREATEST (val,valval….) – Take N arguments and return the greatest value from them.
3. LEAST – LEAST(val,val,….) Take n arguments and return least value.
4. ISNULL - ISNULL(value) - return the 1 when value is null.

pg. 109
2. GREATEST

3. LEAST

pg. 110
4. ISNULL

5. CONTROL FLOW FUNCTIONS – The control flow functions allow you to add IF-THEN-ELSE logic to SQL queries
without using the procedures.

pg. 111
1. CASE
Syntax:
CASE <col>
WHEN <CompareValue> THEN <Result>
WHEN < CompareValue > THEN <Result>
.
.
ELSE <Result>
END
Example:
SELECT
CASE 1
WHEN 1 THEN 'ONE'
WHEN 2 THEN 'TWO'
ELSE 'OTHER'
END;

SELECT CASE 1 WHEN 1 THEN 'ONE' WHEN 2 THEN 'TWO' ELSE 'OTHER' END val;
SELECT CASE 2 WHEN 1 THEN 'ONE' WHEN 2 THEN 'TWO' ELSE 'OTHER' END val;
SELECT CASE 3 WHEN 1 THEN 'ONE' WHEN 2 THEN 'TWO' ELSE 'OTHER' END val;

SELECT CASE 3 WHEN 1 THEN 'ONE' WHEN 2 THEN 'TWO' ELSE 'OTHER' END val;

SELECT C_ID, NAME, FEES, DURATION, STATUS,


CASE STATUS
WHEN 1 THEN 'ACTIVE'
ELSE 'DEACTIVE'
END status
FROM courses;

pg. 112
2. IF (condition, truepart, falsepart)
IF(1=1, ‘correct’, ‘wrong’)

3. IFNULL(arg, arg)- Return first argument when argument is not null otherwise return second.
IFNULL(null, 1)
IFNULL(1,2);

pg. 113
pg. 114
16/06/2023

What is the Set Theory (Home Work)?

The Set Operators.


What is the set operators?
1. Set operators enable the comparison of rows from multiple tables.
2. Set operators helps to combination of results from multiple tables.
3. Set operators are used to join select statements without actually joining the tables.
4. Set operators in MySQL basically used to combine the result of more than one select statement and returns the
output as single result set.

There are four set operators in MySQL.


1. UNION - Return the result set with eliminate the duplicate records.
2. UNIONALL – Return all rows including duplicate records.
3. INTERSECT – Return only common records.
4. EXCEPT – Return only the rows unique to the first query.

Difference between JOIN and SET OPERATORS

Sr. No. SET OPERATOR JOIN


1 Combine rows from different tables. Combine columns from different tables
2 Always combines the result set vertically. Join appends the output horizontally.

Rules to use SET operators


1. Number of columns in select statement must be the same.
2. The order of columns in the select statement must be in the same.
3. Selected columns have must have the same data types.
4. Add order by clause at the end of the select statements.

1. UNION – After performing the UNION Operation the duplicate rows will be eliminated from the result.

Syntax:
SELECT col1,col2,col3….
FROM <Table>
UNION
SELECT col1,col2,col3….
FROM <table>
….
….

Example:
SELECT E_ID, NAME, EMAIL_ID, SALARY FROM employees
UNION
SELECT E_ID, NAME, EMAIL_ID, SALARY FROM old_employees;

pg. 115
1. Write a query to display the all employees from organization (including retired and current)

SELECT E_ID, NAME, EMAIL_ID, SALARY FROM employees


UNION
SELECT E_ID, NAME, EMAIL_ID, SALARY FROM old_employees;

2. Write a query to display the employees from two countries (UK and USA)

pg. 116
SELECT EmployeeID, FirstName, LastName
FROM employeeUSA
UNION
SELECT EmployeeID, FirstName, LastName
FROM employeeUK;

pg. 117
How to apply WHERE condition in UNION.
SELECT EmployeeID, FirstName, LastName
FROM employeeUSA
WHERE EmployeeID < 4
UNION
SELECT EmployeeID, FirstName, LastName
FROM employeeUK;

pg. 118
SELECT EmployeeID, FirstName, LastName
FROM employeeUSA
WHERE EmployeeID < 4
UNION
SELECT EmployeeID, FirstName, LastName
FROM employeeUK
WHERE EmployeeID < 4
;

pg. 119
ORDER BY Clause in UNION

SELECT EmployeeID, FirstName, LastName


FROM employeeUSA
WHERE EmployeeID < 4
UNION
SELECT EmployeeID, FirstName, LastName
FROM employeeUK
WHERE EmployeeID < 4
ORDER BY EmployeeID DESC ;

UNION ALL;
 Union all return the all records from the tables, including duplicate records.
 After performing the UNION ALL operation, the duplicate rows will not be eliminated from the results, and all the
data is displayed in the result without removing the duplication.
Syntax:
SELECT expression_1, expression_2, ... , expression_n
FROM table_1
UNION ALL
SELECT expression_1, expression_2, ... , expression_n
FROM table_2

Example:
SELECT EmployeeID, FirstName, LastName FROM EmployeeUSA
UNION ALL
SELECT EmployeeID, FirstName, LastName FROM EmployeeUK;

pg. 120
SELECT EmployeeID, FirstName, LastName FROM EmployeeUSA
UNION ALL
SELECT EmployeeID, FirstName, LastName FROM EmployeeUK
ORDER BY EmployeeID;

3. INTERSECTION: - The intersection operator is used to combine the two result set and returns the data which are
common in the result set.

pg. 121
Syntax:

SELECT col1,col2,col3…..
FROM table1
Conditions
INTERSECT
SELECT col1,col2,col3…..
FROM table2
Conditions

Example:
SELECT EmployeeID, FirstName, LastName, Gender, Department
FROM employeeUK
INTERSECT
SELECT EmployeeID, FirstName, LastName, Gender, Department
FROM employeeUSA;

pg. 122
After the where condition

4. EXCEPT: The except operator allows to Filter out the result sets which are present in the first table but absent in
the second table.

SELECT EmployeeID, FirstName, LastName, Gender, Department from employeeuk


EXCEPT
SELECT EmployeeID, FirstName, LastName, Gender, Department from employeeusa;

SELECT EmployeeID, FirstName, LastName, Gender, Department from employeeusa


EXCEPT
SELECT EmployeeID, FirstName, LastName, Gender, Department from employeeuk;

pg. 123
pg. 124
Nesting the Queries or Subquery
1. Subquery is the query which is present inside of another query.
2. The sub query is also known as inner query.
3. The query that contains sub query is called the outer query.
4. The inner executes first and gives the result to outer query and outer query will performed.
5. Sub query enclosed with the parentheses (round brackets.).

Syntax:
SELECT col1, col2,clo3…..
FROM <table>
WHERE condition
(
SELECT col…..FROM <table> [WHERE]
);

1. Write a query to show the employee details who has maximum salary.

SELECT E_ID, NAME, DATE_OF_JOINING, SALARY, D_ID, MANAGER, MOBILE_NUMBER


FROM employees
WHERE salary = (SELECT MAX(salary) FROM employees);

2. Write a query to show the third highest salary from employees.

SELECT SALARY FROM


(
SELECT DISTINCT SALARY FROM employees ORDER BY SALARY DESC LIMIT 3
)a
ORDER BY SALARY LIMIT 1;

pg. 125
pg. 126

You might also like