SQL Notes
SQL Notes
emp;
create table dept as select * from scott.dept;
DB Operations ( I / U / D )
DML - Data maunipulation lang
---------------------
-- collecting data
-- manipulate data
-- Analyze data
Data Type
age 45
name suhas
sal 100.100
*****
char v/s varchar2
char is fixed length : means it takes entire defined space
varchars is variable length : means it takes requried space
insert into student values( 1, 'suhas', 'sql', 9999999, 'bangalore', 'M', '01-NOV-
2022');
-- sysdate : system date
insert into student values( 2, 'Payal', 'plsql', 9999999, 'bangalore', 'F',
sysdate);
-- lines starts with -- is called commented lines , means ignore for run ( ctl+ ?
-- selective coulmns
select sname, subject, doj from student;
------- assiggment
account_number
name
account_type
transtction_type
date_of_opening
branch_code
-- ***** create new empty table ( menas only structe should be copied ) no data
create table emp_empty as select * from scott.emp where 1=2;
select * from emp_empty;
-- selective columns
select ename , job , sal from emp;
-- relatinal operator
-- =, <>, > , < , >= , <=
-- ANY data type other than numaric should be in single quote ' '
select * from emp where empno = 7839;
select * from emp where ename = 'KING';
select * from emp where hiredate ='17-NOV-81';
-- in operator
-- all relational operators can check ONLY one value at a time
select * from emp where deptno = 10 , 30;
-- ~IN is NOT IN
select * from emp where deptno not in ( 10 , 30);
-- AND / OR together
~IN is NOT IN
select * from emp where deptno not in (10,20,100, 400);
select * from emp where deptno <> 10 or deptno <> 20 or deptno <> 100 or deptno <>
400;
select * from emp where empno = 7788 or empno = 7566 or emopno = 7521 or
job ='MANAGER' or job = 'CLERK';
x science 95
y math 0
z social -
1) find emp having comm as null and having sal > 1500
select * from emp where comm is null and sal > 1500;
select
ename employee_name,
sal,
comm commision,
sal+ nvl(comm,0) monthly_salary ,
(sal + nvl(comm,0)) * 12 anual_salary
from emp;
insert all
into t values('suresh', null)
into t values('mithun', sysdate)
into t values('mithun-2', sysdate+1)
select * from dual;
------------------
-- day-5 11/29
------------------
nvl2 : replace null as well as non null
nlv2( v1, v2 , v3)
if v1 is not null ==> v2
if v1 is null == > v3
select
-- replacing non null value
nvl2(1, 10, 20 ) ,
-- replacing null value
nvl2(null,10,20)
from dual;
select
nvl2(1, 10, 20 ) ,
nvl2(null,10,20),
nvl2(0,30,20),
nvl2(null,10,null),
nvl2(10,null,30)
from dual;
select
ename,
sal,
comm,
nvl2(comm, sal , 1000) bonus
from emp;
select
empid, basic,
hra, ta,da,
nvl2( basic, hra, nvl(ta,0) + nvl( da,0) ) commision,
nvl2( basic, hra, nvl(ta+da ,0)
from salary;
nvl2(c1,c2,c3)
----------- ----------------------
c1 c2 c3 nvl2(c1,c2,c3) nvl( nvl2(c1,c2,c3),100)
nvl2(c1, nvl(c2,100) , nvl(c3,100))
1 0 2 0 0
1 null 2 null 100
null null 2 2 2
null null null null 100
select
nvl2(null, 'a', 'b'),
nvl2(null, null, 'b'),
nvl2('b', 'a', 'b')
from dual
-- Coalesce takes n values ==> gives first non null values from list
create table test
(
c1 number,
c2 number,
c3 number,
c4 number
);
c1 c2 c3 c4 Coalesce(c1,c2,c3,c4) Coalesce(c3,c4,c2,c1)
1 2 null 2 1 2
null 2 null 2 2 2
null null null 2 2 2
----------
select GREATEST (1,4,600,9,100) , LEAST (2,4,5,6,71) from dual;
select nvl(GREATEST (1,4,600,9,100, null),0) , LEAST (null,2,4,5,6,71) from dual;
********** Decode
-- decode can decode only single columns
-- we cant use exclusively any relational / logical
-- unmatched data we null
-- optinal else part can b written
insert all
into emp values('abc', 'm')
into emp values('xyz', 'f')
into emp values('mnc',null)
into emp values('AMY','x')
into emp values('ABC','z')
select * from dual;
select ename, gender, decode ( gender , 'm' , 'Male' , 'f', 'Female' ) emp_sex
from emp;
select ename, gender, decode ( gender , 'm' , 'Male' , 'f', 'Female' , 'unknown
gender' ) emp_sex
from emp;
insert all
into student values('neeraj', 'J','F')
into student values('Suuraj', 'P','F')
into student values('Meeraj', 'A','F')
into student values('Reena', 'A','M')
into student values('Meena', 'j','M')
select * from dual;
-------- assignment
fruit
fruitid number
fruitcode char(1) 'a','b','c','M', 'O','s','x','z','y', null
a==> apple
b==> banana
c==> chikku
M ==> mango
O ==> ornage
else ==> God knows
--- assignemnt -2
select * from scott.dept
10 ==> ten
20 ==> twnenty
30==
select ename,gender,
decode ( gender ,'m', 'male', 'f', 'female', 'god knowns' ) decode_gender,
case
when gender = 'm' then 'male'
when gender = 'f' then 'female'
else 'god knowns'
end case_gender
from emp;
insert all
into student values('neeraj', 'J','F',55)
into student values('Suuraj', 'P','F',65)
into student values('Meeraj', 'A','F',33)
into student values('Reena', 'A','M',90)
into student values('Meena', 'j','M',77)
select * from dual;
-----------------
if sal < 3000 : 'low level'
sal > 3000 and sal <= 4000 'mid level'
sal > 4000 ' high level'
-----------
-- bonus
deptno=10 and job is president, bonus is dobule of salary
deptno=10 and job is manager is 50% of sal as bonus
deptno =10 any one else other than present and manger bonous 1000
--------------
------------
***** case assignment , find out numbers devided by 3 or 4 or both
create table test ( id number);
insert all
into test values(1)
into test values(2)
into test values(3)
.
.
.
into test values(12)
select * from dual;
id result
--------------------
1 No
2 No
3 3-Yes
4 4-yes
5 No
6 3-yes
7 no
8 4-yes
9 3-yes
10 no
11 no
12 both
********** assignement 2
find out number is devided by 3 or 4 or both. along with odd or even
id result
--------------------
1 No
2 No
3 3-odd-Yes
4 4-even-yes
5 No
6 3-even-yes
7 no
8 4-even-yes
9 3-odd-yes
10 no
11 no
12 both-even
----------------------------------------
orderid qty CC UPI Wallet Cash
1 10 500 0 0 1000 cash
2 5 0 1000 0 500 upi
3 1 500 100 4000 1000 Wallet
4 10 7000 2000 5000 1000 CC
);
1 10 cash
2 5 upi
3 1 wallet
4 10 cc
1 A
1 B
1 C
1 D
-------------
-- day 8 03-dec/22
--- sorting
ordering(rearrange) final result in ascending / decending
-- heap tables : order in which records are inserted in the same order records will
be retrived
-- FIFO -- first IN First Out
*******************
-- order of sql execution
*******************
--3
select *
-- 1
from emp
--2
where job <> 'PRESIDENT' AND deptno =10
--4
order by sal desc;
3 20 2000
5 20 5000
1 10 1000
4 10 2000
3 20 2000
5 20 5000
1 10 1000
4 10 2000
-- sal asc
6 30 1500
2 30 2500
7 30 7000
3 20 2000
5 20 5000
1 10 1000
4 10 2000
-- end of Day-8
-- string functions
'sql' == > upper('sql') == > 'SQL'
'SQL' == > lower('SQL') == > 'sql'
'sql plslq' ==> initcap('sql plslq') ==> Sql Plsql
-- if we dont specify number of chars to be cut, then its all remaining all chars
select
substr('sql python' , 5),
substr('sql python aws' , 5)
from dual;
-- -ve indexing
123456
PYTHON
-3-2-1
select
instr('apple' , 'p' , 1 , 1 ),
instr('apple' , 'p' , 1 , 2 ),
instr('apple' , 'p' , 1 , 5 ),
instr('apple' , 'p' , 3 )
from dual;
---
create table test( fruit char(10));
insert into test values('Apple');
insert all
into test values('OrangE')
into test values('grape')
into test values('Egg')
into test values('pineApplE')
select * from dual;
-- to reverse string
Day-6
------------------
-- ltrim, rtrim , trim ,replace and translate
select
trim (trailing '#' from trim (leading '%' from '%sql#') ),
rtrim( ltrim('%sql#','%') , '#')
from dual;
select
-- pattren found
replace ('apple', 'ap' , 'AP'),
-- pattren not found
replace ('apple', 'ae' , 'AE')
from dual;
********** translate
** replace v/s translate
single char/patten repalces multiple chars find and replace
2 == > B
3 == > c
4 == > D
1 == > A
select translate ( '12341234', '2341' , 'BcDA') from dual;
-- string assignments
name info
Surya [email protected] substr(info,find postion @ +1 12-6)
Miller [email protected]
butler [email protected]
name country
-----------------------
surya india
Miller sa
butler uk
logic :
find postion @ +1
find positon of .-1
insert all
into test values ('A')
into test values ('AA')
into test values ('SA')
into test values ('SSA')
into test values ('ASB')
into test values ('SAB')
select * from dual;
-- having one L
SELECT * FROM EMP where ename like '%L%' and length(ename) >=5;
-- having 2 L together
SELECT * FROM EMP where ename like '%LL%' and length(ename) >=5;
select ename
from emp
where substr(ename,3,1) in ( 'A','R');
--- ASSIGNEMENT
find names starting and ending with vowels( a e i o u)
select * from emp
where substr(ename,1,1) in ( 'A', 'E', 'I','O','U')
and substr(ename,-1,1) in ( 'A', 'E', 'I','O','U') ;
----------
find names having vowels
SSA F
sA P
SB F
AA P
BAA P
aBAB F
---
create table person( name varchar2(10));
insert all
into person values('AB10')
into person values('10AB')
into person values('AB')
into person values('10')
select * from dual;
----------------
chars numbers
AB 10
AB 10
AB -
- 10
-- Day -9
-- date function
-- default format is DD-MON-YY
select sysdate from dual;
select
sysdate,
to_char(sysdate, 'dd'),
to_char(sysdate,'day'),
to_char(sysdate,'dy'),
to_char(sysdate, 'mm'),
to_char(sysdate, 'mon'),
to_char(sysdate, 'month'),
to_char(sysdate, 'yy'),
to_char(sysdate, 'yyyy'),
to_char(sysdate, 'year')
from dual;
select
to_char(sysdate, 'mon-yy'),
to_char(sysdate,'mon-dd'),
to_char(sysdate, 'year-month' )
from dual;
--------------- more examples
-- joined in 87
select * from emp where to_Char(hiredate,'yy') = 87;
-- JOINED IN DEC
select * from emp where to_Char(hiredate,'MON') = 'DEC';
select * from emp where to_Char(hiredate,'MM') = 12;
select * from emp where hiredate LIKE '%DEC%';
select * from emp where to_char(hiredate, 'MON-YY') ='DEC-81';
-- joined in 87
select * from emp where to_Char(hiredate,'yy') = 87;
-- JOINED IN DEC
select * from emp where to_Char(hiredate,'MON') = 'DEC';
select * from emp where to_Char(hiredate,'MM') = 12;
select * from emp where hiredate LIKE '%DEC%';
-- even two / more values are same , stil we get single value
-- sample data
100
200
100
300
300
150
------------------------ Group by
select count(*)
from emp
group by deptno;
t
--------
id
1
1
1
2
3
3
4
insert all
into t values(1,1)
into t values(1,1)
into t values(1,2)
into t values(2,2)
into t values(2,2)
into t values(2,3)
into t values(3,3)
into t values(3,3)
select * from dual;
ID1 ID2
1 1
1 2
2 2
2 3
3 3
------------
insert all
into t values(null,null)
into t values(null,null)
select * from dual;
--------
insert all
into t values(null,100)
into t values(100,null)
select * from dual;
--- total number emp working for diff jobs in each deptno
select count(*), deptno, job
from emp
group by job, deptno;
-------###
How many people's are working as a clerk in deptno 20
How many people are joined in deptno 20 on year 81
How many people's works for salary without commission?
How many number manager getting salary morn then 2500 in dept 10
Write a query who is the most senior employee from the emp table
How emp joined in year 81
how many sales havng salary 500 - 2000 and joined in sept
---- day 12
12th Dec 2022
************ Joins
********************************
12th Dec 2022
--- -- inner / equi join
-- gives only matched records from both tables
*******************************
-- table its on left side of join is called left table ( emp is left table)
-- table its on right side of join is called right table( dept is right table)
********************************
--- -- left join
-- gives matched records from both tables and un-matched records from left tables
-- columns values for the right table columns will be null
*******************************
***** how we get records only in left table not in right using joins
select ename, job, dname , loc, d.deptno
from emp e left join dept d on e.deptno=d.deptno
where dname is null;
********************************
--- -- right join
-- gives matched records from both tables and un-matched records from right tables
-- columns values for the left table columnes will be null
*******************************
select ename, job, dname , loc, d.deptno
from emp e right join dept d on e.deptno=d.deptno
***** how we get records only in right table not in left using joins
select ename, job, dname , loc, d.deptno
from emp e rigth join dept d on e.deptno=d.deptno
where ename is null;
********************************
--- -- full join : inner + left + right ( its matched and unmatched from both
tables )
-- inner : match records
-- left ; unmatch from left
-- right : unmatchef from right
*******************************
select ename, job, dname , loc, d.deptno
from emp e full join dept d on e.deptno=d.deptno;
-------------
-- complex joins
employee
---------------------------
empid ename email dob doj deptno projecid
1 suhas 10 1
dept
--------------------------
deptno dname loc
10 slaes delhi
projects
-------------------------
projecid projectname project_location
1 salesforce mangalore
empsalary
-------------------
empid basic DA HRA
--------------------------------
PRODUCT
Product_id Product_name Product_type price
111 Product_1 X 1000
112 Product_2 Y 2000
113 Product_3 X 5000
STORES
--------------
store_id store_name store_address
456 amazon bangaore
457 flikart mumbai
458 decatlon mysore
SALES
Product_id Store_id qty
111 456 10
112 457 20
112 457 100
product_1 1000*10
product_2 2000*20 + 2000 *100
product_3 0
create table Product (product_id number primary key, product_name varchar2(20) not
null, product_type varchar2(10) check (product_type in ('X','Y')),Price number not
null);
insert into product values(111,'Product_1','X',1000);
insert into product values(112,'Product_2','Y',2000);
insert into product values(113,'Product_3','X',5000);
select * from product;
create table Stores(store_id number primary key, store_name varchar2(20) not null,
store_address varchar2(20) not null);
insert into Stores values(456,'Amazon','Bangalore');
insert into Stores values(457,'Flipkart','Mumbai');
insert into Stores values(458,'Decatlon','Mysore');
select * from stores;
3) total sales value of each product if, product not soled , then sales amout
shoudl be zero
table_A
id
-------
1
1
1
table_B
-----------
1
1
------
A
c1
--------
2
2
3
5
5
Null
B
----
C2
1
1
2
3
3
null
-------- CONSTRAINTS
constraints : set of rules created on table columns
enforces quality of the data coming into data or getting changed in table.
**Primary Key : Not Null and No duplicate: it wont allows null values and no
duplicate values.
exampel roll_no , order_no, acc_no
It uniquely identifide record .
only one PK on table
not null + unique
** check : allows only permited list of values example gender ( M F ) , Sal < 10000
** Foreign Key : Key refer to Primary key, it ensure data Integrety (Consistency)
b/w parent and Child table.
Posible values in FK are Primary key only , but it can be
duplicate
also values could be NULL
******** table can have only one primary key, we can multiple unique constraint
-- End of Day -4
-- example unique constraint
FN LN
--------
vinay kumar
vinay alabur
-- invalid
insert into student values(2,'sachin', 'kumar');
insert into student values(2,NULL, 'kumar');
-- example of conposite PK
-- invalid dup
insert into student values('a', 'c');
-- cant insert null into composite PK columns
insert into student values(null, 'b');
insert into student values('a', null);
insert into student values(null, null);
******************
Un-nomralized table , each cell may have more than one value
sid sname subject
1 Neeraj k,e,m,s,sc
2 Meeraj k,e,m,s
-----------
1st Normal Form
------------
Each cell should be having only single value ( No repeating groups allowed)
entries are in the column of same type
rows should be UNIQUE identified ( means must have primary key)
-- invalid FK violation
insert into subject values ( 4, 3,'M', 90);
select * from subject;
******************************
-- Psudo columns : rownum , rowid
-- Fetch top / bottom records
--- rowid
-- it represents address of record with in table
-- record inserted first will have min rowid and last will have max of rowid
-- limit : mysql
-- top : sql server
-- fetch first 3 rows only : oracle
-- last 3 records
select * from emp
order by rowid desc
fetch first 3 rows only;
insert all
into deptsales values(1)
into deptsales values(2)
into deptsales values(3)
select * from dual;
insert all
into deptmarketing values(1)
into deptmarketing values(2)
into deptmarketing values(5)
into deptmarketing values(7)
select * from dual;
-------- empid
-- union gives combained output of 2 selects : ** without duplicate **
select empid from deptsales
union
select empid from deptmarketing;
1
2
3
5
7
1
2
3
1
2
5
7
-- intersect
-- common records
select empid from deptsales
intersect
select empid from deptmarketing;
minus
-----
-- gives records present in 1st ( deptsales) but not present in 2nd (deptmarking)
table
select empid from deptsales
minus
select empid from deptmarketing;
------ like
-- % any of char of zero or more occrnace
select * from emp where ename like 'A%';
select * from emp where ename like '%S';
select * from emp where ename like '%A%';
Ename return
A yes
aA yes
bbA yes
AbbA yes
bAbA yes
abba No
Ename return
A Yes
aA no
bbA no
AbbA Yes
bAbA No
abba No
-- A in 3rd place
select * from emp where ename like '__A%';
select * from emp where substr(ename,3,1) ='A';
-- 2L
select * from emp where ename like '%L%L%';
return
LAL yes
LLA yes
ALL yes
LALA yes
-- 2 continues L
select * from emp where ename like '%LL%';
return
LAL No
LLA yes
ALL yes
LALA No
select e.*
from emp e
join dept d on e.deptno=d.deptno
where loc ='NEW YORK';
-- outer sql
select * from emp where deptno =
(
-- inner sql
select deptno from dept where loc ='NEW YORK'
);
-- find all dname, loc having SALESMAN
select * from dept where deptno in (
select deptno from emp where job ='SALESMAN');
customer
--------------
cid cname city
1 abc DELHI
2 mnc BANG
3 xyz BANG
4 uuu MYSURU
item
----------
id cid item_desc sold_date
1 1 soap 12-DEC-2022
2 1 book 12-DEC-2022
3 2 milk 13-DEC-2022
4 3 shampo 12-DEC-2022
5 3 book 12-DEC-2022
6 3 milk 13-DEC-2022
---- normalization
------- views