Dbms full notes
Dbms full notes
com/sainathatheli/5APlusplus
What is a Database?
To keep it simple GUI is the part where user interacts with (like Facebook
applications – look
and feel) and the Data that we see in the application (like Facebook profile,
messages, images
and videos) are pulled from Database.
End User who interacts with the application may not know how the data is being
fetched and
where so much of information is stored. Internally all the dynamic content that we
see in the
application is fetched from Database.
Database and all its components should be designed and configured at the time of
application
development. Once the application is developed we will not be able to make changes
to the
database structure as every change will hugely affect the business application GUI
code.
It is very important to make sure that data is securely maintained and accurately
stored.
What is DBMS?
DBMS (Database Management System) is a software tool that is used to store and
manage data
in the Database.
A database management system contains a set of programs that control the creation,
maintenance, and use of a database. Like:
Redundancy: In a flat file system, data often gets duplicated across multiple
files, leading to redundancy.
Scattered Data: Data is scattered across various files, making it hard to correlate
and retrieve related data efficiently.
Constraints: Enforcing data integrity constraints like foreign keys, unique keys,
and checks is challenging in flat file systems.
Security Issues
Access Control: Implementing fine-grained access control in flat file systems is
difficult, leading to potential security risks.
Data Privacy: Protecting sensitive data from unauthorized access is more complex
without a centralized control mechanism.
What is RDBMS?
A relational database management system (RDBMS) is a Database Management System
(DBMS) that is based on the relational model introduced by E. F. Codd and most
popular
databases currently in use are based on the relational database model. To put in
different
words RDBMS is built on top of in which data is stored in tables and the
relationships 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
an individual entry in the database.
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, location will be stored in dept table and location, street, city,
state, phone will be stored under locations table.
Any information to be obtained is done by properly relating the ‘emp’, ‘dept’
and ‘locations’ tables.
DDL
===
Data definition Language
DML
===
Data manipulation Language
command:
=======
select
DDL:
====
Step1:
======
if you want to create any objects in mysql we need to use database.
1)createing a database:
syntax:
=======
sol:
====
cmd is :---
show databases;
cmd:
-----
use database;
ex:
----
use cts;
cmd:
----
select database();
creating a table:
=================
syntax:
=======
ex:
===
tablename: employee
empno int 4
ename varchar 20
sal decimal 10,2 -->738.30
sol:
====
show tables;
syntax:
-------
describe tablename;
ex:
---
describe employee;
syntax:
-------
ex:
===
sol:
----
syntax:
=======
ex:
===
alter:
======
ex:
---
Add column name is job to existing table employee.
sol:
====
ex2:
===
sol:
====
syntax:
-------
ex:
===
modify the size of job column 20 to 10 size.
sol:
=====
alter table employee modify job varchar(10);
ex:
===
modify the size of address column 20 to 30 size.
sol:
----
alter table employee modify address varchar(30);
ex:
---
change mobileno datatype int to decimal
sol:
----
alter table employee modify mobileNo decimal(10);
note:
=====
if want to decrease the size or change the datatype of column => All the values in
the coloum becomes NULL
firt we need to make column should contain null values.
syntax:
-------
ex:
===
sol:
----
ex:
---
rename columname sal to salary in employee table
sol:
---
syntax:
-------
sol:
-----
3)rename at DDL:
==============
rename a object
syntax:
=======
ex:
===
rename table name employee to employees;
sol:
---
4) truncate :
=============
truncate command is used to remove or delete all the records or rows or tuples from
a table.
note:
====
once table is truncated we cannot restore those delete records.
syntax:
-------
truncate table tablename;
ex:
---
truncate a table employees;
sol:
----
truncate table employee;
5)drop
======
note:
-----
drop command will remove the strucutre and data from the database.
syntax:
========
ex:
---
sol:
----
DML:
====
insert:
=======
using insert command we can insert a row or record into table.
b) insert five records into employees table for all the columns.
sol:
====
syntax:
=======
ex:
===
insert 3 record into a table for specific columns(empno,ename,sal) of employees
sol:
====
syntax:
-------
ex:
===
insert multiple records into employees table
sol:
----
REPLACE:
========
sol:
Update:
=======
update is used to update the existing record data from the table.
syntax:
=======
note:
====
If where condition is not specified then all the records will be
updated in the table.
Ex:
===
update sal column(3000 to 5000) of employees record where empno 7547
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:
=======
delete command is used to delete a specific records based on condition or
we can delete all the records with out condition.
syntax:
-------
note:
=====
if where condition is not specified all the records will be deleted.
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:
----
delete from employees where sal=6000;
DRL:
====
cmd: select
select command is used to display all columns or specific columns data from a
table.
syntax:
-------
select * [specific columns] from tablename [where condition]
ex1:
====
write a query to all the records from the employees table?
sol:
----
select * from employees;
ex2:
====
write a query to display empno,enmae,sal from employees table ?
sol:
----
select empno,ename,sal from employees;
ex3:
----
sol:
----
select * from employees where sal>=5000 and sal<=7000;
note:
-----
In insert into select statement that source data types and target data types should
be same.
sytntax:
--------
insert into tgt_tablename select *[specific columns ] from src_tablename
[where condition]
ex1:
===
copy the empno,ename columns data from employees table and insert
into student(sid,sname);
sol:
====
create table student(sid int(4),sname varchar(20));
or
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:
===
sol:
====
CONSTRAINTS:
============
MySQL CONSTRAINT is used to define rules to allow or restrict what values can be
stored in columns.
The purpose of inducing constraints is to enforce the integrity of a database.
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 entire table.
Constraints can be both inline [beside the coloumn] or last of the table which is
table constraint
both are same but table constaints are more radable and industry stadards
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:
-------
create table tablename (
colum1 datatype not null,
column2 datatype not null,
column3 datatype not null)
Ex:
---
create table named as ex1(empno,ename,sal) with not null constraints.
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
inserting 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:
----
create table ex2(
sid int(4) not null,
sname varchar(10) not null,
marks int(4) not null default 0);
CHECK:
------
A CHECK constraint controls the values in the associated column.
The CHECK constraint determines whether the value is valid or not from a logical
expression (condition).
syntax:
-------
check (condition)
sol:
----
colum-level
-----------
create table ex3(
sid int(4) not null,
sname varchar(10) not null,
age int(3) not null check(age>18),
address varchar(10) not null);
table-level:
============
syntax;
------
create table tablename(
col1 datatype [null | not null],
col2 datatype [null | not null] ,
col3 datatype [null | not null] default value,
check(condition) );
ex:
---
create a table named as ex4(empno,ename,sal,job,address) with check constraint for
sal(sal>1500) at table level
sol:
----
create table ex4(
empno int(4) not null,
ename varchar(10) not null,
sal int(5) not null,
job varchar(10) not null,
address varchar(10),
check(sal>1500));
colum-level
-----------
create table tablename(
col1 datatype [null | not null] default value,
col2 datatype [null | not null] unique,
col3 datatype [null | not null] default value);
ex:
---
create table named as ex5(empno,ename,sal) with not null constraint for ename,sal
and unique constraint
for empno
sol:
----
create table ex5(
empno int(5) unique,
ename varchar(10) not null,
sal int(5) not null);
Table-level
-----------
create table tablename(
col1 datatype [null | not null],
col2 datatype [null | not null],
col3 datatype [null | not null],
unique(columname),
);
ex:
---
create table ex6( empno int(4),
ename varchar(10) not null,
sal int(5) not null,
job varchar(10) not null,
unique(empno));
PRIMARY KEY:
------------
It uniquely identifies a row in the table. It is a combination 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:
-----
A Table Should contain only one primary key.
syntax:
-------
colum-level
ex:
---
create a table named as ex7(empno,ename,sal)with primary key (empno)
sol:
----
create table ex7( empno int(4) primary key,
ename varchar(10) not null,
sal int(5));
Table-level:
-------------
ex:
---
create table ex8( empno int(4),
ename varchar(10),
sal int(5),
primary key(empno));
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
------------
ex:
---
create parenttable named as dept_1(deptno,dname,loc) and here deptno is primary key
create child table named as emp_1(empno,ename,sal deptno) here-deptno is specified
column
and empno is pk ,link between two tables dept_1,emp_1 using specified
column(deptno);
sol:
---
create table dept_1(
deptno int(3) primary key,
dname varchar(10),
loc varchar(10)
);
Ex:
---
table-level
-----------
syntax:
-------
create table tablename(col1 datatype,
col2 datatype,
col 3 datatype,
specifiedcolumn datatype,
foreign key(specified_column) REFERENCES
parent_table(Specified_column-pk);
sol:
----
create table course(
cid int(4),
cname varchar(10),
fees int(4),
primary key(cid));
child table:
-------------
create table student_1(
sid int(4),
sname varchar(10),
address varchar(10),
cid int(4),
primary key(sid),
foreign key(cid) REFERENCES course(cid));
ON DELETE CASCADE:
==================
IF TRY TO DELETE A RECORD FROM PARENT TABLE IF
THEIR EXISTS DEPENDENT RECORD (CHILD RECORD),WE WILL GET
ERROR
Ex:
---
create table named as product_1(pid,pname,price) --> pid is pk
create table named as customer_1(cid,cname,address,pid)--> cid is pk and pid is
fk
link two tables using specified column(pid) with on delete cascade;
sol:
====
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:
---
note:
-----
Adding not null and default constraint at alter level and table level are not
possibe.
Mysql Aliases:
==============
In some situation we have long table names in our database to use this long table
names we need to use that long names instend we can create a simple short temporary
name to that long name called Allias
Mysql aliases can be used to create a temporary name for columns or tables.
ex:
----
mysql> select current_date() as 'todayDate' ;
ex:
---
mysql> select e.ename,e.sal from employees as e;
Mysql Aliases:
==============
Mysql aliases can be used to create a temporary name for columns or tables.
ex:
----
mysql> select current_date() as 'todayDate' ;
ex:
---
mysql> select e.ename,e.sal from employees as e;
Scriptfile:
===========
create a file , specify group of mysql commands and save the file with filename.sql
Ex:
===
create a file named as mysqlscript.sql
and add the following below commands
to run :
--------
source mysqlscript.sql
==============================================================
==============================================================
JOINS:
======
Join are used to retrieve the records from multiple tables .
Inner join
Left join
Right join
Full outer 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
from dept d inner join emp e on(d.deptno=e.deptno);
left Join:
---------
left outer join fetches the matched records from both tables and
non-matched records from the left table.
syntax:
------
select specific_columns from table1 alias name left [outer] join table2
aliasename
on(table1.common_column_name=table2.common_column_name);
note:
----
Here table1 act as left table.
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
from dept d left join emp e on(d.deptno=e.deptno);
Right Join:
---------
Right outer join fetches the matched records from both tables and
non-matched records from the Right table.
syntax:
------
select specific_columns from table1 alias name Right [outer] join table2
aliasename
on(table1.common_column_name=table2.common_column_name);
note:
----
Here table2 act as right table.
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
from dept d Right join emp e on(d.deptno=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
from dept d full join emp e on(d.deptno=e.deptno);
--we can perform full outer join by union using left join and right join
------------------------------------------------------------------------
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
from dept d left join emp e on(d.deptno=e.deptno)
union
select d.deptno,d.dname,d.loc,e.empno,e.ename,e.sal,e.deptno
from dept d Right join emp e on(d.deptno=e.deptno);
sol:
----
select e.empno,e.ename,e.sal,d.deptno,d.dname,d.loc from dept d join emp e
on(d.deptno=e.deptno) and d.deptno=20;
or
self Join:
---------
A self join is a join that is used to join a table with itself.
note:
----
we need to create two aliasname on the same table.
ex:
---
write a query to display employeenames and its managers from emp table using self
join?
sol:
----
Table:
------
cross Join:
-----------
It will perform cartesian product.
ex:
==
write query to perform cross join between dept and emp ?
dept--5records
emp -- 15 records
cross join -- 5*15 = 75 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:
=============
NATURAL JOIN IS SIMILAR TO INNER JOIN,
BUT THE CONDITION IS PERFORMED IMPLICITY BASED ON COLUMN NAME.
EX:
===
NOTE:
=====
IN NATURAL JOIN THE COMMON COLUMN NAME BETWEEN THE TWO TABLE
MUST BE SAME. IF NOT IT WILL PERFORM CROSS JOIN
NON-EQUI JOIN:
==============
=,!= OTHER THAN THESE OPERATORS(like between,in,...)
SALGRADE Table
------------------
CREATE TABLE SALGRADE (GRADE int,LOSAL int,HISAL int);
SOL:
=====
SELECT E.EMPNO,E.ENAME,E.SAL,S.GRADE
FROM EMP E,SALGRADE S WHERE E.SAL BETWEEN S.LOSAL AND S.HISAL;
==============================================================
==============================================================
Operators in MySQL
-------------------
Operators are used to specifying a condition in a statement in MySQL.
Below are the different types of operators used in MySQL.
1. Arithmetic Operators
------------------------
In MySQL, arithmetic operators are used to perform the arithmetic operations as
described below.
Operator Description
Example
+ Addition of two operands
a + b
– Subtraction of right operand from the left operand
a – b
* Multiplication of two operands
a * b
/ Division of left operand by the right operand
a / b
% Modulus – the remainder of the division of left a % b
operand by the right
The comparison operators in MySql are used to compare values between operands and
return true or false according to the condition specified in the statement.
Operator Description
-------- ------------
> If the value of left operand is greater than that of the value of the right
operand,
the condition becomes true; if not then false.
< If the value of left operand is less than that of a value of the right
operand,
the condition becomes true; if not then false.
= If both the operands have equal value, the condition becomes true; if not
then false.
!= If both the operands do not have equal value, the condition becomes true; if
not then false.
>= If the value of left operand is greater than or equal to the right operand,
the condition becomes true;
if not then false.
<= If the value of left operand is less than or equal to the right operand, the
condition becomes true;
if not then false.
<> If the values of two operands are not equal, the condition becomes true; if
not then false.
Ex:
---
SELECT * FROM EMP WHERE SAL > 4000;
Logical operators
-----------------
logical operators we perform boolean operations.
Ex:
---
1)The AND operator evaluates to true if both operands are true.
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 negation operator. It makes true false and false true.
Ex:
---
1)WRITE A QUERY TO DISPLAY RECORD WITH SPECIFIED RANGE(between oper)
SAL 2000 AND 3000?
sol:-
or
LIKE OPERATOR:
==============
SYNTAX:
=======
LIKE 'PATTERN'
EX:
===
WRITE A QUERY TO DISPALY ALL ENAMES FROM EMP
WHERE ENAME START WITH S.
SOL:
====
SELECT ENAME FROM EMP WHERE ENAME LIKE 'S%';
ex:
===
write a query to display all enames start with
sol:
=====
select ename from emp where ename like 'A_L%';
==============================================================
==============================================================
ORDER BY CLAUSE:
================
THIS CLAUSE IS USED TO SORT THE OUTPUT STATEMENT BASED ON SELECT
QUERY.
DESCENDING
-----------
DESC
SYNTAX:
========
SELECT * FROM TABLENAME [WHERE] [ORDER BY COLUMNANME...];
==============================================================
==============================================================
==============================================================
GROUP BY Clause
---------------
GROUP BY Clause is used to collect data from multiple records and group the result
by one or more column.
It is generally used in a SELECT statement.
You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on
the grouped column.
SYNTAX:
=======
note:
----
The expressions that are not encapsulated within an aggregate function and must be
included in the GROUP BY clause.
EX
===
1)WRITE A QUERY TO PERFORM SUM OF SALARIES BASED ON for EACH
DEPARTMENT NO FROM EMP TABLE.
sol:
----
select Deptno,sum(sal) from emp group by deptno;
or
+--------+----------+
| deptno | SUM(sal) |
+--------+----------+
| 10 | 92000.00 |
| 20 | 80000.00 |
| 30 | 95000.00 |
| 40 | 30000.00 |
+--------+----------+
Or
BY using joins
==============
+------------+------------+
| dname | sum(e.sal) |
+------------+------------+
| Accounting | 92000.00 |
| Research | 80000.00 |
| Sales | 95000.00 |
| Operations | 30000.00 |
+------------+------------+
sol:
----
select deptno,sum(sal) as total_sum,
count(empno) from emp group by deptno;
+--------+-----------+--------------+
| deptno | total_sum | count(empno) |
+--------+-----------+--------------+
| 10 | 92000.00 | 2 |
| 20 | 80000.00 | 2 |
| 30 | 95000.00 | 2 |
| 40 | 30000.00 | 1 |
+--------+-----------+--------------+
sol:
----
select deptno,job,sum(sal),count(ename) from emp group by deptno,job order by
deptno;
HAVING Clause
-------------
HAVING Clause is used with GROUP BY clause. It always returns the rows where
condition is TRUE.
The HAVING clause is used in the SELECT statement to specify filter conditions
for a group of rows or aggregates.
The HAVING clause is often used with the GROUP BY clause to filter groups based on
a specified condition.
NOTE:
=====
If the GROUP BY clause is omitted, the HAVING clause behaves like the WHERE
clause.
syntax:
-------
SELECT exp1,expr2,aggregate_function(expr) FROM TABLNAME [WHERE][GROUP BY
exp1,expr2]
[Having condition][ORDER BY
COLUMNS];
Ex;
===
Write a query to display sum(sal) of for each dept sum(sal)greater 8750?
Error:
======
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near 'where sal > 8750' at line 1
select deptno ,sum(sal) from emp group by deptno where sal > 8750;
sol:
---
+--------+----------+
| deptno | sum(sal) |
+--------+----------+
| 10 | 92000.00 |
| 20 | 80000.00 |
| 30 | 95000.00 |
| 40 | 30000.00 |
+--------+----------+
4 rows in set (0.00 sec)
or
select deptno,sum(sal) as ssal from emp group by deptno having ssal>8750 ;
==============================================================
==============================================================
String Functions:
------------------
MySQL string functions that allow you to manipulate character string data
effectively.
1. ASCII(str)
--------------
Returns the ASCII value of the leftmost character of the string str.
Ex:
--
mysql> select ascii('a');
+------------+
| ascii('a') |
+------------+
| 97 |
+------------+
1 row in set (0.00 sec)
Ex:
---
mysql> select ascii(ename) from emp;
+--------------+
| ascii(ename) |
+--------------+
| 83 |
| 65 |
| 87 |
| 74 |
| 77 |
| 66 |
| 67 |
| 83 |
| 75 |
| 84 |
| 65 |
| 74 |
| 70 |
| 77 |
+--------------+
2.CHAR_LENGTH(str)
------------------
Returns the length of the string str in characters.
ex:
----
mysql> select char_length('welcome');
+------------------------+
| char_length('welcome') |
+------------------------+
| 7 |
+------------------------+
1 row in set (0.00 sec)
ex:
----
select ename,char_length(ename) as "len" from emp;
ex:
---
mysql> select concat('hello','hi','welcome') as concat;
Ex:
---
mysql> select concat_ws('#','hello','hi','welcome') as concat_ws;
+------------------+
| concat_ws |
+------------------+
| hello#hi#welcome |
+------------------+
Ex:
---
mysql> select concat_ws('$','hello',ename) as concatws from emp;
Ex:
---
mysql> select ename,insert(ename,3,3,'hii') from emp;
smith,3,3,'hii' --smhii
Ex:
---
mysql> select instr('foobar','oo');
Ex:
===
mysql> select lcase('HELLO');
write a query to dislay the ename in lower case from emp table
select lower(ename) from emp;
Ex:
--
mysql> select left('hello',3);
+-----------------+
| left('hello',3) |
+-----------------+
| hel |
+-----------------+
1 row in set (0.00 sec)
mysql> select right('hello',3);
+------------------+
| right('hello',3) |
+------------------+
| llo |
+------------------+
1 row in set (0.00 sec)
9.LENGTH(str) / OCTET_LENGTH(str)
---------------------------------
Returns the length of the string str in bytes.
Ex:
===
mysql> select length('welcome');
Ex;
---
mysql> select ltrim(' hello');
12.QUOTE(str)
-------------
This query quotes and un-quotes the string str.
Special characters are escaped.
Ex:
---
mysql> select replace('welcome','el','hi');
+------------------------------+
| replace('welcome','el','hi') |
+------------------------------+
| whicome |
+------------------------------+
1 row in set (0.00 sec)
Ex:
---
mysql> select ename,replace(ename,'S','A') from emp;
14.REVERSE(str)
---------------
Reverses the string str.
Ex:
---
mysql> select reverse('hello') ;
Ex:
==
mysql> select substr('hello',2),substring('hello',2);
+-------------------+----------------------+
| substr('hello',2) | substring('hello',2) |
+-------------------+----------------------+
| ello | ello |
+-------------------+----------------------+
1 row in set (0.01 sec)
Ex:
---
mysql> select substr('welcome',-4,3);
+------------------------+
| substr('welcome',-4,3) |
+------------------------+
| com |
+------------------------+
1 row in set (0.00 sec)
==============================================================
==============================================================
NUMBER FUNCTIONS:
=================
SYNTAX:
=======
ABS(NUM)
EX:
===
SELECT ABS(5),ABS(-5),ABS(NULL);
OLP:-- 5,5,
SQRT:
=====
IT WILL RETRUN SQRT ROOT VALUE OF A NUMBER.
SYNTAX:
========
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():
=========
SYNTAX:
-------
ifNULL(colname,REPLACE VALUE)
EX:
===
WRITE A QUERY TO DISPLAY COMM COLUMN FROM EMP
AN REPLACE NULL VALUES WITH 0;
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:
======
THIS FUNCTION ROUND THE VALUE TO Lowest POSSIBLE VALUE
SYNTAX:
-------
FLOOR(NUM);
EX:
===
SELECT FLOOR(4.5),FLOOR(4.2),FLOOR(4.7);
O/P:- 4,4,4,
pow(numer,exponential):
======================
it will return power of an number.
select pow(3,2),pow(2,3);
o/p:- 9,
=======================================================
VIEWS IN SQL
=======================================================
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 time.
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 calculation and hide the complexity.
A table may expose a lot of data including sensitive data such as personal and
banking information.
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 information, which
should be accessible by the HR department only.
To expose general information such as first name, last name, and gender to the
General Administration (GA) department, you can create a view based on these
columns and grant the users of the GA department the view, not the entire table
employees .
TYPES OF VIEW:
==============
1)SIMPLE VIEW
2)COMPLEX VIEW
SIMPLE VIEW:
============
1) A VIEW IS CREATED BASED ON SINGLE TABLE.
SYNTAX:
========
CREATE OR REPLACE VIEW VIEWNAME AS SELECT * [SPECIFIC COLUMNS]
FROM TABLENAME;
EX:
===
CREATE A VIEW ON EMP TABLE IT CONTAINS THREE COLUMNS
EMPNO,ENAME,SAL
SOL:
====
CREATE or replace VIEW EMP_V1 AS SELECT EMPNO,ENAME,SAL FROM EMP;
ex:
====
select * from emp_v1;
or
to drop a view:
===============
drop view viewname;
COMPLEX VIEW:
=============
SYNTAX:
=======
EX:
===
CREATE COMPLEX VIEW TO STORE EQUI JOIN OUTPUT OF DEPT AND EMP TABLE.
SOL:
====
CREATE OR REPLACE VIEW EMP_DEPT_EQ AS
SELECT E.EMPNO,E.ENAME,E.SAL,D.DEPTNO,D.DNAME FROM
DEPT D JOIN EMP E ON (D.DEPTNO=E.DEPTNO);
Create or replace view v3 As select empno, ename, sal, deptno from emp with read
only;
ex:
insert into test_v12 values(7143,'RAJESH',5000,30) //valid
insert into test_v12 values(7323,'RAJESH',5000,10) //invalid
ALter a view:
--------------
Alter view viewName as select * from tableName;
ex:
-----
Alter view v1 as select empno,ename,job from emp;
Exercises:
----------
salesman
---------
create below table.
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:
--------
Sample table: customer
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 often 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 multiple value operators
such as the IN ,All or Any operator.
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 execution:
----------------------
select * from emp wher sal > 1600
Note:
-----
Subqueries are executed first and then parent query is executed by using the result
of sub query.
0/p=0;
Select * from emp where job = (select job from emp where ename = 'ALLEN') AND sal
= (select sal from emp where ename = 'ALLEN');
Note:
-----
The above query is three level query. Sub query can be nested upto 32 levels.
ALL
----
OR
ANY
----
OR
Note: we should use multiple row operators with multiple row subqueries.
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);
internally execution:
------------------------
select * from emp where sal > ANY(1600,1250,1250,2850);
*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);
Select * from emp where(job,sal) IN(select job, sal from emp where deptno = 30);
+-------+----------+----------+---------+--------+
| empno | ename | sal | job | deptno |
+-------+----------+----------+---------+--------+
| 1001 | John | 50000.00 | Manager | 10 |
| 1007 | Jennifer | 42000.00 | Analyst | 10 |
+-------+----------+----------+---------+--------+
Exercise:
---------
write a subquery to find second highest salary emp table.
sol:
----
select max(sal) from emp where sal < (select max(sal) from emp);
+-----------------------+
| second_highest_salary |
+-----------------------+
| 50000.00 |
+-----------------------+
Co-RELATED SUBQUERY:
--------------------
When subquery is executed in relation to parent query, it is called 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);
+-------+-------+----------+---------+--------+
| empno | ename | sal | job | deptno |
+-------+-------+----------+---------+--------+
| 1001 | John | 50000.00 | Manager | 10 |
| 1002 | Mary | 45000.00 | Analyst | 20 |
| 1006 | James | 55000.00 | Manager | 30 |
+-------+-------+----------+---------+--------+
Execution:
----------
The above example is a co−related subquery.
In co−related subquery, parent query is executed first and then subquery is
executed in relation to result of parent query(parenet table alias name).
SCALAR subquery:
---------------
when we use subquery in the select clause. It is called as Scalar subquery.
Scalar subquery are also called sub select.
Ex:
------
select dept.deptno, subquery1.total_amt from dept, ( select emp.deptno,
Sum(emp.sal) total_amt
from emp group by deptno) subquery1 WHERE subquery1.deptno = dept.deptno;
Exists:
------
In the previous section, 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 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 entire SQL
statement returns nothing.
SELECT "column_name1"
FROM "table_name1"
WHERE EXISTS
( SELECT *
FROM "table_name2"
WHERE [Condition] )
Example:
==================================================================
Exercises On Subqueries:
==================================================================
1. Write a query to display the employee name and sal for all
employees in the same department as Blake. Exclude Blake.
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;
+-------+-------+
| empno | ename |
+-------+-------+
| 1006 | James |
| 1008 | Blake |
| 1001 | John |
| 1002 | Mary |
+-------+-------+
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:
----
SELECT empno, ename FROM emp WHERE deptno IN ( SELECT deptno
FROM emp WHERE ename LIKE '%T%' );
+-------+--------+
| empno | ename |
+-------+--------+
| 1003 | Robert |
| 1006 | James |
+-------+--------+
4.Display the employee name, department number, and job title for all
employees whose department location is Dallas.
sol:
---
+-------+--------+---------+
| ename | deptno | job |
+-------+--------+---------+
| Mary | 20 | Analyst |
| Lisa | 20 | Clerk |
+-------+--------+---------+
select ename,deptno, job from emp where deptno=(select deptno from dept where
loc='Dallas')
5.Display the employee name and id of all employees who report to Charile.
select ename,sal from emp where mgr in (select empno from emp where ename='KING');
==============================================
dense_rank():
--------------
==============================================
This function assigns a rank to each row within a partition.
The ranks are assigned in a consecutive manner, if there two values are equal then
they will be assigned the same rank, and the next rank value will be one greater
than the previous rank assigned.
Based on each department you need assign DENSE rank using PARTITION BY:
----------------------------------------------------------------
SELECT empno, ename, sal,deptno ,
DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal) dens_rank
FROM emp;
Rank:
-----
This function assigns a rank to each row within a partition that has gaps.
In this case, ranks are assigned in a non-consecutive 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 distinct sal from (select empno,ename,sal,dense_rank() over (order by sal
desc) as dnk from emp) dnkemp
where dnkemp.dnk=2;
==========================================================
INDEXES:
========
========================================================
Index is a database object ,index is a pointer which
locates the phsyical data of a table.
TYPES OF INDEXES:
======================================
1)SIMPLE INDEX
2)COMPLEX INDEX OR COMPOSITE INDEX
SIMPLE INDEX:
=============
SYNTAX:
=======
EX:
===
Before Index created:
---------------------
create index:
--------------
CREATE INDEX i_hire_date ON employees(hire_date);
NOTE:
======
WE NEED TO CREATE INDEX ON COLUMNS,THAT COLUMNS
FREQUENTLY USED IN WHERE CLAUSE.
SYNTAX:
========
CREATE INDEX INDEXNAME ON TABLENAME(COL1,COL2...,COL32);
Ex:
---
Before Index created:
---------------------
SELECT * FROM employees WHERE first_name = 'Georgi'AND last_name = 'Facello';
create index:
-------------
3)Unique index:
----------------
Syntax:
--------
create unique index indexname on tablename(columns);
it will create the indexes on columns as well as it will create the unique
constraints on
columns(duplicates not allowed).
ex:
---
create unique index infy_fn_ln_uq on info_1(first_name,last_name);
Ex:
show index from emp from parul;
to drop index:
--------------
DROP INDEX index_name ON table_name
or
==========================================================
SET OPERATORS
==========================================================
UNION
UNIONALL
UNION:
======
THIS OPERATEOR UNION RETRIVES THE OUTPUT OF TWO QUERIES
AND IT REMOVES DUPLICATE RECORDS.
EX:
====
UNION ALL:
==========
NOTE:
=====
IT WILL DISPLAY ALL THE DUPLICATE RECORDS FROM TWO TABLES
so we use emulate
Variable:
=========
A variable allows a programmer to store data temporarily during the execution of
code.
syntax:
-------
set @variablename=initialize the value;
select @variablename;
Ex:
===
set @name='Sumit deshpade'; --declare and initialize the variable
+----------------+
| @name |
+----------------+
| Sumit deshpade |
+----------------+
1 row in set (0.01 sec)
Case- WHEN-END
===============
to check multiple conditions
syntax:
-------
case columnname
when condition then result
when conditon then result
[else]
end;
Ex:
----
mysql> select empno,ename,case sal
-> when 5000 then 'highest salary'
-> when 3000 then 'low salary'
-> else 'daily wages'
-> end as salary from emp;
select case
when count(salary)=0 then null
else salary
end
as SecondHighestSalary from (select salary,dense_rank() over (order by salary
desc) as
rnk from employee) re
where re.rnk=2
or
or
select max(salary)
as SecondHighestSalary from (select salary,dense_rank() over (order by salary
desc) as
rnk from employee) re
where re.rnk=2
=======================================================
if condition
=======================================================
syntax:
-------
if (expr1,exp2,exp3) --> if expr1 is true then it will return exp2,if not then it
exp3;
ex:
---
select if(10>5,'greater','lesser than 5')
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 operations 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 operations on a table.
Syntax:
-------
Following is the syntax of the MySQL LOCK TABLES Statement −
Syntax:
-------
Following is the syntax of the MySQL UNLOCK TABLES Statement −
UNLOCK TABLES;
Grant Privileges:
-----------------
GRANT ALL PRIVILEGES ON * . * TO 'new_user'@'localhost';
ex:
---
CREATE USER 'raj'@'localhost' IDENTIFIED BY 'raj';
ex:
----
drop user 'lucky'@'localhost' ;
Ex:
----
alter user 'sarath'@'localhost' account lock;
Ex:
---
alter user 'sarath'@'localhost' account unlock;
Procedures
=======================================================
We can invoke the procedures by using triggers, other procedures and applications
such as Java, Python, PHP, etc.
Stored procedure reduces the traffic between application and database server.
Because the application has to
send only the stored procedure's name and parameters instead of sending multiple
SQL statements.
syntax:
-------
IN: These types of parameters are assigned the values while calling the stored
procedure and
the value cannot be modified or overwritten inside the stored procedure but
only referenced and
used by the stored procedure.
OUT: These are the parameters that can be assigned the values and overridden in the
stored procedure
but cannot be referenced by it.
IN OUT: These types of parameters are assigned the values while calling the stored
procedure and
the value can be modified or overwritten inside the stored procedure as
well as
referenced and used by the stored procedure.
Ex:1
-----
Create a procedure to store select query to display the data from emp table.
sol:
===
Delimiter //
create procedure ex1()
begin
select * from emp;
end //
to call procedure:
===================
call ex1();
ex:
===
to drop procedure:
==================
drop procedure databasename.procedure_name
or
use database;
Ex2:
====
create a procedure named as ex2 and to store the query to display the emp records
where depnto 10,20 or 30 using in parameter
sol:
====
Delimiter //
create procedure ex2(in dno decimal)
begin
select * from emp where deptno=dno;
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 //
end //
delimiter ;
sol:
====
delimiter //
create procedure ex4(in eno int,out en varchar(15))
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 //
create procedure ex_sum(IN a int,IN b int,OUT c int)
begin
set c=a+b;
end //
delimiter ;
----------------
call ex_sum(10,30,@st)
select @st
Ex4:
-----
write a procedure to get ename of empno=7566 and display it.
sol:
----
delimiter //
end //
delimiter ;
---------------
call ex_en(7566,@vn);
select @vn
ex4:
====
create procedure named as ex4 to store max(sal) int to outparameter from emp
where deptno 10 or 20 or 30 using in,out paramter
sol:
----
delimiter //
end //
delimiter ;
to call procedure:
==================
call ex4(10,@tn);
select @tn;
call ex4(20,@tn);
select @tn;
call ex4(30,@tn);
select @tn;
Ex5:
----
create a procedure named as ex5 to store max(sal) from emp
where deptno 10 or 20 30 using INOUT parameter
sol:
----
Delimiter //
call ex5(@n);
select @n;
--------------
set @n=20
call ex5(@n);
select @n;
Ex6:
----
Create a procedure to declare local variable
initialize and display it.
sol:
---
delimiter //
create procedure ex6()
begin
declare a int;
declare b varchar(10); /*declaration of variables */
declare c float;
set a=10;
set b='welcome'; /*initialization variable using set keyword*/
set c=300;
delimiter ;
to call the procedure:
----------------------
call ex6();
conditional or control statement:
=================================
if:
---
if condition then
statement-1;
end if;
if-else:
--------
syntax:
-------
if condition then
statement-1;
else
statement-2;
end if;
Ex:
---
create a procedure to compare two integer variables
display which is greater using in parameter.
sol:
-----
delimiter //
create procedure ex7(in a int,in b int)
begin
if a > b then
set msg='a is greater than b';
else
set msg='b is greater than a';
end if;
select msg;
end //
delimiter ;
sol:
===
Delimiter //
create procedure ex7(in a int,in b int)
begin
declare msg varchar(30);
if a>b then
set msg='a is greater than b';
else
set msg='b is greater than a';
end if;
select msg;
end //
delimiter ;
to call procedure:
------------------
call ex7(10,5) ;
call ex7(1,5) ;
Ex:
---
if-else-if:
-----------
syntax:
-------
if condition then
statement-1;
elseif condition then
statement-2;
elseif condition then
statement-3;
else
statement-4;
end if;
ex:
---
create a procedure to compare three integer variables
display which is greater using in parameter and if-else-if.
sol:
---
Delimiter //
else
set msg='c is greater than a,b';
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:
=========
1)create a procedure named as ex9 to perform sum of two number
using in parameters.
sol:
----
delimiter //
set res=n1+n2;
select res;
end //
delimiter ;
to call procedure:
------------------
call ex_9(10,10);
sol:
----
delimiter //
set res=n1+n2;
end //
delimiter ;
to call procedure:
==================
call ex10(10,30,@rs);
select @rs;
Function:
---------
In MySQL, a function is a stored program that you can pass parameters into and then
return a value.
Just as you can create functions in other languages, you can create your own
functions in MySQL.
Syntax
-------
DETERMINISTIC
BEGIN
declaration_section
executable_section
return datatype;
END;
DELIMITER //
function_name
--------------
The name to assign to this function in MySQL.
parameter
----------
One or more parameters passed into the function. When creating a function,
all parameters are considered to be IN parameters (not OUT or INOUT parameters)
where the parameters can be referenced by the function but can not be overwritten
by the function.
return_datatype
----------------
The data type of the function's return value.
declaration_section
--------------------
The place in the function where you declare local variables.
executable_section
------------------
The place in the function where you enter the code for the function.
DETERMINISTIC:
--------------
it means the function will return the same values if the same arguments are
supplied to it.
to call function:
==================
Ex:
---
create a function named as addition which takes three parameters
and perform sum of three numbers and return it
sol:
----
delimiter //
create function addition(a int,b int,c int)
returns int
DETERMINISTIC
begin
return (a+b+c);
end //
delimiter ;
or
---
create table test1(a int,b int,c int);
insert into test1 values(10,30,50);
to drop function:
-----------------
drop function function_name;
note:
-----
function name should be userdefined name.
(Don't use predefined function names like string functions,date functions,number
functions etc).
Ex:
---
create a function which returns the max(sal) from emp table.
sol:
----
delimiter //
DETERMINISTIC
begin
return v_m;
end //
delimiter ;
Exercise:
---------
create a function to display welcome 'ename' from emp table
when pass a ename column it should print welcome smith...etc
sol:
====
delimiter //
DETERMINISTIC
begin
declare en varchar(20);
return en;
end //
delimiter ;
TRIGGERS:
=========
These DML (Data Manipulation Language) execution operations can be INSERT, DELETE,
UPDATE and triggers
can be called before or after these events.
A trigger is a set of actions that are run automatically when a specified change
operation
(SQL INSERT, UPDATE, or DELETE statement) is performed on a specified table.
Triggers are useful for tasks such as enforcing business rules, validating 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 alterations are done to the data
of a table.
Triggers are simply a SQL code to run before or just after any DML action events on
a particular table in a database.
Syntax
-------
CREATE
[DEFINER = user] TRIGGER trigger_name
trigger_time trigger_event
ON tbl_name
FOR EACH ROW
trigger_body
Parameters
------------
DEFINER clause:
---------------
Identifies the MySQL account that is used for access at trigger initiation time.
trigger_name:
-------------
The name of all triggers should be unique inside a schema.
trigger_time:
-------------
Defines the trigger action time which can be either before or after any row
affected.
trigger_event:
--------------
Specifies the type of operation to activate the trigger.
tbl_name:
---------
The table name should be of a permanent table not a temporary or a view table to
associate a trigger.
trigger_body:
-------------
It is used to display a statement when the trigger is fired.
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 insertion, updation and deletion
actions on a table.
Like if you have a table and 50 rows are inserted, updated or deleted, then
automatically the trigger
is also invoked for 50 times.
Statement-Level Trigger:
======================
This trigger is invoked only once for a transaction regardless of the number of
rows inserted, updated, or deleted.
note:
=====
Row-Level Trigger is supported in MySQL but not Statement-Level Trigger.
PSEUDO COLUMNS:
===============
full syntax:
============
delimiter //
{before/after}
begin
statment; or logic;
end //
delimiter //
Example:
========
1) create a table named as emp13(empno,ename,sal)
2) create a trigger before insert into emp13 covert the ename into capital letter.
3) perform multiple insert to check trigger is fired or not?
sol:
----
delimiter //
set New.ename=upper(New.ename);
end //
delimiter ;
3)
insert into emp13 values(101,'ramu',3000);
Example:
--------
1)create table emp14(empno int,ename varchar(10),sal decimal(10,2));
trigger:
--------
delimiter //
Example:
----------
write a trigger on emp15 table before insert into empno column append PU_ to
empno.
insert into emp15 values(5010,'smith',3000);
sol:
----
1)create table emp15(empno varchar(10),ename varchar(10),sal decimal);
2)
delimiter //
create trigger trg_emp_15
before insert on emp15
for each row
begin
set New.empno=concat('PU_',New.empno);
end //
delimiter ;
3)
insert into emp15 values('5010','smith',3000);
Exercise:
=========
1)create table studentdetails(sid int(4),sname varchar(10),m1 int(3),m2 int(3),m3
int(3),total int(5));
sol:
----
1) create table studentdetails(sid int(4),sname varchar(10),m1 int(3),m2 int(3),m3
int(3),total int(5));
2)
delimiter //
create trigger trg_sd
before insert on studentdetails
for each row
begin
set New.total=New.m1+New.m2+New.m3;
end //
delimiter ;
1 Rahul 60 60 70 190
execute insert
==============
mysql> insert into studentdetails (sid,sname,m1,m2,m3) values
-> (101,'rahul',60,70,80);
Query OK, 1 row affected (0.01 sec)
Example:
--------
bank audting
sol:
create table emp_base(empno int(4),ename varchar(10),sal int(8));
sol:
create table emp_base_update_bkup(empno int(4),n_ename varchar(10),
o_ename varchar(10),n_sal int(8),o_sal int(8),opera
varchar(10),ef_ondate date);
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:
--------
mysql> update emp_base set ename='martin',sal=5000 where empno=1001;
Exercise:
--=======
1)create a table emp_base(empno,ename,sal)
3) create a trigger before delete a record from emp_base,the deleted record should
backup into emp_base_delete table.
sol:
----
delimiter //
end //
delimiter ;
Execute:
========
mysql> delete from emp_base where empno=1005;
Query OK, 1 row affected (0.01 sec)
mysql>
to drop a trigger:
==================
drop trigger trigger_name;
or
show triggers;
NOW()
------
This date function returns the current date and time of the running server
instance.
DATE()
--------
This date function extracts and returns the date part from the given DATETIME
value.
CURDATE()
----------
It is a simple date function that fetches the current date of the system running
the MySQL instance.
DATE_FORMAT():
--------------
Sometimes 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.
Therefore, you can use the DATEDIFF() function.
Note:
-----
The DATEDIFF() function 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,
DATE_ADD('2019-08-04', INTERVAL 1 DAY) 'Added 1 day',
DATE_ADD('2019-08-04', INTERVAL 1 WEEK) 'Added 1 week',
DATE_ADD('2019-08-04', INTERVAL 1 MONTH) 'Added 1 month',
DATE_ADD('2019-08-04', INTERVAL 1 YEAR) 'Added 1 year';
EXTRACT():
----------
The EXTRACT function will extract a part of a date from a specified date value.
Specifier Description
--- -----------
%a Abbreviated weekday name (Sun..Sat)
%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
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 multiple times 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 generating 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 times that a subquery needs to be executed
WITAH cte_name(
SELECT column1, column2, ...
FROM table_name
WHERE condition
)
SELECT *
FROM cte_name;
Syntax:multiple CTEs within the same query, by separating each CTE definition with
a comma. For example:
WITH cte1 AS (
SELECT column1, column2, ...
FROM table1
WHERE condition1
),
cte2 AS (
SELECT column3, column4, ...
FROM table2
WHERE condition2
)
SELECT *
FROM cte1
JOIN cte2 ON cte1.column1 = cte2.column3;
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 selecting 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:
The following commands can be used to insert data into the table:
Query:
-------
WITH sales_last_30_days AS (
SELECT product_name, SUM(revenue) AS total_revenue
FROM sales
WHERE sales_date BETWEEN '2023-03-10' AND '2023-04-09'
GROUP BY product_name
),
sales_previous_30_days AS (
SELECT product_name, SUM(revenue) AS total_revenue
FROM sales
WHERE sales_date BETWEEN '2023-02-08' AND '2023-03-09'
GROUP BY product_name
)
SELECT
s.product_name,
s.total_revenue,
(s.total_revenue - p.total_revenue) / p.total_revenue * 100 AS revenue_change
FROM sales_last_30_days s
JOIN sales_previous_30_days p ON s.product_name = p.product_name;
Explanation:
------------
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",
"quantity", 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.
Reuse code:
----------
CTEs can be used to create modular SQL code that can be reused across multiple
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.
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 identify and fix errors.
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 operations 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 operations on a table.
Syntax:
-------
Following is the syntax of the MySQL LOCK TABLES Statement −
Syntax:
-------
Following is the syntax of the MySQL UNLOCK TABLES Statement −
UNLOCK TABLES;
Grant Privileges:
-----------------
GRANT ALL PRIVILEGES ON * . * TO 'new_user'@'localhost';
ex:
---
CREATE USER 'raj'@'localhost' IDENTIFIED BY 'raj';
ex:
----
drop user 'lucky'@'localhost' ;
Ex:
----
alter user 'sarath'@'localhost' account lock;
Ex:
---
alter user 'sarath'@'localhost' account unlock;