1. SQLClassRoom (1)
1. SQLClassRoom (1)
-----------------------------------
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
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
--------------------------------------------------------
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
pg. 2
3. DBMS - Sorting easy
3. FS - Is very hard
6. Avoid duplicate.
------------------------------------------------------------
Day 3 - Installation MySQL DBMS
Website visit
Create database.
Carete table - Column
80443
pg. 3
Client - Server
------------------------------------------
Databse - Tables
Charates Types
pg. 4
----------------------------------------------------------------------------------------
Day 4 - SQL Commands [Statement]
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;
pg. 5
Admin - Higher
Teaching staff - Course
HR - Recrutment
Other - Viewr
------------------------------------------------------------
SELECT CRATE
------------------------------------------------------------
Query to Show database list.
SHOW DATABASES;
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());
pg. 6
Constraint is optional
1. CREATE TABLE teachers (Name varchar(50) NOT NULL, MobileNumber varchar(10), Address
varchar(250));
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);
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);
----------------------------------------------------------------------
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)
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)
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.
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;
-----------------------------------------------------------------------
Day 8 - 12-04-2023
Ajenda for upcoming few days
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;
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.
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.
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;
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 -
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.
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.
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.
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%';
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
pg. 14
the can perform the operations on operands such as arithmetic, comparison operators.
What is operands
Operands is constant and columns in SQL.
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.
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;
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;
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
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;
4. BETWEEN
To get data in the form of range.
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 '_________';
21-04-2023
Integrity Constraints.
---------------------------------------
Keys in DBMS.
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
pg. 18
Keys in DBMS
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
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
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.
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.
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.
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.
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
pg. 21
Tomorrow
Integrity Constraints.
25/04/2023
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.
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));
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));
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
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.
pg. 26
ALTER TABLE std ADD (DOB DATE DEFAULT '1990-01-01' , DOJ DATETIME );
Existing column:
ALTER TABLE std ALTER SNAME SET DEFAULT 'A';
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
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
2. Existing column
pg. 29
3. Add with constraint name
27-04-2023
Table : student
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, …..)
);
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) );
2. Table alter
CREATE TABLE DEPARTMENT (DID INT, DCODE VARCHAR(2), DNAME VARCHAR(100));
pg. 31
Added records.
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>;
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.
Example:
CREATE TABLE emp
( EID INT CHECK (EID > 0) ,
NAME VARCHAR(100),
GENDER VARCHAR(10) 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);
pg. 36
5. PRIMARY KEY
What is the primary key?
How to implement the primary key on table?
How to drop the primary key?
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.
pg. 39
Example:
CREATE TABLE std
(
S_ID INT,
NAME VARCHAR(100),
D_ID INT,
CONSTRAINT pk_std_sid PRIMARY KEY (S_ID)
);
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)
);
pg. 41
CREATE TABLE bank
( BankID INT PRIMARY KEY AUTO_INCREMENT,
BankName VARCHAR(120) NOT NULL,
BankAddress VARCHAR(400)
);
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.
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
Syntax:
ALTER TABLE <TableName>
ADD PRIMARY KEY(Col1, col2,…);
Example:
ALTER TABLE laptops
ADD 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
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.
pg. 49
1. At the time of table creation
2. After table created – Alter table
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)
);
pg. 50
pg. 51
2. After the table creation – Alter table
Rules: Already exists table should follow the all rules for Foreign key.
Syntax:
ALTER TABLE <TableName>
ADD 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);
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.
Example:
SHOW CREATE TABLE std;
pg. 55
Difference between Foreign key and Primary key.
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?
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).
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);
pg. 63
INSERT INTO branhes (BranchName, BankId) VALUES ('WarjeNagar', 14);
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.
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.
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)
pg. 69
| 2 | SACHIN G | 9988776655 | 8 |
| 3 | Pallavi G | 9988776656 | NULL |
| 4 | Bhagyashree | 9988776657 | 6 |
+-----+-------------+------------+------+
3 rows in set (0.00 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)
------------------------------------------------------------------------------------
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
);
pg. 71
(
Col1 DT constraint,
Col2 DT constraint,
Col3 DT constraint,
FOREIGN KEY (ConName) REFERENCES <ParentTable>(ColName) ON DELETE RESTRICT ON UPDATE
RESTRICT
);
Examples:
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)
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)
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);
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> 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)
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)
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
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.
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;
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.
PS: Write the query to show the data as below from the tables;
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;
pg. 79
2. Write a query to display the cities count state wise.
Maharashtra 35,
Himachal Pradesh 30
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.
pg. 81
ItemPrice decimal(10,2) NOT NULL ,
ItemQuentity int NOT NULL DEFAULT 1,
OrderId INT,
FOREIGN KEY(OrderId) REFERENCES orders(OID)
);
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;
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;
4. Write a query to display orders lists, those order item count is more than 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;
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;
pg. 86
Practice Examples
pg. 87
INSERT INTO employee (E_NAME, E_EMAIL, E_CONTACT, E_DESIGNATION ,E_SALARY)
VALUES ('pallavi', '[email protected]', '9922881511', 'Developer', 31000);
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 |
+------+--------+------------------+------------+-----------------+----------+
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);
When miltiple records are same (Mupltiple employee salary are same)
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;
7. Write A SQL Query to show the company names who having no employee
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.
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.
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.
3. Write a query to show the company and employee list, display all company names who has employee or not.
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');
pg. 93
Syntax:
SELECT col1, col2, col3, ……
FROM table1
RIGHT OUTER JOIN table2 ON <condition>;
Examples:
1. Write the query to show employees, employee has assigned departments or not.
3.Write the query to show all female employee with address, who does not have address it should display.
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;
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
CREATE TABLE admisions (S_ID INT, C_ID INT, S_NAME VARCHAR(10), SINCE INT);
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;
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;
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 ('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);
pg. 98
09/06/2023
MySQL Predefined Functions
12-06-2023
Single row functions.
Date functions
1. NOW() – Get the current date and time. Format of YYYY-MM-DD hh:mm:ss
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 |
+---------------------+---------------------+---------------------------+----------------------------+
pg. 100
1 row in set (0.00 sec)
Note: CURRENT_DATE, CURRENT_DATE() both functions are synonyms for CURDATE();
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 |
+------------+-----------------------------+------------------------------+----------------------------+
+------------+-----------------------------+------------------------------+----------------------------+
3. SYSDATE(fsp)
+---------------------+----------------------------+
| SYSDATE() | SYSDATE(6) |
+---------------------+----------------------------+
+---------------------+----------------------------+
pg. 101
4. DATEDIFF – To find the difference between date in DAYS
pg. 102
5. DATE_FORMAT – TO display the formatted date
DATE_FORMAT(date, format);
pg. 103
7. WEEK – get week from the year.
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.
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
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;
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
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)
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
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.
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.
pg. 125
pg. 126