Notes
Notes
DBMS vs RDBMS
=============
-DBMS (e.g. MS Excel, FoxPro, etc)
------
a. Field
b. Record
c. File
Infoemix
* Fastes in terms of processing speed(but should done at assembly level)
Oracle
* Most popular RDBMS because the programming is very easy
* product of Oracle Corporation
* #1 largest overall s/w company in the world
* #1 largest database s/w company in the world
* 10/10 of the top 10 companies in the world use Oracle
* largest database in the world is amazon.com (uses Oracle)
* largest Distributed database in the world is yahoo.com (uses Oracle)
* > 90% of Fortune 500 companies use Oracle
* works on 113 OS
* 63% of world commercial database market in the Client-server environment
* 86% of world commercial database market in the Internet environment
Sybase
* going down
* recently acquired by SAP
MS SQL Server
* good RDBMS from Microsoft(Limitation : Only works with Windows OS)
* 16% of world commercial database market
DB2
CICS
TELON
IDMS
MS Access
Paradox
Vatcom SQL
MySQL
-----
* founded in 1995 by a Swedish company
* it's name is a combination of "My",co-founder Michael Widenius
daughter, and "SQL"
* MySQL is an open-source RDBMS
* most widely used open-source RDBMS
* part of the widely used "LAMP" open-source web application software stack
(and others "AMP"stacks)
* free-software open-source projects thst require a RDBMS use MySQL
* e.g. WordPress, Facebook, Google(through not for searches)
Joomla, Twitter, Flickr, Instagram, YouTube, etc.
* Occupies 42% of world open-source database market
* Sun Microsystems acquired MySQL in 2008
* Oracle acquired Sun Microsystems in 2010
MySQL
-----
SQL
* Structured Query Language
* commonly pronounced as "Sequel"
* create, Drop, Alter
Insert, Update, Delete
Grant, Revoke, Select
* conforms to ANSI standards (e.g. 1 char=1 byte, datatypes)
* conforms to ISO standards for QA
* common for all RDBMS
* not a product of MySQL
* initially founded by IBM (1975-1977)
* now controlled by ANSI (therefore SQL is common for all RDBMS)
* in 2005, the source code of SQL rewritten using Java (100%)
MySQL Workbench
* MySQL client s/w
* used for running SQL commands, MySQL commands, and MySQL-PL programs
* interface with database
* GUI based
MySQL -PL
* MySQL Programming Language
* Programming language from MySQL
* used for database programming
e.g. HRA_CALC, TAX_CALC, ATTENDANCE_CALS, etc.
MySQL Connectors
MySQL for Excel
MySQL Notifier
MySQL Enterprise Backup
MySQL Enterprise High Availability
MySQL Enterprise Encryption
MySQL Enterprise Monitor
MySQL Query Analyzer
etc.
MySQL - SQL
DML(Upsert, Merge)
**Varchar**
(allows any character)(max 65,535 character)(64Kb - 1)
(no default width)(width has to be specified)(variable length)
(conserve on HDD space)(searching and retrieval will be slow)
(e.g. NAME, ADDRESS, CITY, etc.)
Float
Double
--------------------------------------------
Fixed-point Types:-
Decimal
* stores Double as a string
e.g. "653.7"
* used when it is necessary to preserve the exact precision
e.g monetary data
* max number of digits is 65
Boolean
--------
* True and False evaluate to 1 and 0 respectively
* e.g. Marital_Status boolean
* can insert True, False, 1, or 0
Date
* 1st Jan 1000 AD oto 31st Dec 9999 AD
* 'YYYY-MM-DD' isthe default date format in MySQL
* e.g.
'2021-11-19'
'21-11-19'
* year values from 70-99 are converted to 1970 to 1999
* year values from 00-69 are converted to 2000 to 2069
'47-08-15'
* date1 - date2 -> returns the number of days between the 2 dates
* max 4,096 columns per table provided row size<= 65,535 bytes
* no upper limit on number of rows per table provided but the max table size is
64TB
INSERT
------
insert into emp
values('1','Amit',5000,'Mumbai','1990-01-04'); <----Easier to write
'1990-01-04' -> 'YYYY-MM-DD'
'1990-01-04' -> 'YY-MM-DD'
* metacharacter
(all columns)
To restrict columns:-
the order of column in SELECT statement, will determine the position of column in
the output (to be written)
WHERE clause:-
---------------
Relational Operators:-
1. >
2. >=
3. <
4. <=
5. != or <>
6. =
Logical Operator:-
NOT
AND
OR
In MySQL:-
Queries are case-insensitive (More user-friendly)(Less secure)
In Oracle:-
Queries are case-sensitive (Less user-friendly)(More secure)
* Computed columns, e.g. sal*12, are never stored in the table (it's a wastage
of HDD space);
as and when require you can SELECT sal*12 to see yearly SAl
Arithmetic Operators:-
1. ( )
2. /
3. *
4. +
5. -
Alias
select ename, sal, sal*12 as annual from emp; -> Column should createe with
Capital Letters
select ename, sal, sal*12 as "annual" from emp; -> Column should createe with
small Letters
select ename, sal, sal*12 as "Annual Salary" from emp; -> Column should
createe with given Letters
select ename, sal, sal*12 as "ANNUAL" from emp; -> best practice
* when you use DISTINCT, sorting takes place internally in the server RAM
root/cdac
* has DBA privileges
* createe users, assign permission, take backups, performance
monitoring, performance tuning, etc.
mysql.sys
* most important user in MySQL
* owner of database
* startup database, shutdown database
MySQL Workbench
1. To createe a new connection for 'root' user:-
username:- root
show databases;
to connect to a database:-
use <databasename>;
use mysql;
or
show databases;
createe user <username> identified by <password>;
@'%' -> this user will be able to connect to the database from any computer
To grant permission:-
Select the username you createed from the user AccountList on LHS
ok - click
click on Apply
Exit from MySQL Workbench and createe a New connection for pgdac1 user
DATE : 22/11/2021
------------------
ORDER BY clause
* used for sorting
* sorting takes place in server RAM;
ORDER BY clause
* to make the output more presentable
select...................
order by country, state, city;
any==logical OR
UPDATE
------
update emp
set sal=10000
where empno = 1;
(for empno 1 we set sal = 10000)
update emp
set sal=sal + sal*0.4
where empno = 1;
(for empno 1 we set sal = sal+sal*0.4)
update emp
set sal=10000, city = 'Nasik'
where empno = 1;
(for empno 1 we set sal = 10000)
update emp
set sal=10000
where city = Mumbai;
(for employee who having there city as Mumbai we set sal = 10000)
update emp
set sal=10000, city='Nasik'
where city = Mumbai;
(for employee who having there city as Mumbai we set sal = 10000)
update emp
set sal=10000
(for all employee we set sal = 10000)
DELETE
-------
drop table emp; (Delete the whole table having name emp)
***********************************************************************************
TRANSACTION PROCESSING
***********************************************************************************
* commite will save all the DML changes since the last committed state
* when the user issues a commit, it is known as end of transaction
* Commit will make the Transaction permanent
commit work;
or
commit;
* Rollback will undo all the DML changes since the last committed state
* only the DML commands are affected by Rollback and commit
* any DDL command, it automatically commits
* when you exit from SQL*Plus (Oracle client s/w), it automatically commits
* any kind of power failure, network failure, system failure, PC rebbot, window
close,
end of task, etc.; in all such cases your last uncommitted Transaction, it
automatically
Rolled back in MySQL and Oracle
update emp set sal = 10000;
* UPDATE and DELETE commands without WHERE clause will not be allowed
in MySQL Workbench
Click on Edit (menu at the top) -> Preferences -> SQL Editor -> Safe Updates
(Checkbox at the bottom) -> uncheck it -> click on OK
DATE : 23/11/2021
------------------
Read and Write Consistency:-
-----------------------------
in a multi-user environment, when you Select from a table, you can view only
the committed data of other users plus (union) the changes made by you.
There is a separate NEW TABLE for every user (It's private to each user)
* when you Update or Delete a row, that row is automatically locked for other
users
* ROW LOCKING IS AUTOMATIC IN MySQL AND ORACLE
* when you UPDATE or DELETE a row, that row becomes READ_ONLY for other users
* other users can SELECT from that tablr; they will view the old data before
your changes
* other users can INSERT rows into that table
* other users can UPDATE/DELETE "other" rows from that table
* no other user can UPDATE or DELETE your locked row, till you have issued a
Rollback or Commit
* Locks are automatically released when you rollback or commit
PESTISTIC ROW LOCKING -> you manually lock the rows in advance BEFORE issuing
UPDATE or DELETE
* To lock the rows manually, you have to use SELECT statement with the FOR
UPDATE clause
e.g.
Click on Query (menu at the top) -> New tab to current server -> Click on it
To try out Row locking in MySQL Workbench, if you get stuck in the Request
Queue, to abort the operation:-
Functions
---------
Character Functions
-------------------
1. Routine that Returns a value (return statement)
2. You can parameters/arguments to a function
3. Functions can be overloaded
In Oracle:-
concat (str1,str2)
In MySQL:-
concat(str1,str2,str3,....,strn)
select concat(fname,' ',lname) from emp;
Output:-
Arun Purun
Tarun Arun
Sirun Kirun
Nutan Purun
UPPER
-----
ARUN
TARUN
SIRUN
NUTAN
In Oracle:-
arun
tarun
sirun
nutan
In Oracle:-
Arun
Tarun
Sirun
Nutan
Uses:-
a. Right justification
b. Billing Receipt
c. Cheque printing
Uses:-
a. Left justification of numeric data
b. to convert varchar to char (convert variable length to fixed-length)
c. Billing Receipt
d. Cheque printing
Arun Purun
Tarun Arun
Sirun Kirun
Nutan Purun
Uses:-
a. Left justification
Output:-
trim blank spaces from right hand side
Uses:-
a. to convert char to varchar (convert fixed-length length to variable)
DATE : 24/11/2021
------------------
Number Functions
=================
sin(x)
cos(x)
tan(x)
ln(y)
log(n,m)
Date Function
-------------
1. 'YYYY/MM/DD'
2. '1000/01/01' to '9999/12/31'
3. date1-date2
4. internally date is stored as fixed-length number
(number of days since 1st Jan 1000 AD)
5. 7 Bytes
6. date and time is stored together
7. default value for time is 12 am midnight
8. 1970 is the cut-off year
select sysdate() from dual; <-returns server data and time when the statement
executed
+---------------------+
| sysdate() |
+---------------------+
| 2021-11-24 15:17:08 |
+---------------------+
'2021-11-24 15:15:16'
* returns the DB server data and time
select now() from dual; <-returns server data and time when the statement
began to executed
+---------------------+
| now() |
+---------------------+
| 2021-11-24 15:18:32 |
+---------------------+
* independent of datatype
ifnull(comm,0)
ifnull(comm,100)
ifnull(city,'Mumbai')
ifnull(orderdate,'2021-04-01')
select greatest(sal,3000) from emp;
Uses:-
a. used to set a lower limit on some value
e. g. Bonus = 10% sal, Min Bonus=300
greatest(num1,bum2,num3)
greatest('str','str2','str3')
greatest(date1,date2,date3)
set x=greatest(a,b,c,d);
Case Expression:-
select case
when deptno =10 then 'Training'
when deptno =20 then 'Exports'
when deptno =30 then 'Sales'
else 'Others'
end "DEPTNAME"
from emp;
DEPTNAME
--------
Training
Training
Exports
Sales
Others
Uses:-
a. Encoding and Decoding
select case
when deptno =10 then 'Ten'
when deptno =20 then 'Twenty'
when deptno =30 then 'Thirty'
end "DEPTNAME"
from emp;
DEPTNAME
--------
Ten
Ten
Twenty
Thirty
Environment Functions:-
**********************************************************************************
EMP
EMPNO ENAME SAL DEPTNO JOB MGR
1 Arun 8000 1 M 4
2 ALI 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M
5 Thomas 8000 2 C 4
M=MANAGER
C=CLERK
Group/Aggregate function
select sum(sal) from emp; <- NULL VALUES ARE NOT COUNTED BY
GROUP Function
27000
select sum(ifnull(sal,0)) from emp; <- Output is same as above but it's
(if null) not required
27000
DATE-25/11/2021
---------------
DEPTNO SUM(SAL)
------ --------
1 18000
2 17000
Rule #1
Besides the group function, whichever column is present in SELECT clause, it has
to be present in GROUP BY clause
Rule #2
Whichever column is present in GROUP BY clause, iy may be or may not be presentin
select
clause
select...................
group by country, state, city;
* if you have large number of column in GROUP BY clause, then the SELECT
statement will be slow (that much sorting has to take place)
select job,
select ...........
group by city, country, district, state; <- Slow
select ...........
group by country, state, district, city; <- fast
In Oracle:-
select max(sum(sal)) from emp group by deptno; <- NESTING OF GROUP FUNCTION IS
ALLOWED ONLY
IN ORACLE RDBMS; NOT
SUPPORTED IN
ANY OTHER RDBMS
In MySQL:-
**********************************************************************************
JOINS
-----
EMP
EMPNO ENAME SAL DEPTNO JOB MGR
1 Arun 8000 1 M 4
2 ALI 7000 1 C 1
3 Kirun 3000 1 C 1
4 Jack 9000 2 M
5 Thomas 8000 2 C 4
DEPT
DEPTNO DNAME LOC
1. TRN MUM
2. EXP DEL
3. MKTG CAL
create table
DATA REDUNDANCY -> UNNECESSARY DUPLICATION OD DATA
* all the data is not stored in one table; data is stored in multiple
tables
* to view/combine the columns of 2 or more tables, then you will have to write
a JOIN
dept -> driving table
emp -> driven table
DNAME ENAME
------ ------
TRN ARUN
TRN ALI
TRN KIRUN
EXP JACK
EXP THOMAS
* IN ORDER FOR YOUR JOIN TO WORK FASTER, PREFERABLY THE DRIVING TABLE
SHOULD BE TABLE WITH LESSER NUMBER OF ROWS
select dname, loc, ename, job, sal from emp,dept where dept.deptno=emp.deptno order
by 1;
select * from emp,dept where dept.deptno=emp.deptno order by 1;
* The common column that is present in both the tables, that column's
name need not be the same in both the tables;
select dname, loc, ename, job, sal from emp, dept where dept.x=emp.y order by 1;
select snum, onum, amt, odate, cnum, cname, city, rating from orders,customers
where orders.cnum=customers.cnum order by 1;
ERROR 1052 (23000): Column 'snum' in field list is ambiguous
DEPTNO SUM(SAL)
------ -------
1 18000
2 17000
select dname, sum(sal) from emp, dept where dept.deptno=emp.deptno group by name;
DNAME SUM(SAL)
----- --------
select upper(dname), sum(sal) from emp, dept where dept.deptno=emp.deptno group by
upper(dname) having sum(sal)>10000 order by 1;
Types of JOINS(5):-
1. Equijoin
Join based on equality condition
shows matching rows of both the tables
Uses:-
a. view the columns of both the tables
e.g. DNAME and ENAME, CUSTONAME and ORDER_DETAILS, etc.
this is the most frequently used join (>90%)
and hence it is also known as Natural join
2. Inequijoin (Non-Equijoin)
join based on inequality condition
shows non-matching rows of both the tables
Uses:-
a.
3. Outerjoin
join with (+) sign
shows matching rows of both the tables and non-matching rows of "OUTER" table
OUTER table -> table which is on outer side of (+) sign
OUTER table -> table which is on opposite side of (+) sign
a. Half outerjoin ((+) sign is on any one side, i.e. LHS or RHS )
i. Right ii. Left
b. Full outerjoin
Uses:-
Master -Detail child (Parent-child report)
select dname, ename from emp, dept where dept.deptno = emp.deptno (+);
DNAME ENAME
----- -----
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
select dname, ename from emp, dept where dept.deptno (+) = emp.deptno ;
DNAME ENAME
----- -----
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
null Scott
FULL outerjoin
select dname, ename from emp, dept where dept.deptno = emp.deptno (+);
union
select dname, ename from emp, dept where dept.deptno (+) = emp.deptno ;
DNAME ENAME
----- -----
TRN Arun
TRN Ali
TRN Kirun
EXP Jack
EXP Thomas
MKTG null
null Scott
select dname, ename from emp full outer join dept on (dept.deptno = emp.deptno);
--------------------------------------------------------------------------------
select dname, ename from emp right outer join dept on (dept.deptno = emp.deptno);
--------------------------------------------------------------------------------
select dname, ename from emp left outer join dept on (dept.deptno = emp.deptno);
--------------------------------------------------------------------------------
select dname, ename from emp right outer join dept on (dept.deptno = emp.deptno);
union
select dname, ename from emp left outer join dept on (dept.deptno = emp.deptno);
---------------------------------------------------------------------------------
INNER JOIN
* by default every join is an Inner join putting a (+) sign is what makes it in
Outerjoin
1. Equijoin
2. Inequijoin
3. Outerjoin
4. Cartesian join
* join without a WHERE condition
* every row of driving table is combined with each and every row of
driven table
* cross product of two tables hence also known as Cross join
Uses:-
select dname, ename from emp, dept; <- FAST (lesser the input/output between
the
server HDD and
server RAM, the faster
it will execute)
select dname, ename from emp, dept; <- SLOW (more the input/output between
the
server HDD and
server RAM, the slower
it will execute)
DNAME ENAME
----- -----
TRN Arun
TRN Ali
TRN Kirun
TRN Jack
TRN Thomas
EXP Arun
EXP Ali
EXP Kirun
EXP Jack
EXP Thomas
MKTG Arun
MKTG Ali
MKTG Kirun
MKTG Jack
MKTG Thomas
5. Self join
mysql> select a.ename, b.ename from emp b, emp a where a.mgr = b.empno;
+--------+-------+
| ename | ename |
+--------+-------+
| Arun | Jack |
| Ali | Arun |
| Kirun | Arun |
| Thomas | Jack |
+--------+-------+
* Cartesian join is the fastest join because there is no WHERE clause, and
hence
no searching in involved
+--------+-------+------+
| DEPTNO | DNAME | LOC |
+--------+-------+------+
| 1 | TRN | MUM |
| 2 | EXP | DEL |
| 3 | MKTG | CAL |
+--------+-------+------+
+--------+-------+
| DEPTNO | DHEAD |
+--------+-------+
| 1 | Arun |
| 2 | Jack |
+--------+-------+
select dname, ename, dhead from emp, dept, depthead where depthead.deptno =
dept.deptno
and dept.deptno=emp.deptno;
+-------+--------+-------+
| dname | ename | dhead |
+-------+--------+-------+
| TRN | Arun | Arun |
| TRN | Ali | Arun |
| TRN | Kirun | Arun |
| EXP | Jack | Jack |
| EXP | Thomas | Jack |
+-------+--------+-------+
Types of Relationships:-
***********************************************************************************
**
Sub-queries (V.V.Imp)
select ename from emp where sal = (select min(sal) from emp);
+-------+
| ename |
+-------+
| Kirun |
+-------+
select ename from emp where sal = (select min(sal) from emp where deptno =
(select...));
select max(sal) from emp where sal < (select max(sal) from emp);
+----------+
| max(sal) |
+----------+
| 8000 |
+----------+
select ename, max(sal) from emp where sal < (select max(sal) from emp);
+-------+----------+
| ename | max(sal) |
+-------+----------+
| Arun | 8000 |
+-------+----------+
select * from emp where deptno = (select deptno from emp where ename='Thomas');
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 4 | Jack | 9000 | 2 | M | NULL |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
-----------------------------------------------------------------------------------
----
select * from emp where job = (select job from emp where ename='Arun');
+-------+-------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+-------+------+--------+------+------+
| 1 | Arun | 8000 | 1 | M | 4 |
| 4 | Jack | 9000 | 2 | M | NULL |
+-------+-------+------+--------+------+------+
select * from emp where job = (select job from emp where ename='Kirun');
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 2 | Ali | 7000 | 1 | C | 1 |
| 3 | Kirun | 3000 | 1 | C | 1 |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
In Oracle:-
delete from emp where deptno=(select deptno from emp where ename = 'Thomas');
update emp set sal = 10000 where job = (select job from emp where ename = 'Kirun');
In MySQL, you cannot UPDATE or DELETE from a table from which are currently
SELECTing:-
Solution for MySQL:-
delete from emp where deptno = (select tempp.deptno from (select deptno from emp
where ename = 'Thomas') as tempp);
update emp set sal = 10000 where job = (select tempp.job from(select job from
emp where ename = 'Kirun') as tempp);
Multi-row sub-queries:-
* Sub-query returns multiple rows
Display all the rows that are receving a SAL equal to any of the Managers:-
select * from emp where sal =any (select sal from emp where job = 'M');
ANY=LOGICAL OR
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 1 | Arun | 8000 | 1 | M | 4 |
| 4 | Jack | 9000 | 2 | M | NULL |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
select * from emp where sal in (select sal from emp where job = 'M');
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 1 | Arun | 8000 | 1 | M | 4 |
| 4 | Jack | 9000 | 2 | M | NULL |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
select * from emp where sal in (select min(sal) from emp where job = 'M');
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 1 | Arun | 8000 | 1 | M | 4 |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
select * from emp where sal >= (select min(sal) from emp where job = 'M');
+-------+--------+------+--------+------+------+
| EMPNO | ENAME | SAL | DEPTNO | JOB | MGR |
+-------+--------+------+--------+------+------+
| 1 | Arun | 8000 | 1 | M | 4 |
| 4 | Jack | 9000 | 2 | M | NULL |
| 5 | Thomas | 8000 | 2 | C | 4 |
+-------+--------+------+--------+------+------+
-----------------------------------------------------------------------------------
----
Assumption 3rd row SAL is 13000:-
select sal from emp where sal > (select sal from emp where job = 'M');
select sal from emp where sal > all (select sal from emp where job = 'M');
select sal from emp where sal > all (select max(sal) from emp where job = 'M'); <-
FASTER
-----------------------------------------------------------------------------------
----
Using sub-query in the HAVING clause:-
In Oracle:-
DEPTNO SUM(SAL)
------ --------
1 18000
2 17000
SUM(SAL)
--------
18000
17000
MAX(SUM(SAL))
-------------
18000
DEPTNO SUM(SAL)
------ --------
1 18000
DNAME SUM(SAL)
------ --------
TRN 18000
In MySQL:-
----------
SUM(SAL)
--------
18000
17000
select max(sum_sal) from (select sum(sal) sum_sum from emp group by deptno) as
tempp;
max(sum_sal)
------------
18000
DEPTNO SUM(SAL)
------ --------
1 18000
select dname, sum(sal) from emp, dept where dept.deptno=emp.deptno group by dname
having sum(sal) = (select max(sun_sal) from (select sum(sal) sum_sal from emp)
group by deptno)as tempp);
DATE-27/11/2021
---------------
Correlated Sub-query (using the EXISTS operator)
* THIS IS THE EXCEPTION WHEN SUB-QUERY IS FASTER THAN JOIN
* EXISTS in a Special Operator
Soln #1:-
select dname from dept where deptno =any (select distinct deptno from emp);
+-------+
| dname |
+-------+
| TRN |
| EXP |
+-------+
select dname from dept where deptno in (select distinct deptno from emp);
+-------+
| dname |
+-------+
| TRN |
| EXP |
+-------+
select dname from dept where deptno not in (select distinct deptno from emp);
+-------+
| dname |
+-------+
| MKTG |
+-------+
Soln #2:-
* if you have a join, along with distinct to make it work faster, use
Correlated
sub-query (use the EXISTS operator)
Soln #3:-
select dname from dept where exists (select deptno from emp where
dept.deptno=emp.deptno);
+-------+
| dname |
+-------+
| TRN |
| EXP |
+-------+
select dname from dept where not exists (select deptno from emp where
dept.deptno=emp.deptno);
+-------+
| dname |
+-------+
| MKTG |
+-------+
Set Operators
-------------
* based on set theory
EMP1 EMP2
EMPNO ENAME EMPNO ENAME
1 A 1 A
2 B 2 B
3 C 4 D
5 E
EMPNO ENAME
----- ------
1 A
2 B
3 C
4 D
5 E
union -> will combine the output of both the SELECT statements and it will suppress
the
duplicates
EMP1 EMP2
EMPNO1 ENAME EMPNO2 ENAME
1 A 1 A
2 B 2 B
3 C 4 D
5 E
EMPNO1 ENAME
----- ------
1 A
2 B
3 C
4 D
5 E
EMPNO1 ENAME
----- ------
1 A
1 A
2 B
2 B
3 C
4 D
5 E
EMPNO1 ENAME
----- ------
1 A
2 B
intersect -> will return what is common in both the SELECT statement and the
duplicate
are suppressed
EMPNO1 ENAME
----- ------
3 C
minus -> will return what is present in the 1st SELECT statement and not present in
the 2nd
SELECT statement, and the duplicates are suppressed
* max upto 255 SELECT statements (this limit of SQL can be exceed using Views)
JOB
----
PRESEDENT
JOB
----
PRESEDENT
* Multiple SELECT statement with set operators; brackets for changing the
precedence
-->> not supported by MySQL
Pseudo Columns
* fake columns (virtual columns)
NO two rows of any table in the entire DB servers HD can have the same ROWID
ROWID words as an Unique Identifier for every row in the database
When you UPDATE a row, if the row length is increasing, then the ROWID MAY change
EMP
EMPNO ENAME SAL
1 Scott 3000
2 King 5000
* rename a table
* add a column
* drop a column
Indirectly:-
* reduced width of column
In MySQL:-
alter table tableName modify columName datatype(size);
alter table emp modify ename varchar(15); <- data will get truncated
In Oracle:-
alter table emp modify ename varchar(15); <- ERROR
* you can reduced the width provided the contents are null
insert into emp select * from emo2 where where deptno = 10;
Method #1:-
Method #2:-
truncate table emp_struct; <- truncate will delete all the rows and commit
also
Method #3:-
#DELETE
* Comman for all RDBMS
* DML command & will delete the rows
* Requires commit
* Rollback possible
* DELETE from emp where
#TRUNCATE
* Extra command MySQL & Oracle
* DDL command
* Will delete ALL the rows & commit
* Auto commit
* Rollback not possible
* Truncate table emp
* Where condition not possible
* rename a column
create table emp_copy as select empno, ename, sal salary from emp;
rename a column
#DELETE
-------
* DELETE triggers on table will execute
#TRUNCATE
* DELETE
When you truncate EMP table, if you want to retain the rows of deptno 10:-
create table emp_copy as select * from where deptno = 10;
DATE-28/11/2021
---------------
INDEXES
-------
EMP
EMPNO ENAME SAL DEPTNO
5 A 5000 1
4 A 6000 1
1 C 7000 1
2 D 9000 1
3 E 8000 2
* present in all RDBMS, all DBMS, and some progamming language also
* to speed up the searching operations (for faster access)
* to speed up the SELECT statement with a WHERE clause
* indexes are automatically invoked by MySQL and when required
* indexes are automatically updated by MySQL for all your DML operations
* no upper limit on the number of indexes per table
* larger the number of indexes, the slower would be the DML operations
* you cannot index text and blob
* duplicate value are not stored in an index
* null values are not stored in an index
* if you have 2 or more INDEPENDENT columns in the WHERE clause then create;
seperate indexes for each column; MySQL will use both the indexes as and when
required
COMPOSITE INDEX -> combine 2 or more INTER-DEPENDENNT columns in the single index
INDEX KEY -> Column or set of column on whose basis the index has been created
use information_schema;
select * from statistics;
Types of Indexes:-
1. Normal Index
2. Unique Index
3. Clusterd Index etc.
Privileges:-
------------
Grant and Revoke
samdehadrai@yahoo.com
contact@sameerdehadrai.com
Mob : 9820134740
DATE-29/11/2021
---------------+
EMP
EMPNO ENAME SAL DEPTNO
1 A 5000 1
2 B 6000 1
3 C 7000 1
4 D 9000 2
5 E 8000 2
CONSTRAINTS
------------
* limitations/restriction imposed on a table
create table emp(empno char(4) primary key, ename varchar(25), sal float, deptno
int);
mysql> insert into emp values ('5','F',5000,2); <- ERROR
* all constraint are at server level (you may perform the DML operations using
any
front-end s/w, the constraints will always be valid)
* internally a constraint is a MySQL created function; it performs the
validations
NOT NULL
---------
create table emp(empno char(4), ename varchar(25) not null, sal float not null,
deptno int);
UNIQUE
-------
* duplicate values are not allowed (similar to primary key)
* null values are allowed (you can specify any number of null values)
* text and blob cannot be unique
* unique index is created automatically
* you can combine upto 32 columns in a composite unique
* YOU CAN HAVE ANY NUMBER OF UNIQUE CONSTRAINTS
create table emp(empno char(4), ename varchar(25) not null, sal float not null,
deptno int, mob_no char(15) unique, <- Column level constraint
unique(deptno,empno)); <- table level constraint
* column level constraint can be specified at table level (at the end of the
structure
), but a table level composite constraint can never be specified at column level
* column level constraint can be specified at table level (at the end of the
structure)
except for the not null constraint, which is always a column level constraint, and
therefore
the syntax will not support specifying it at table level (at the end of structure)
EMP DEPT
=== =====
EMPNO ENAME SAL DEPTNO MGR DEPTNO DNAME LOC
----- ----- --- ------ --- ------ ----- ---
1 A 5000 1 1 1 TRN
MUM
2 B 6000 1 1 2 EXP
DEL
3 C 7000 1 1 3 MKTG CAL
4 D 9000 2 2
5 E 8000 2 2
6 F 9000 2 2
FOREING KEY (Foreign column) (column that has been derived from elsewhere)
* Column or set of columns that references a columnor set of columns of some
table
* Foreign key constraint is specified on child column (not the parent column)
* parent column has to be Primary key or UNIQUE
(this is pre-requisite for Foreign key)
* Foreign key (child column) will allow duplicate values (unless specified
otherwise)
* text and blob cannot be Foreign key
* index for the child column is not created automatically over here
(if you want the index then you will have to create it manually)
* Foreign key (child column) may reference column of same table
(known as Self-reference)
create table dept(deptno int primary key, dname varchar(15), loc varchar(10));
create table emp(empno char(4) primary key, ename varchar(25), sal float, deptno
int,
mgr char(4), constraint fk_emp_deptno foreing key(deptno), references deptno,
constraint fk_emp_mgr foreing key(mgr) reference emp(empno));
* you can delete the parent row provided child rows don't exist
create table emp(empno char(4) primary key, ename varchar(25), sal float, deptno
int,
mgr char(4), constraint fk_emp_deptno foreing key(deptno) on delete cascade,
references deptno,
constraint fk_emp_mgr foreing key(mgr) reference emp(empno));
ON DELETE CASCADE -> if you delete the parent row then MySQL will automatically
delete
the child rows also delete the child rows also
ON UPDATE CASCADE -> if you update the parent column then MySQL will update the
child rows also
* avoid on delete cascade in the event of self-referencing, you may delete more
rows than expected
* it's safer to use on delete cascade across 2 tables
CHECK constraint
----------------
* Relation operators
* Logical operators
* Arithmetic operators
* Special operators
e.g. BETWEEN, in, like, etc.
* all single-row functions
e.g. upper, substr, etc.
DATE-30/11/2021
----------------