Dbmss
Dbmss
com/sainathatheli/5APlusplus
What is a Database?
In today’s World, Data plays a vital role in every business. In our day to day life, we see or
interact with many applica ons and So ware’s, every applica on that we see or work with will
2. Database
To keep it simple GUI is the part where user interacts with (like Facebook applica ons – look
and feel) and the Data that we see in the applica on (like Facebook profile, messages, images
End User who interacts with the applica on may not know how the data is being fetched and
where so much of informa on is stored. Internally all the dynamic content that we see in the
Database and all its components should be designed and configured at the me of applica on
development. Once the applica on is developed we will not be able to make changes to the
database structure as every change will hugely affect the business applica on GUI code.
It is very important to make sure that data is securely maintained and accurately stored.
So to maintain security and accuracy in database a set of rules / so ware system is defined and that
we call it as DBMS (Data Base Management System – which performs all the opera ons on the
database)
What is DBMS?
DBMS (Database Management System) is a so ware tool that is used to store and manage data
in the Database.
A database management system contains a set of programs that control the crea on,
DBMS allows different user applica on programs to concurrently access the same database.
Before Database and DBMS were introduced, tradi onal approach was to store data in flat files
(physical files in system) but there were some disadvantages with it.
What is RDBMS?
(DBMS) that is based on the rela onal model introduced by E. F. Codd and most popular
databases currently in use are based on the rela onal database model. To put in different
words RDBMS is built on top of in which data is stored in tables and the rela onships among
the data are maintained. The data stored in a table is organized into rows and columns. Each
row in a table represents an individual record and each column represents a field. A record is
----------------------------------
For example, consider the database which stores employee informa on.
In DBMS, all details like empno, ename, job, salary, deptno, dname, loca on, street, city, state, phone
will
But in RDBMS, the data model will be designed in such a way that
like the empno, ename, job, salary and deptno will be stored in emp table and deptno, dname,
loca on will be stored in dept table and loca on, street, city, state, phone will be stored under
loca ons table.
MYSQL:
======-------
DDL
===
DML
===
DMl is used to perform insert or update or delete a record from database Object(table)
commands are :- insert,update,delete
============================
command:
=======
select
DDL:
====
Step1:
======
1)createing a database:
syntax:
=======
ex:
===
sol:
====
=========================
cmd is :---
show databases;
====================================================================
cmd:
-----
use database;
ex:
----
use cts;
=============================================
cmd:
----
select database();
crea ng a table:
=================
syntax:
=======
col1 datatype,
col2 dataetype,
ex:
===
tablename: employee
empno int 4
ename varchar 20
sol:
====
=====================================
cmd:
----
show tables;
=======================================
syntax:
-------
describe tablename;
ex:
---
describe employee;
====================================================
syntax:
-------
ex:
===
sol:
----
===========================================
syntax:
=======
ex:
===
alter:
======
-------------------------------
syntax:
-------
---
sol:
====
ex2:
===
sol:
====
----------------------------------------
syntax:
-------
ex:
===
sol:
=====
ex:
===
sol:
----
ex:
---
sol:
----
note:
=====
===================================
syntax:
-------
ex:
===
sol:
----
==========================================
syntax:
--------
ex:
---
sol:
---
======================================
syntax:
-------
3)rename at DDL:
==============
rename a object
syntax:
=======
ex:
===
sol:
---
rename table employee to employees;
4) truncate :
=============
truncate command is used to remove or delete all the records or rows or tuples from a table.
note:
====
syntax:
-------
ex:
---
sol:
----
5)drop
======
note:
-----
drop command will remove the strucutre and data from the database.
syntax:
========
ex:
---
sol:
----
DML:
====
insert:
=======
=========================================
a) create table named as employees(empno,ename,job,sal,hiredate); date format:- 'yyyy-mm-dd'
b) insert five records into employees table for all the columns.
sol:
====
------------------------------------------------------
syntax:
=======
===
sol:
====
============================
syntax:
-------
(value1,value2,value3,value4),
(value1,value2,value3,value4),
(value1,value2,value3,value4),
(value1,value2,value3,value4),
(value1,value2,value3,value4);
ex:
===
sol:
----
(7187,'madhu','Trainee',4000,'2020-12-10'),
(7154,'suhas','manager',6000,'2009-09-09'),
(7787,'balu','analyist',9000,'2018-10-02');
Update:
=======
update is used to update the exis ng record data from the table.
syntax:
=======
note:
====
===
sol:
====
Ex
---
write a query to update job,ename columns of employees table where sal is 5000;
sol:-
=====
Ex:
===
write a query to update sal with bonus 100 for all the employees;
sol:
----
delete:
=======
syntax:
-------
note:
=====
ex:
===
write a query to delete a record from employees table where sal is 10000;
sol:
----
ex:
===
write a query to delete a records from employees table where sal is 6000;
sol:
----
====
cmd: select
select command is used to display all columns or specific columns data from a table.
syntax:
-------
ex1:
====
sol:
----
ex2:
====
sol:
----
----
sol:
----
===================
inser into select statement copies the data from one table and
note:
-----
In insert into select statement that source data types and target
sytntax:
--------
ex1:
===
copy the empno,ename columns data from employees table and insert
into student(sid,sname);
sol:
====
or
==============================
select current_date();
=======================================
======================================
create table tablename as select * [specific columns ] from table where 1=2;
ex1:
===
create a table named as emp11 as copy structure of empno,ename,sal with out data.
sol:
====
======================================
ex1:
===
with data.
sol:
====
============
MySQL CONSTRAINT is used to define rules to allow or restrict what values can be stored in columns.
MySQL CONSTRAINTS are used to limit the type of data that can be inserted into a table.
MySQL CONSTRAINTS can be classified into two types - column level and table level.
The column level constraints can apply only to one column where as table level constraints are
applied
to the en re table.
-----------------------
NOT NULL
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK
DEFAULT
NOT NULL:
---------
In MySQL NOT NULL constraint allows to specify that a column can not contain any NULL value.
syntax:
-------
Ex:
---
sol:
====
DEFAULT:
--------
It ensures that the column sets a default value for empty records.
In a MySQL table, each column must contain a value ( including a NULL). While inser ng data into a
table,
if no value is supplied to a column, then the column gets the value set as DEFAULT.
syntax:
=======
Ex:
---
create table named as ex2(sid,sname,marks) with not noll and default constraint for marks.
sol:
----
+-----+-------+-------+
| 1 | ss | 30 |
| 2 | BB | 0|
+-----+-------+-------+
CHECK:
------
The CHECK constraint determines whether the value is valid or not from a logical expression
(condi on).
syntax:
-------
ex:
---
create a table named as ex3(sid,sname,age,address) with not null constraint and apply
check constraint for age column(age should be greater than 18)
sol:
----
colum-level
-----------
mysql>
table-level:
============
syntax;
------
check(condi on) );
ex:
---
sol:
----
address varchar(10),
check(sal>1500));
UNIQUE:
-------
The UNIQUE constraint in MySQL does not allow to insert a duplicate value in a column.
colum-level
-----------
ex:
---
create table named as ex5(empno,ename,sal) with not null constraint for ename,sal and unique
constraint
for empno
sol:
----
-----------
unique(columname),
);
ex:
---
unique(empno));
PRIMARY KEY:
------------
It uniquely iden fies a row in the table. It is a combina on of NOT NULL and UNIQUE constraints
A PRIMARY KEY constraint for a table enforces the table to accept unique data for a specific column.
Note:
-----
syntax:
-------
colum-level
ex:
---
sol:
----
sal int(5));
Table-level:
-------------
col1 datatype ,
primary key(columnname),
);
ex:
---
ename varchar(10),
sal int(5),
primary key(empno));
mysql>
FOREIGN KEY:
------------
A FOREIGN KEY in MySQL creates a link between two tables by one specific column of both tables.
we can add foreign key for specified column using References keyword.
syntax:
-------
column-level
------------
col2 datatype,
col 3 datatype,
ex:
---
create paren able named as dept_1(deptno,dname,loc) and here deptno is primary key
and empno is pk ,link between two tables dept_1,emp_1 using specified column(deptno);
sol:
---
dname varchar(10),
loc varchar(10)
);
ename varchar(10),
sal int(5),
Ex:
---
table-level
-----------
syntax:
-------
col2 datatype,
col 3 datatype,
specifiedcolumn datatype,
sol:
----
cid int(4),
cname varchar(10),
fees int(4),
primary key(cid));
child table:
-------------
sid int(4),
sname varchar(10),
address varchar(10),
cid int(4),
primary key(sid),
================================================
first insert the records into parent table followed by child table.
ON DELETE CASCADE:
==================
ERROR
----------------------
Ex:
---
====
pname varchar(10),
price decimal(10,2));
-----------------------------------
cname varchar(10),
caddress varchar(10),
pid int(4),
first insert the records into parent table followed by child table.
delete a record from parent check it record is delete or not ? yes deleted
To display all constraints on a table, you can try any of the following methods
----------------------------------------------------------------------------------
------------------------------
------------------------
------------------------------------
------------------------
ex:
====
Alter Level:
============
ex:
---
-----------------------------------------
--------------------------------------------
=========================================
syntax:
-------
==============================================
syntax:
-------
note:
-----
Adding not null and default constraint at alter level and table level are not possibe.
select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME,
REFERENCED_TABLE_NAME
==============================
Mysql Aliases:
==============
Mysql aliases can be used to create a temporary name for columns or tables.
-------------------
==================
----
+------------+
| todayDate |
+------------+
| 2021-03-03 |
+------------+
ex:
---
Mysql Aliases:
==============
Mysql aliases can be used to create a temporary name for columns or tables.
-------------------
==================
ex:
----
+------------+
| todayDate |
+------------+
| 2021-03-03 |
+------------+
ex:
---
Scrip ile:
===========
create a file , specify group of mysql commands and save the file with filename.sql
===================
Ex:
===
to run :
--------
source mysqlscript.sql
JOINS:
======
Join are used to retrieve the records from mul ple tables .
join are used to create temporary a rela on between the tables
-------------------------------------------
Inner join
Le join
Right join
Self-join
Cross join
InnerJoin or equi-join:
-----------------------
Inner joins fetch or return the matched records from the both tables.
syntax:
--------
select specific_columns from table1 alias name inner join table2 aliasename
on(table1.common_column_name=table2.common_column_name);
Ex:
---
write a inner join or equi-join to fetch matched records from dept,emp tables.
dept(deptno,dname,loc)
emp(empno,ename,sal,job,deptno)
sol:
---
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.job,e.deptno
le Join:
---------
le outer join fetches the matched records from both tables and
syntax:
------
select specific_columns from table1 alias name le [outer] join table2 aliasename
on(table1.common_column_name=table2.common_column_name);
note:
----
Ex:
---
write a join to fetch matched records from dept,emp tables and non-matched records from dept.
dept(deptno,dname,loc)
emp(empno,ename,sal,deptno)
sol:
---
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
Right Join:
---------
Right outer join fetches the matched records from both tables and
syntax:
------
select specific_columns from table1 alias name Right [outer] join table2 aliasename
on(table1.common_column_name=table2.common_column_name);
note:
----
Ex:
---
write a join to fetch matched records from dept,emp tables and non-matched records from emp.
dept(deptno,dname,loc)
emp(empno,ename,sal,deptno)
sol:
---
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
---------------
syntax:
------
select specific_columns from table1 alias name Full [outer] join table2 aliasename
on(table1.common_column_name=table2.common_column_name);
Ex:
---
write a join to fetch matched records and non-matched records from dept,emp tables.
emp(empno,ename,sal,deptno)
sol:
---
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
--we can perform full outer join by union using le join and right join
------------------------------------------------------------------------
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
deptno,dname,loc from dept by using selec on criteria display the deptno 20 decords.
sol:
----
or
---------
note:
----
ex:
---
write a query to display employeenames and its managers from emp table using self join?
sol:
----
cross Join:
-----------
ex:
==
dept--5records
emp -- 15 records
sol:
----
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal from dept d cross join emp e;
or
NATURAL JOIN:
=============
EX:
===
NOTE:
=====
IN NATURAL JOIN THE COMMON COLUMN NAME BETWEEN THE TWO TABLE
NON-EQUI JOIN:
==============
SALGRADE Table
------------------
SOL:
=====
SELECT E.EMPNO,E.ENAME,E.SAL,S.GRADE
-------------------
1. Arithme c Operators
------------------------
In MySQL, arithme c operators are used to perform the arithme c opera ons as described below.
-----------------------------
Operator Descrip on
Example
------------------------------------------
The comparison operators in MySql are used to compare values between operands and
return true or false according to the condi on specified in the statement.
-----------------------------
Operator Descrip on
-------- ------------
> If the value of le operand is greater than that of the value of the right operand,
< If the value of le operand is less than that of a value of the right operand,
= If both the operands have equal value, the condi on becomes true; if not then false.
!= If both the operands do not have equal value, the condi on becomes true; if not then false.
>= If the value of le operand is greater than or equal to the right operand, the condi on
becomes true;
<= If the value of le operand is less than or equal to the right operand, the condi on becomes
true;
<> If the values of two operands are not equal, the condi on becomes true; if not then false.
(INCLUSIVE)
IN RETURNS THE VALUE ,THE VALUE AVAILABLE IN THE
Ex:
---
Logical operators
-----------------
---
mysql> SELECT FALSE AND FALSE, FALSE AND TRUE,TRUE AND FALSE, TRUE AND TRUE;
mysql> SELECT FALSE OR FALSE, FALSE OR TRUE, TRUE OR FALSE, TRUE OR TRUE;
3)The NOT operator is nega on operator. It makes true false and false true.
Ex:
---
sol:-
or
LIKE OPERATOR:
==============
SYNTAX:
=======
LIKE 'PATTERN'
EX:
===
WRITE A QUERY TO DISPALY ALL ENAMES FROM EMP
SOL:
====
ex:
===
sol:
=====
ORDER BY CLAUSE:
================
QUERY.
-----------
DESC
SYNTAX:
========
===========================================
ex:
---
SUM
AVG
MIN
MAX
COUNT
GROUP BY Clause
---------------
GROUP BY Clause is used to collect data from mul ple records and group the result
SYNTAX:
=======
note:
----
The expressions that are not encapsulated within an aggregate func on and must be included in the
GROUP BY clause.
EX
===
sol:
----
or
----
sol:
----
HAVING Clause
-------------
HAVING Clause is used with GROUP BY clause. It always returns the rows where condi on is TRUE.
The HAVING clause is used in the SELECT statement to specify filter condi ons for a group of rows
or aggregates.
The HAVING clause is o en used with the GROUP BY clause to filter groups based on a specified
condi on.
If the GROUP BY clause is omi ed, the HAVING clause behaves like the WHERE clause.
syntax:
-------
===
sol:
---
or
------------------
MySQL string func ons that allow you to manipulate character string data effec vely.
1. ASCII(str)
--------------
Returns the ASCII value of the le most character of the string str.
Ex:
--
+------------+
| ascii('a') |
+------------+
| 97 |
+------------+
+------------+
| ascii('A') |
+------------+
| 65 |
+------------+
Ex:
---
+--------------+
| ascii(ename) |
+--------------+
| 83 |
| 65 |
| 87 |
| 74 |
| 77 |
| 66 |
| 67 |
| 83 |
| 75 |
| 84 |
| 65 |
| 74 |
| 70 |
| 77 |
+--------------+
2.CHAR_LENGTH(str)
------------------
ex:
----
+------------------------+
| char_length('welcome') |
+------------------------+
| 7|
+------------------------+
ex:
----
------------------------------
Returns a string formed by joining str1 to strn. If any sub-string is NULL, the result is NULL.
ex:
---
--------------------------------------
Ex:
---
+------------------+
| concat_ws |
+------------------+
| hello#hi#welcome |
+------------------+
Ex:
---
--------------------------------
Replaces the sub-string star ng at posi on pos and of length len in the string str with newstr.
Ex:
---
mysql> select insert('welcome','3','3','aaa');
+---------------------------------+
| insert('welcome','3','3','aaa') |
+---------------------------------+
| weaaame |
+---------------------------------+
Ex:
---
smith,3,3,'hii' --smhii
---------------------------------------------------------------------
Ex:
---
-----------------------------------------
Ex:
===
mysql> select lcase('HELLO');
write a query to dislay the ename in lower case from emp table
----------------------------------
Returns the le most and rightmost len characters from the string str.
Ex:
--
+-----------------+
| le ('hello',3) |
+-----------------+
| hel |
+-----------------+
+------------------+
| right('hello',3) |
+------------------+
| llo |
+------------------+
9.LENGTH(str) / OCTET_LENGTH(str)
---------------------------------
Ex:
===
--------------------------------------
Returns the string str a er trimming white spaces from le , right or both ends.
Ex;
---
12.QUOTE(str)
-------------
+------------------------+
| quote('welcome$hello') |
+------------------------+
| 'welcome$hello' |
+------------------------+
+--------------------------+
| quote('welcome\n hello') |
+--------------------------+
| 'welcome
hello' |
+--------------------------+
Replaces all occurrences of sub-string from_str with sub-string to_str in the string str.
It is case-sensi ve.
Ex:
---
+------------------------------+
| replace('welcome','el','hi') |
+------------------------------+
| whicome |
+------------------------------+
Ex:
---
14.REVERSE(str)
---------------
Ex:
---
--------------------------------------------------------------------------------------
Returns a substring from the string str star ng from posi on pos,
Ex:
==
+-------------------+----------------------+
| substr('hello',2) | substring('hello',2) |
+-------------------+----------------------+
| ello | ello |
+-------------------+----------------------+
+---------------------+------------------------+
| substr('hello',2,2) | substring('hello',2,2) |
+---------------------+------------------------+
| el | el |
+---------------------+------------------------+
Ex:
---
| substr('welcome',-4,3) |
+------------------------+
| com |
+------------------------+
NUMBER FUNCTIONS:
=================
SYNTAX:
=======
ABS(NUM)
EX:
===
SELECT ABS(5),ABS(-5),ABS(NULL);
OLP:-- 5,5,
SQRT:
=====
========
SQRT(NUM);
EX:
===
SELECT SQRT(4),SQRT(9),SQRT(5),SQRT(NULL);
OLP:-- 2,3,2.36,
MOD:
====
SYNTAX
======
MOD(VALUE,DIVISON);
EX:
===
SELECT MOD(4,2),MOD(5,2);
O/P:- 0,1
ifnull():
=========
THIS FUNCTION IS USED TO REPLACE THE NULL VALUES.
SYNTAX:
-------
ifNULL(colname,REPLACE VALUE)
EX:
===
SOL:
====
CEIL:
======
THIS FUNCTION ROUND THE VALUE TO not less than current value.
SYNTAX:
========
CEIL(NUM);
EX:
===
SELECT CEIL(4.5),CEIL(5),CEIL(4.2) ;
OLP:- 5,5,5
FLOOR:
======
SYNTAX:
-------
FLOOR(NUM);
EX:
===
SELECT FLOOR(4.5),FLOOR(4.2),FLOOR(4.7);
O/P:- 4,4,4,
pow(numer,exponen al):
======================
select pow(3,2),pow(2,3);
o/p:- 9,8
VIEWS:
======
A VIEW IS A LOGICAL REPRESENTATION OF DATA FROM ONE OR MORE THEN ONE TABLE.
When we write select statement on view, we get the data from the table for the first me.
-------------------------
Views help simplify complex queries. If you have any frequently used complex query, you can create
a view based on it so that you can reference the view by using a simple SELECT statement instead of
typing the query all over again.
Suppose you have to repeatedly write the same formula in every query. Or you have a query that
has complex business logic. To make this logic consistent across queries, you can use a view to store
the calcula on and hide the complexity.
A table may expose a lot of data including sensi ve data such as personal and banking informa on.
By using views and privileges, you can limit which data users can access by exposing only the
necessary data to them.
For example, the table employees may contain SSN and address informa on, which should be
accessible by the HR department only.
To expose general informa on such as first name, last name, and gender to the General
Administra on (GA) department, you can create a view based on these columns and grant the users
of the GA department the view, not the en re table employees .
TYPES OF VIEW:
==============
1)SIMPLE VIEW
2)COMPLEX VIEW
SIMPLE VIEW:
============
SYNTAX:
========
FROM TABLENAME;
EX:
===
EMPNO,ENAME,SAL
SOL:
====
=============================
ex:
====
------------------------------------
SELECT
TABLE_SCHEMA,
TABLE_NAME,
TABLE_TYPE
FROM
informa on_schema.TABLES
WHERE
or
----------------------------------------
to drop a view:
===============
COMPLEX VIEW:
=============
SYNTAX:
=======
EX:
===
CREATE COMPLEX VIEW TO STORE EQUI JOIN OUTPUT OF DEPT AND EMP TABLE.
SOL:
====
====================================
Ex:
Create or replace view v3 As select empno, ename, sal, deptno from emp with read only;
====================
These views will allow DML opera on only when where condi on is sa sfied.
Ex:
As select empno, ename, sal, deptno from emp Where deptno = 30 With check op on;
ex:
ALter a view:
--------------
-----
1.Created by using only one table. 1. Created by using mul ple tables.
2.DML opera ons are allowed. 2. DML opera ons are not allowed.
3.Should not be created using 3. Can be created using arithme c arithme c opera ons or
func ons opera ons or func ons or or group by clauses.
group by clauses.
Exercises:
----------
salesman
---------
-------------+------------+----------+------------
(5002,'Nail Knite','Paris',0.13),
(5005,'Pit Alex','London',0.11),
(5006,'Mc Lyon','Paris',0.14), ;
1. From the following table, create a view for those salespeople who belong to the city of New York.
2. From the following table, create a view for all salespersons. Return salesperson ID, name, and city.
3. From the following table, create a view to locate the salespeople in the city 'New York'.
4. From the following table, create a view to count the number of unique customers, compute the
average and the total purchase amount of customer orders by each date.
tables:
--------
-------------+----------------+------------+-------+-------------
orders:
---------
----
Subqueries:
------------
An SQL subquery is nothing but a query inside another query. We use a subquery to fetch data from
two tables. A subquery is o en also referred to as an inner query, while the statement containing a
subquery is also called an outer query or outer select.
There are some rules which are followed while using subqueries.
They are:
Subqueries that return over one row can only be used with mul ple value operators such as the IN
,All or Any operator.
4.Co−related subquery
5.Scalar subquery
6.Inline view
---------------------
Ex: write a query to display details are having salary > 'ALLENS' sal ?
Select * from emp where sal > (select sal from emp where ename = 'ALLEN');
internally execu on:
----------------------
Note:
-----
Subqueries are executed first and then parent query is executed by using the result of sub query.
----------------
Select * from emp where job = (select job from emp where ename = 'ALLEN') AND job = (select job
from emp where ename = 'BLAKE');
0/p=0;
Select * from emp where job = (select job from emp where ename = 'ALLEN') AND sal = (select sal
from emp where ename = 'ALLEN');
------------------------------------
Select * from emp where sal > (select sal from emp Where ename = (select ename from emp Where
empno = 7499));
Note:
-----
The above query is three level query. Sub query can be nested upto 32 levels.
ALL
----
OR
ANY
----
OR
------------------------
When subquery returns mul ple rows. It is called mul ple row salary.
Note: we should use mul ple row operators with mul ple row subqueries.
1.IN
2.ANY
3.ALL
All:
----
Select * from emp Where sal > ALL(Select sal from emp Where deptno = 30);
Any:
-----
Select * from emp where sal > ANY(select sal from emp where deptno = 30);
------------------------
*IN:
-----
Select * from emp where ename IN(select ename from emp where deptno = 30);
Select * from emp where sal IN(select sal from emp where deptno = 30);
--------------------------
When subquery return more then one column. It is called mul ple column subquery.
Exercise:
---------
sol:
----
select max(sal) from emp where sal < (select max(sal) from emp);
Co-RELATED SUBQUERY:
--------------------
*write a query to display all the rows who are having salary greater than AVG salary his department?
Ex:
----
Select * from emp e where sal > (select AVG(sal) from emp where deptno = e.deptno);
Execu on:
----------
In co−related subquery, parent query is executed first and then subquery is executed in rela on to
result of parent query(parenet table alias name).
SCALAR subquery:
---------------
Example:
--------
Select deptno, dname, loc, (Select sum(sal) from emp where deptno = d.deptno) Sum_sal from dept
d;
*from clause subquery or INLINE VIEW:
--------------------------------------
When a subquery is used in from clause. It is called INLINE view or inline subsquery.
Ex:
------
----------------------
Exists:
------
In the previous sec on, we used IN to link the inner query and the outer query in a
subquerystatement.
IN is not the only way to do so -- one can use many operators such as >, <, or =.
EXISTS is a special operator that we will discuss in this sec on.
EXISTS simply tests whether the inner query returns any row. If it does, then the outer query
proceeds. If not, the outer query does not execute, and the en re SQL statement returns nothing.
SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
( SELECT *
FROM "table_name2"
Example:
Exercises On Subqueries:
-------------------------
1. Write a query to display the employee name and hiredate for all
sol:
----
select ename,hiredate from emp where deptno =(select deptno from emp where ename ='BLAKE')
and ename !='BLAKE';
2.Create a query to display the employee number and name for all employees who earn
more than the average salary. Sort the results in descending order of salary.
sol:
---
select empno,ename from emp where sal >(select avg(sal) from emp ) order by sal desc;
3.Write a query to display the employee number and name for all
employees who work in a department with any employee whose name contains a T.
sol:
----
4.Display the employee name, department number, and job tle for all
sol:
---
select ename,deptno, job from emp where deptno=(select deptno from dept where loc='Dallas')
5.Display the employee name and salary of all employees who report to King.
select ename,sal from emp where mgr in (select empno from emp where ename='KING');
dense_rank():
--------------
---------------------------
SELECT empno, ename, sal, DENSE_RANK() OVER (ORDER BY sal) my_rank FROM emp;
Based on each department you need assign DENSE rank using PARTITION BY:
----------------------------------------------------------------
FROM emp;
Rank:
-----
This func on assigns a rank to each row within a par on that has gaps.
In this case, ranks are assigned in a non-consecu ve manner i.e if there two records have the same
value then they will be assigned the same rank, and the next rank value will be the previous rank plus
the number of duplicates.
Examples:
---------
SELECT empno, ename, sal, RANK() OVER (ORDER BY sal) my_rank FROM emp;
Based on each department you need assign rank using PARTITION BY:
----------------------------------------------------------------
SELECT empno, ename, sal, deptno,RANK() OVER (PARTITION BY deptno ORDER BY sal) my_rank
FROM emp;
Exercise:
---------
write query to get second highest salary using subquery and Dense_rank().
sol:
---
select dis nct sal from (select empno,ename,sal,dense_rank() over (order by sal desc) as dnk from
emp) dnkemp
where dnkemp.dnk=2;
INDEXES:
========
TYPES OF INDEXES:
======================================
1)SIMPLE INDEX
SIMPLE INDEX:
=============
=======
EX:
===
---------------------
create index:
--------------
A er Index created:
---------------------
NOTE:
======
RANGE SCAN.
COMPLEX or composite index:
---------------------------
SYNTAX:
========
Ex:
---
---------------------
create index:
-------------
a er index created:
--------------------
3)Unique index:
----------------
Syntax:
--------
ex:
---
=======================================
Ex:
to drop index:
--------------
SET OPERATORS:
==============
UNION
UNIONALL
=======================
2. column data type should match for the queries in set operators.
UNION:
======
EX:
====
UNION ALL:
==========
UNION ALL
NOTE:
=====
-> union
Variable:
=========
A variable allows a programmer to store data temporarily during the execu on of code.
syntax:
-------
select @variablename;
Ex:
===
+----------------+
| @name |
+----------------+
| Sumit deshpade |
+----------------+
Case- WHEN-END
===============
syntax:
-------
case columnname
[else]
end;
Ex:
----
============================
select case
else salary
end
where re.rnk=2
or
where re.rnk=2
or
select max(salary)
where re.rnk=2
if condi on:
-------------
syntax:
-------
if (expr1,exp2,exp3) --> if expr1 is true then it will return exp2,if not then it exp3;
ex:
---
ifnull() or NVl() or coalesce() --to replace the null with some values .
------------------------
You can restrict the access to records of the tables in MYSQL by locking them. These locks are used to
keep other sessions away from modifying the tables in the current session.
MySQL sessions can acquire or release locks on the table only for itself. To lock a table using the
MySQL LOCK TABLES Statement you need have the TABLE LOCK and SELECT privileges.
These locks are used to solve the concurrency problems. There are two kinds of MYSQL table locks −
READ LOCK − If you apply this lock on a table the write opera ons on it are restricted. i.e., only the
sessions that holds the lock can write into this table.
WRITE LOCK − This lock allows restricts the sessions (that does not possess the lock) from performing
the read and write opera ons on a table.
Syntax:
-------
------------------------
Once the client session is done using/accessing a MySQL table, they must unlock the table for other
client sessions to use it. To do so, you can use the MySQL UNLOCK TABLE statement. This will release
the table un l other sessions lock it again.
Syntax:
-------
UNLOCK TABLES;
---------------------------
syntax:
-------
Grant Privileges:
-----------------
ex:
---
-------------------
syntax:
-------
ex:
----
-----------------
syntax:
Ex:
----
Enterpasswor:*****
-----------------------------------------
-----------------
Ex:
---
Enterpasswor:*****
Procedure
=========
We can invoke the procedures by using triggers, other procedures and applica ons such as Java,
Python, PHP, etc.
-------------------------
Stored Procedure increases the performance of the applica ons. Once stored procedures are
created,
send only the stored procedure's name and parameters instead of sending mul ple SQL statements.
applica ons that access stored procedures in the database without giving any permissions on the
database tables.
syntax:
-------
BEGIN
Executable_sec on
END && or //
DELIMITER ;
-------------- -----------------------------------------------
==========================
IN: These types of parameters are assigned the values while calling the stored procedure and
the value cannot be modified or overwri en inside the stored procedure but only referenced and
OUT: These are the parameters that can be assigned the values and overridden in the stored
procedure
IN OUT: These types of parameters are assigned the values while calling the stored procedure and
the value can be modified or overwri en inside the stored procedure as well as
======================
syntax:
-------
Ex:1
-----
Create a procedure to store select query to display the data from emp table.
sol:
===
Delimiter //
begin
end //
to call procedure:
===================
call ex1();
===========================================
ex:
===
to drop procedure:
==================
or
use database;
Ex2:
====
create a procedure named as ex2 and to store the query to display the emp records
sol:
====
Delimiter //
begin
end //
delimiter ;
to call procedure:
==================
call ex2(10);
call ex2(20);
call ex2(30);
Ex3:
----
create a procedure named as ex3 to store max(sal) into out parameter from emp table.
sol:
====
Delimiter //
begin
end //
delimiter ;
=====================================
call ex3(@s); /*when call the procedure it will return out parameter or variable
value,then we need to store that value into a variable).*/
select @s ;
Exercise:
---------
sol:
====
delimiter //
begin
select ename into en from emp where empno=eno;
end //
delimiter ;
-----------------
call ex4(7566,@n);
select @n;
Ex:
====
write a procedure to perfrom sum of two numbers(two -IN) and return sum(OUT)
sol:
----
delimiter //
begin
set c=a+b;
end //
delimiter ;
----------------
call ex_sum(10,30,@st)
select @st
Ex4:
-----
sol:
----
delimiter //
create procedure ex_en(in eno decimal,out en varchar(10))
begin
end //
delimiter ;
---------------
call ex_en(7566,@vn);
select @vn
ex4:
====
create procedure named as ex4 to store max(sal) int to outparameter from emp
sol:
----
delimiter //
begin
end //
delimiter ;
to call procedure:
==================
call ex4(10,@tn);
select @tn;
call ex4(20,@tn);
select @tn;
call ex4(30,@tn);
select @tn;
Ex5:
----
sol:
----
Delimiter //
begin
end //
======================
set @n=10; /*it will act as input parameter */
call ex5(@n);
select @n;
--------------
set @n=20
call ex5(@n);
select @n;
Ex6:
----
sol:
---
delimiter //
begin
declare a int;
declare c float;
set a=10;
set c=300;
end //
delimiter ;
----------------------
call ex6();
=================================
if:
---
if condi on then
statement-1;
end if;
if-else:
--------
syntax:
-------
if condi on then
statement-1;
else
statement-2;
end if;
Ex:
---
sol:
-----
delimiter //
begin
if a > b then
else
end if;
select msg;
end //
delimiter ;
sol:
===
Delimiter //
begin
if a>b then
else
end if;
select msg;
end //
delimiter ;
to call procedure:
------------------
call ex7(10,5) ;
call ex7(1,5) ;
Ex:
---
if-else-if:
-----------
syntax:
-------
if condi on then
statement-1;
statement-2;
statement-3;
else
statement-4;
end if;
ex:
---
sol:
---
Delimiter //
begin
else
end if;
select msg;
end //
delimiter ;
to call procedure:
==================
call ex8(10,5,1);
call ex8(5,10,2);
cal ex8(5,1,7);
Exercises:
=========
using in parameters.
sol:
----
delimiter //
begin
set res=n1+n2;
select res;
end //
delimiter ;
to call procedure:
------------------
call ex_9(10,10);
sol:
----
delimiter //
begin
set res=n1+n2;
end //
delimiter ;
to call procedure:
==================
call ex10(10,30,@rs);
select @rs;
Func on:
---------
In MySQL, a func on is a stored program that you can pass parameters into and then return a value.
Just as you can create func ons in other languages, you can create your own func ons in MySQL.
Syntax
-------
--------------------------------------------
DELIMITER //
RETURNS return_datatype
DETERMINISTIC
BEGIN
declara on_sec on
executable_sec on
return datatype;
END;
DELIMITER //
func on_name
--------------
parameter
----------
One or more parameters passed into the func on. When crea ng a func on,
where the parameters can be referenced by the func on but can not be overwri en by the func on.
return_datatype
----------------
declara on_sec on
--------------------
executable_sec on
------------------
The place in the func on where you enter the code for the func on.
DETERMINISTIC:
--------------
it means the func on will return the same values if the same arguments are supplied to it.
Ex:
---
sol:
----
delimiter //
returns int
DETERMINISTIC
begin
return (a+b+c);
end //
delimiter ;
----------------------
---
-----------------
note:
-----
(Don't use predefined func on names like string func ons,date func ons,number func ons etc).
Ex:
---
sol:
----
delimiter //
returns decimal
DETERMINISTIC
begin
return v_m;
end //
delimiter ;
=====================
Exercise:
---------
sol:
====
delimiter //
returns varchar(20)
DETERMINISTIC
begin
declare en varchar(20);
return en;
end //
delimiter ;
=====================
TRIGGERS:
=========
A Trigger in MySQL is a special kind of stored opera on that gets invoked automa cally when an
event has
It is a database object which is related to a table in the database and becomes ac ve when a defined
MySQL
These DML (Data Manipula on Language) execu on opera ons can be INSERT, DELETE, UPDATE and
triggers
A trigger is a set of ac ons that are run automa cally when a specified change opera on
Triggers are useful for tasks such as enforcing business rules, valida ng input data, and keeping an
audit trail.
For example when a row is inserted to a table or when any columns are modified, a trigger can be
fired.
Mostly, triggers can are made to run whenever any altera ons are done to the data of a table.
Triggers are simply a SQL code to run before or just a er any DML ac on events on a par cular table
in a database.
Syntax
-------
CREATE
trigger_ me trigger_event
ON tbl_name
FOR EACH ROW
trigger_body
Parameters
------------
DEFINER clause:
---------------
Iden fies the MySQL account that is used for access at trigger ini a on me.
trigger_name:
-------------
trigger_ me:
-------------
Defines the trigger ac on me which can be either before or a er any row affected.
trigger_event:
--------------
tbl_name:
---------
The table name should be of a permanent table not a temporary or a view table to associate a
trigger.
trigger_body:
-------------
The compound statement construct BEGIN … END can be used to complete many statements.
=========================
Row-Level Trigger:
=================
It is executed when each row is affected by inser on, upda on and dele on ac ons on a table.
Like if you have a table and 50 rows are inserted, updated or deleted, then automa cally the trigger
Statement-Level Trigger:
======================
This trigger is invoked only once for a transac on regardless of the number of rows inserted,
updated, or deleted.
note:
=====
PSEUDO COLUMNS:
===============
============
delimiter //
{before/a er}
begin
statment; or logic;
end //
delimiter //
Example:
========
2) create a trigger before insert into emp13 covert the ename into capital le er.
----
2)
delimiter //
begin
set New.ename=upper(New.ename);
end //
delimiter ;
3)
Example:
--------
--------
delimiter //
begin
end //
Example:
----------
write a trigger on emp15 table before insert into empno column append PU_ to empno.
sol:
----
2)
delimiter //
create trigger trg_emp_15
begin
set New.empno=concat('PU_',New.empno);
end //
delimiter ;
3)
Exercise:
=========
2)create trigger on studentdetails before insert to table it should calculate sum of m1+m2+m3 and
store in total column
sol:
----
2)
delimiter //
create trigger trg_sd
begin
set New.total=New.m1+New.m2+New.m3;
end //
delimiter ;
1 Rahul 60 60 70 190
execute insert
==============
-> (101,'rahul',60,70,80);
+------+-------+------+------+------+-------+
+------+-------+------+------+------+-------+
+------+-------+------+------+------+-------+
--------
bank aud ng
sol:
sol:
3)create a trigger before update an record in emp_base table insert that record into
emp_base_update(history,new value).
sol:
----
delimiter //
(old.empno,new.ename,old.ename,new.sal,old.sal,'update',current_date());
end //
delimiter ;
Execute:
--------
+-------+--------+------+
+-------+--------+------+
+-------+--------+------+
+-------+---------+---------+-------+-------+--------+------------+
+-------+---------+---------+-------+-------+--------+------------+
+-------+---------+---------+-------+-------+--------+------------+
--=======
3) create a trigger before delete a record from emp_base,the deleted record should backup into
emp_base_delete table.
sol:
----
delimiter //
begin
(old.empno,old.ename,old.sal,'delete',current_date());
end //
delimiter ;
Execute:
========
+-------+--------+------+
+-------+--------+------+
+-------+--------+------+
+-------+-------+------+--------+------------+
+-------+-------+------+--------+------------+
+-------+-------+------+--------+------------+
mysql>
to drop a trigger:
==================
=============================
ex:
---
or
show triggers;
---------------------
MySQL supports a bunch of date u lity func ons that we can use to handle DATE efficiently.
NOW()
------
This date func on returns the current date and me of the running server instance.
SELECT NOW();
DATE()
--------
This date func on extracts and returns the date part from the given DATETIME value.
SELECT DATE(NOW());
CURDATE()
----------
It is a simple date func on that fetches the current date of the system running the MySQL instance.
SELECT CURDATE();
DATE_FORMAT():
--------------
Some mes you need to display a date in a user-defined style. For example, you want to show the
month first, then the date, and the year in the last.
DATEDIFF():
------------
You may want to count the difference between the two dates.
Note:
-----
The DATEDIFF() func on would subtract the second date argument from the first and return the diff
in days.
i.e 3
DATE_ADD():
-------------
It enables you to add any of the days, weeks, months, or years to a given date. Check the below
example.
SELECT
'2019-08-04' ACTUAL,
EXTRACT():
----------
The EXTRACT func on will extract a part of a date from a specified date value.
EXTRACT(unit FROM date)
It uses the same unit specifiers as other date func ons such as DATE_ADD and DATE_SUB.
Specifier Descrip on
--- -----------
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%k Hour (0..23)
%l Hour (1..12)
%p AM or PM
%S Seconds (00..59)
%s Seconds (00..59)
%U Week (00..53), where Sunday is the first day of the week; WEEK() mode 0
%u Week (00..53), where Monday is the first day of the week; WEEK() mode 1
%V Week (01..53), where Sunday is the first day of the week; WEEK() mode 2; used with
%X
%v Week (01..53), where Monday is the first day of the week; WEEK() mode 3; used with
%x
%X Year for the week where Sunday is the first day of the week, numeric,
four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits;
used with %v
%% A literal % character
------------------------------------
A Common Table Expression (CTE) is a temporary named result set that is defined within the scope of
a single SQL query.
It allows you to write complex queries in a more readable and maintainable manner, by breaking
them down into smaller, logical steps.
CTEs can be used in MySQL with the "WITH" keyword, followed by the name of the CTE and the
SELECT statement that defines it. Once a CTE is defined, it can be referenced mul ple mes within
the same query.
One of the main benefits of using CTEs is that they allow you to create recursive queries, which are
queries that reference themselves.
This can be useful for tasks such as genera ng hierarchical data or finding the shortest path between
nodes in a graph.
CTEs can also be used to simplify the syntax of complex joins, to create derived tables that can be
used within other queries, or to improve query performance by reducing the number of mes that a
subquery needs to be executed
------------------
The basic syntax for crea ng a Common Table Expression (CTE) in MySQL is as follows:
WITAH cte_name(
FROM table_name
WHERE condi on
SELECT *
FROM cte_name;
Syntax:mul ple CTEs within the same query, by separa ng each CTE defini on with a comma. For
example:
WITH cte1 AS (
FROM table1
),
cte2 AS (
SELECT *
FROM cte1
In this example, two CTEs are defined: "cte1" and "cte2". The CTEs are then referenced in the main
query by joining them on a common column and selec ng all columns from both CTEs.
------------------
Suppose you have a sales table with columns "product_name", "sales_date", and "revenue".
You want to calculate the total revenue for each product over the past 30 days, as well as the
percentage change in revenue compared to the previous 30-day period. You can use a CTE to
calculate these metrics:
product_name VARCHAR(50),
sales_date DATE,
The following commands can be used to insert data into the table:
Query:
-------
WITH sales_last_30_days AS (
FROM sales
GROUP BY product_name
),
sales_previous_30_days AS (
FROM sales
GROUP BY product_name
SELECT
s.product_name,
s.total_revenue,
FROM sales_last_30_days s
------------
This CTE first calculates the total revenue for each product over the past 30 days and stores the result
in a CTE called "sales_last_30_days".
It then calculates the total revenue for each product over the previous 30-day period and stores the
result in a CTE called "sales_previous_30_days".
The main query joins these two CTEs on the "product_name" column and calculates the percentage
change in revenue.
-----------------------------
Suppose you have a database with a table called "sales" that contains sales data for a company. The
"sales" table has columns for "order_date", "product", "quan ty", and "revenue".
You want to create a report that shows the total revenue generated by each product, broken down
by month. However, you also want to include a column that shows the percentage of total revenue
generated by each product, based on the revenue generated by all products.
order_date DATE,
product VARCHAR(50),
quan ty INT,
revenue DECIMAL(10,2)
);
INSERT INTO sales1 (order_date, product, quan ty, revenue) VALUES
Query:
-----
WITH monthly_sales AS (
SELECT
product,SUM(revenue) AS revenue
),
total_sales AS (
SELECT
month,SUM(revenue) AS total_revenue
SELECT
monthly_sales.month,
monthly_sales.product,
monthly_sales.revenue,
FROM
monthly_sales
-------------------
Here are some of the benefits of using Common Table Expressions (CTEs) in MySQL:
-----------------------
CTEs can be used to break down complex queries into smaller, more manageable parts. By defining
CTEs, you can avoid wri ng complex subqueries mul ple mes, which can make your code easier to
read and understand.
-------------------------
CTEs can help improve query performance by reducing the number of database scans required to
execute a query. By defining a CTE, you can create a temporary table that can be used to store
intermediate results, which can reduce the number of scans required to retrieve data.
Reuse code:
----------
CTEs can be used to create modular SQL code that can be reused across mul ple queries. By defining
a CTE at the beginning of a query, you can create a self-contained module that can be used in other
queries, making your code more flexible and adaptable.
-------------------------
CTEs can be used to traverse hierarchical data structures, such as organiza onal charts or product
categories. By defining a recursive CTE, you can traverse the hierarchy and perform complex
calcula ons on the data.
Simplify debugging:
------------------
CTEs can help simplify debugging by breaking a complex query into smaller parts. By defining CTEs,
you can analyze each part of the query individually, making it easier to iden fy and fix errors.
------------------------
CTEs can improve the readability of your SQL code by providing a clear and concise way to define
temporary named result sets. By using descrip ve names for your CTEs, you can make your code
easier to read and understand.
------------------------
You can restrict the access to records of the tables in MYSQL by locking them. These locks are used to
keep other sessions away from modifying the tables in the current session.
MySQL sessions can acquire or release locks on the table only for itself. To lock a table using the
MySQL LOCK TABLES Statement you need have the TABLE LOCK and SELECT privileges.
These locks are used to solve the concurrency problems. There are two kinds of MYSQL table locks −
READ LOCK − If you apply this lock on a table the write opera ons on it are restricted. i.e., only the
sessions that holds the lock can write into this table.
WRITE LOCK − This lock allows restricts the sessions (that does not possess the lock) from performing
the read and write opera ons on a table.
Syntax:
-------
------------------------
Once the client session is done using/accessing a MySQL table, they must unlock the table for other
client sessions to use it. To do so, you can use the MySQL UNLOCK TABLE statement. This will release
the table un l other sessions lock it again.
Syntax:
-------
UNLOCK TABLES;
---------------------------
syntax:
-------
Grant Privileges:
-----------------
ex:
---
-------------------
------------------
syntax:
-------
ex:
----
-----------------
syntax:
Ex:
----
Enterpasswor:*****
will you get the error
-----------------------------------------
-----------------
Ex:
---
Enterpasswor:*****