0% found this document useful (0 votes)
15 views43 pages

SQL Notes

The document provides a comprehensive overview of SQL database operations, including creating tables, inserting, updating, and deleting records, as well as querying data using various SQL commands. It explains data types, the structure of tables, and the use of functions like NVL and NVL2 for handling null values. Additionally, it covers logical operators, relational operators, and the importance of comments in SQL scripts.

Uploaded by

mohang150396
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views43 pages

SQL Notes

The document provides a comprehensive overview of SQL database operations, including creating tables, inserting, updating, and deleting records, as well as querying data using various SQL commands. It explains data types, the structure of tables, and the use of functions like NVL and NVL2 for handling null values. Additionally, it covers logical operators, relational operators, and the importance of comments in SQL scripts.

Uploaded by

mohang150396
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 43

create table emp as select * from scott.

emp;
create table dept as select * from scott.dept;

data base - repo / container for collecting in organized manner


----------------
structure manner -table
table- columns ( attributes ) , row - actual values - records

single row -- record


mutiple rows -- record set / data set

-- we must a structure to collect


1) identify the attributes to be collected
2) create structure ( create table )

DB Operations ( I / U / D )
DML - Data maunipulation lang
---------------------

insert - Collecting new information


Update - Modifying existing data
delete - Remove unwanted data

select - retrive -- reading the data

-- collecting data
-- manipulate data
-- Analyze data

S Q L - structure query language

----------------- -- end of day-1

Data Type

numeric int float


string char- string alpa + special char : 'sql' 'pyhhon-3'
Date 01-jan-2022
Boolean True / False 1/0
complex x+jy

age 45
name suhas
sal 100.100

*** sql data Types


----------------
number - int + float
char - fixed legnth char : it accumlates entire space.
varchar2 - variable chars
date - date

number - 2**-31 to 2**32


precision - whole part( int + deciaml)
scale - decimal point
100.10
number
100.10 number(5,2)
1000.5 number(5,1)
22.333 number(5,3)
2.222 number(4,3)

maximun of 9999 for rollnumber number(4,0)


number(3,3) .456

*****
char v/s varchar2
char is fixed length : means it takes entire defined space
varchars is variable length : means it takes requried space

char can have max of 2000 chars only


varhcar2 can have max of 4000 chars

create table student


(
rollnum number(3,0),
sname varchar2(100),
subject varchar2(100),
phone char(10),
place varchar2(100),
Gender char(1),
doj date
);

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);

-- read the table data

-- any line starts with -- commented lines , skip from run/execution


-- short cut ctl +?

-- * gives all the columns of table


select * from student;

-- lines starts with -- is called commented lines , means ignore for run ( ctl+ ?

-- selective coulmns
select sname, subject, doj from student;

-- multiline comments : single line comment


/* multiline comment
select * from student;
select sname, subject, doj from student;
*/

** google : how to have single quote within data sql's


-- to see structure of a table
describe student;

------- assiggment

emp Identify DT / create new table


--------------
empno
ename
job
sal
departname
email
doj

Bank_account -- identify columns/DT and create new table


-------------

account_number
name
account_type
transtction_type
date_of_opening
branch_code

************* ------ End of day -2


22/11/22

create table student


(
rollnum number(3,0),
sname varchar2(100),
place varchar2(100),
Gender char(1),
doj date
);

-- inserting values to all columns


insert into student values( 1, 'ajay' , 'bag' , 'm', sysdate);

-- inserting nulls to few columns


insert into student values(2,'sam', null, 'm', null);

select * from student;

-- inserting only few columns


insert into student ( rollnum , sname, place ) values (3, 'nidhi', 'dhl');

***** insert multiple in single insert statement


insert all
into student values( 4, 'Bijay' , 'bag' , 'm', sysdate+1)
into student values( 5, 'vijay' , 'bag' , 'm', sysdate-1)
into student values( 6, 'vinay' , 'bag' , 'm', null)
select * from dual;

select * from student;

-- scott user / account hving 2 table emp/dept


select * from scott.emp;
select * from scott.dept;

-- create local copy of emp table


***** how do we create copy of one table ( create new table from existing table )
-- CTAS create table as select

create table emp as select * from scott.emp;


create table dept as select * from scott.dept;

-- CTAS --create table as select


create table emp as select * from scott.emp;
select * from emp;

-- new table name can be different from exisit table


create table E2 as select * from scott.emp;
select * from e2;

-- create table with only selective columns


create table emp_new as select empno, ename , job from scott.emp;
select * from emp_new;

-- ***** 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;

----------- End of day -3


23/11/2022
-- ctl+ enter : will execute statement
-- * represents all columns
select * from emp;

-- selective columns
select ename , job , sal from emp;

-- relatinal operator
-- =, <>, > , < , >= , <=

-- where is used fillter rows/records

select * from emp where deptno = 10;


select * from emp where sal < 3000;
select * from emp where sal <= 3000;
select * from emp where sal >= 3000;
select * from emp where sal != 3000;
select * from emp where sal <> 3000;
select ename , job , sal from emp where sal =3000;

-- in any order we can list u r requried columns


select sal, job, deptno, ename from emp
where deptno =30;

-- 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';

-- data in the table is case sensitive


select * from emp where job ='Salesman';

-- sql commandas are case insenstive


( select , where from, table/column names can be in any case)

-- in operator
-- all relational operators can check ONLY one value at a time
select * from emp where deptno = 10 , 30;

-- IN : checks for multiple equals


select * from emp where deptno in ( 10 , 30);

-- ~IN is NOT IN
select * from emp where deptno not in ( 10 , 30);

-- EMP WORKING EITHER AS CLERK , ANALYST


select * from emp where job in ('CLERK' , 'ANALYST');

-- use of logical operators AND / OR

AND (MUST pass all condiations )


------------
T T T
T F F
F T F
F F F

select * from emp where deptno=20 and job='CLERK';

-- ALL EMP IN 30 OTHER THAN SALESMAN


select * from emp where deptno=30 and job <> 'SALESMAN'

-- OTEHR THAN 20 ALL MANAGERS


select ename, job, sal, deptno
from emp
where deptno <> 20 and job ='MANAGER';

-- we can apply n number of fillter


select ename, job, sal, deptno
from emp where sal < 3000 and deptno <> 10 and job ='SALESMAN';

OR (EITHER one of all condiations )


--------------
T T T
T F T
F T T
F F F

select * from emp where deptno =10 or job ='SALESMAN';


select * from emp where hiredate > '01-JAN-1985' OR job ='ANALYST';
select * from emp where hiredate > '01-JAN-1985' OR job ='ANALYST' or sal > 3000;

-- if either of condiations failed , no records will return


select ename, job, sal, deptno
from emp where sal > 5000 or deptno = 50;

** find employes not working in dept 10 and as president


** find employes not working in dept 20 or any one as salesman
** salesman taking salary above 2000

-- AND / OR together

select * from emp where ( deptno=30 or job='CLERK' ) and sal >=1500;

-- and is stronger than or


select * from emp
where deptno=20 and job ='ANALYST' or sal > 3000;

select * from emp


where (deptno=20 and job ='ANALYST') or sal > 3000;

select * from emp


where deptno=20 and ( job ='ANALYST' or sal > 3000 );

-- IN and NOT IN operator


select * from emp where empno in (7782 , 7369,7934,7902) or job='CLERK' ;
select * from emp where empno in (7782 , 7369,7934,7902) AND job='CLERK' ;

~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 job not in ('PRESIDENT', 'MANAGER');


-- not working as president or manager and belogs to 30
select * from emp where job not in ('PRESIDENT', 'MANAGER') and deptno=30;

-- in is specify form of multiple OR's


select * from emp where deptno in (10,30);
select * from emp where deptno =10 or deptno =30;

select * from emp where empno = 7788 or empno = 7566 or emopno = 7521 or
job ='MANAGER' or job = 'CLERK';

select * from emp


where EMPNO IN( 7788 , 7566 , 7521) or job in ( 'MANAGER' , 'CLERK');

----------- end Day 4

*** Null values : missing or unknown value is called NULL

null <> 0 .. null <> null..


since null does not have value we can't compare using relatinal operator

NULL <> NULL

x science 95
y math 0
z social -

-- all relatinal operator fail ( = <> <= >= <>)


select * from emp where comm = null;

-- to compare null values we use IS


select * from emp where comm is null;

-- non null values can be feteched usig IS NOT


select * from emp where comm is NOT null;

-- any arthematic with null resulted into null


select ename , sal, comm, sal + comm from emp;
select sal, comm ,comm+100 , comm *100 , comm/100 , comm-0 from emp;

--- system date


select <what to be selected > ?? from <where to be selected>???

-- dual is called psudo table.


select sysdate from dual;

-- dual single column / row table having value of X


select * from dual;

-- dual is used get current date and run equations / expressions


select 5+5 , 5*5 , 5/5 , 5-5 from dual;
select 5+0 , 5+null, 5*null, 5*0, null+null from dual;

1) find emp having comm as null and having sal > 1500
select * from emp where comm is null and sal > 1500;

2) find emp belogs to either deptno 10 or 20 and eligable for comm


select * from emp where deptno in (10, 20) and comm is not null;

-- NVL stands for null value function


-- it repalces null value with subsitute value
-- if comm is null then 0
select ename, sal, comm, sal+ nvl ( comm,0) from emp;

-- nvl can be used to replace null with any value


select ename, sal, comm, sal+ nvl ( comm,100) from emp;

create table test ( name VARCHAR2(10));

insert into test values('suresh');


insert into test values(null);
select * from test;

select nvl( name , 'no name given') from test;

-- column alias : giving another name to columns / expression


-- it gives meaning names
-- alias can also give for table columns as well as expression
select
ename as emplpyee_name,
sal salary,
comm ,
sal + nvl(comm,0) totalsalary
from emp;

select
ename employee_name,
sal,
comm commision,
sal+ nvl(comm,0) monthly_salary ,
(sal + nvl(comm,0)) * 12 anual_salary
from emp;

***** Limitation of nvl function


*** replacement value must be same dataType of the column in NVl function
-- wrong ?? replacement is varchar where column Datatype numaric
select ename, nvl(comm, 'a') from emp;

create table t ( name varchar2(10), dob date);

insert all
into t values('suresh', null)
into t values('mithun', sysdate)
into t values('mithun-2', sysdate+1)
select * from dual;

select name , dob , nvl(dob , '01-JAN-2023') from t;

------------------
-- 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 nvl2(null, 1,2) from dual;

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;

drop table salary;

create table salary


(
empid number,
basic number,
hra number,
TA number,
DA number
);

insert into salary values(1,1000,300,null, null);


insert into salary values(2,null,3000,100, 200);
insert into salary values(3,null,null,100, 200);
insert into salary values(4,null,null,100, null);
insert into salary values(5,null,null,null, 100);

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

***** nvl v/s nvl2


-- nvl - takes 2 values ==> its replaces ONLY null
-- nvl2 takes 3 values ==> its replaces both null and non null values

select
nvl2(null, 'a', 'b'),
nvl2(null, null, 'b'),
nvl2('b', 'a', 'b')
from dual

------------------------ Day 6 12/01/2022

-- Coalesce takes n values ==> gives first non null values from list
create table test
(
c1 number,
c2 number,
c3 number,
c4 number
);

insert into test values ( 1, 2, null, 2);


insert into test values ( null, 2, null, 2);
insert into test values ( null, null, null, 2);

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 Coalesce ('a','b','c'), Coalesce(null,'b','c') , Coalesce(null, null, 'c')


from dual;

----------
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

create table emp


(
ename varchar2(10),
gender char(1)
);

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;

-- decode uses implicity equlity for column value comparision


-- it is kind of writing else in sql statement

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;

select ename, gender,


decode (nvl( gender,'m') , 'm' , 'Male' , 'f', 'Female' , 'unknown
gender' )emp_sex
from emp;

-- null are treated as males


-- any values other nulls, 'm' , 'f' ( 'x','y'.. should be teated as females)
select ename, gender,
decode (nvl(gender,'m'), 'm' , 'f' , 'f','m' ,'f') actualgender
from emp;

------ some more examples


create table student ( name varchar2(10), subject varchar2(1) , gender
varchar2(1));

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;

select name, subject, upper(subject),


decode ( upper( subject) , 'J', 'JAVA', 'A','AWS','P','PYHTON', 'GOD KONWS')
subject
from student;

-------- 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==

------- day 7 12/03/2022


** case Expressions

create table emp


(
ename varchar2(10),
gender char(1)
);
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', 'god knowns' ) decode_gender,
case
when gender = 'm' then 'male'
when gender = 'f' then 'female'
else 'god knowns'
end case_gender
from emp;

drop table student


create table student ( name varchar2(10), subject varchar2(1) , gender
varchar2(1) , marks number);

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;

-- marks < 35 fial


-- marrks >=35 and marks <= 60 pass
-- marks >= 60 and marks <=100 excellet
select
name, subject, marks,
case
when marks <35 then 'fail'
when marks >=35 and marks <=60 then 'Just passed'
when marks > 60 and marks <=100 then 'exccellent'
else ' call college'
end results
from student;

-----------------
if sal < 3000 : 'low level'
sal > 3000 and sal <= 4000 'mid level'
sal > 4000 ' high level'

select ename, job, deptno,sal,


case
when sal <= 3000 then 'low level'
when sal > 3000 and sal <= 4000 then 'mid level'
when sal > 4000 then 'high level'
else 'un-known values'
end salary_range
from emp;
----------
deptno=10 bonus = 10% of sal
deptno=20 bonus = 30% of sal
deptno=30 bonus = 20% of sal

select ename, job, sal,


case
when deptno=10 then sal * .10
when deptno=20 then sal * .15
when deptno=30 then sal * .30
else 10000
end casebonus,
decode ( deptno , 10 , sal * .10 ,
20 , sal * .15,
30 ,sal * .30 , 10000
) decodebonus
from emp;

-----------

-- 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

deptno=20 and job is analyst bonus is dobule of salary


deptno=20 and job is clerk is 50% of sal as bonus
deptno =20 any one else other than present and manger bonous 1000

deptno=30 and job is analyst bonus is dobule of salary


deptno=30 and job is salesman is 50% of sal as bonus
deptno =30 any job is clerk ..bonus as 10000
other others job 0

select ename, deptno,job, sal,


case
when deptno=10 and job ='PRESIDENT' then sal * sal
when deptno=10 and job ='MANAGER' then sal * 0.5
when deptno=10 and job not in ('PRESIDENT' , 'MANAGER') then 1000
end deptbonus
from emp;

--------------

if deptno =10 and sal < 2500 30% fo sal


if deptno =10 and sal > 2500 10% fo sal
if deptno =20 and sal > 2500 40% fo sal
if deptno =20 and sal > 2500 10% fo sal

select ename, sal,deptno,


case
when deptno =10 and sal < 2500 then (sal + nvl(comm,0))*.20
when deptno =10 and sal < 2500 then (sal + nvl(comm,0))*.25
when deptno =20 and sal < 2500 then (sal + nvl(comm,0))*.30
when deptno =20 and sal > 2500 then (sal + nvl(comm,0))*.27
when deptno =40 and sal < 2500 then (sal + nvl(comm,0))*.24
when deptno =30 and sal < 2500 then (sal + nvl(comm,0))*.50
when deptno =40 and sal > 2500 then (sal + nvl(comm,0))*.10
else 0
end Bonus
from emp;

------------
***** 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

create table order


(

);

select orderid, qty,


case
when cc>upi and cc>wallet and cc>cash then 'CC'
when upi> wallet and upi > cash then 'upi'
when wallet > cash then 'wallet'
else 'cash'
end modepayment
from order;

1 10 cash
2 5 upi
3 1 wallet
4 10 cc

-- if avgsal = if avg(sal) > sal then sal else avg(sal)


empno sal deptno avgsal
1 1000 10 1000
2 2000 10 1500
3 5000 20 3500
4 2000 20 2000
3 4000 30 4000

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

-- ascending : lower to high


-- decending : high to low
select * from emp order by sal desc;
select * from emp order by sal asc;

-- default sorting is ascending order


select * from emp order by deptno;

*** if we sort null value columns, null goes last


select * from emp order by comm;

-- if null to be first sort by desc


select * from emp order by comm desc;

-- ***** sorting on string columns


-- A < B < C < D ... Z .. <a < b <c.. y<z
-- default sorting is ascending
select * from emp order by ename

-- ***** sorting on date columns


-- latest date is > older vaule
-- sysdate+1 > sysdate > sysdate -1 > sysdate -2
-- '01-jan-1987' < '22-jan-2023' < '02-feb-205'
select * from emp order by hiredate desc;

*******************
-- order of sql execution
*******************

--3
select *
-- 1
from emp
--2
where job <> 'PRESIDENT' AND deptno =10
--4
order by sal desc;

------ multi column sorting


create table t ( id number, dept number, sal number);
id dept sal
1 10 1000
2 30 2500
7 30 7000
3 20 2000
5 20 5000
6 30 1500
4 10 2000

-- example 1 select * from emp order by dept desc, sal desc


-------------------------------------
select * from emp order by dept desc
2 30 2500
7 30 7000
6 30 1500

3 20 2000
5 20 5000
1 10 1000
4 10 2000

order by dept desc , sal desc


7 30 7000
2 30 2500
6 30 1500
5 20 5000
3 20 2000
4 10 2000
1 10 1000

-- example 2 select * from emp order by dept desc, sal asc


select * from emp order by dept desc
2 30 2500
7 30 7000
6 30 1500

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

select * from emp


order by job asc , sal desc

-- end of Day-8

-- string functions
'sql' == > upper('sql') == > 'SQL'
'SQL' == > lower('SQL') == > 'sql'
'sql plslq' ==> initcap('sql plslq') ==> Sql Plsql

select lower('SQl') from dual;


select upper('SQl') from dual;
select initcap('SQl pythoN') from dual;
select ename, lower(ename), initcap(ename) from emp;

select length('sql python') from dual;


select ename, length(ename) , length(job),job from emp;

-- index : means position of char within string


1 2 3
S Q L

-- substr : gives part of the string


substr(string, start_index, how many chars)

select substr('SQL is very easy',1,3) from dual;


select substr('SQL python is very easy',5,6 ) from dual;

-- it gives till end


select substr('SQL python is very easy',5 ) from dual;

-- Get first 3 chars of name


select ename , substr(ename, 1,3) from emp;

-- 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;

create table test( cname varchar2(100));


insert into test values('we are in india');

-- -ve indexing
123456
PYTHON
-3-2-1

select substr('oracle sql' ,-1) ,


substr('oracle sql' ,-3),
substr('oracle sql' ,-3,1)
from dual;

-- get last 5 chars using length and -ve index


select
substr(cname , length(cname)-5 ),
substr(cname , -5 )
from test;

------- google and find out how to revese string in sql


-- instr : gives index(postion) of char with in string

select instr('apple' , 'e') from dual;


select instr('apple' , 'p') from dual;

instr( string , char to be find , starting index , occurance

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;

select * from test;


select
fruit, instr(lower(fruit), 'e') ,
fruit, instr(upper(fruit), 'E')
from test;

-- to reverse string

select reverse('sql') from dual;

Day-6
------------------
-- ltrim, rtrim , trim ,replace and translate

ltrim ==> removes spaces / chars from left side


rtrim ==> removes spaces / chars from right side
works only on leading and trailing chars, not in between

-- default removes spaces


select ltrim(' sql ' ) , rtrim(' sql ') ,
length(rtrim(ltrim(' sql ')))
from dual;

select ltrim('###&sql#&&', '#' ) from dual;


select ltrim('###&sql#&&', '#&' ) from dual;

select rtrim('###&sql#&&', '&' ) from dual


select rtrim('###&sql#&&', '&#' ) from dual;

-- trims removes spaces on both sides


select trim( ' sql ') from dual;

select length( rtrim( ltrim('$$python**','$'),'*') ) from dual;

-- assignment to remove leading and trailing spaces using trim

select
trim (trailing '#' from trim (leading '%' from '%sql#') ),
rtrim( ltrim('%sql#','%') , '#')
from dual;

--------- replace : find a char and replace it with given char

select replace('mpple' 'm', 'a') from dual;


select replace('mpple mango modle', 'm', 'a') from dual;
select replace('apple mango grape', ' ', '-') from dual;

select
-- pattren found
replace ('apple', 'ap' , 'AP'),
-- pattren not found
replace ('apple', 'ae' , 'AE')
from dual;

-- pattren can be replaced with another pattren


select ('apple' , 'pp' , 'PP') , ('apple' , 'pp' , 'Pass') from dual;

-- replacement char is not specified, ? that char will be remvoed


select
replace ( 'sql plsql' ,'q' ,'Q'),
replace ( 'sql plsql' ,'q')
from dual;

** how to remove all spaces in given stirng


select replace(' s ql ', ' ') from dual;

*** Interview question

-- find occurance of given char in string


select length('vinay kumar alabur') - length(replace ('vinay kumar alabur', 'a' ))
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;

-- as like in repalce, if we dont specify repalcement char, that char will be


removed
select translate ( '12341234', '2341' , 'BcD') from dual;

-- example to remove multiple chars in given string


select translate('123$ABC#' ,'#$',' ' ) from dual;

-- string assignments

-- new table called player

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

-- Day -7 Like operator


-- % WILDCARD operator : zero or any number any char ( 0-9 or a-z ~-_)

-- names start with A


create table test ( name varchar2(10));

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;

select * from emp where ename like 'A%'


-- names ends with A
select * from emp where ename like '%A'
select * from emp where ename like '%A%';
A
AA
SA
SSA
ASB
SAB
select * from emp where ename like '%A';
A
AA
SA
SSA

-- 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;

-- having 2 A any where


SELECT * FROM EMP where ename like '%A%A%' and length(ename) >=5;

-- name having 3rd letter as A or 3rd letter as R or L


select ename
from emp
where substr(ename,3,1) ='A' or substr(ename,3,1) ='R';

select ename
from emp
where substr(ename,3,1) in ( 'A','R');

Day-8 : continues Like operator


-------------------

--- 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

select * from emp


where ename like '%A%' or ename like '%E%' or ename like '%I%' OR ename like '%U
%';

-- _ is matches exactly only one word

select * from emp where ename like '_A%';

SSA F
sA P
SB F
AA P
BAA P
aBAB F

-- find names having 2nd char as A


select * from emp where ename like '_A%';
-- find names having last but one char as A
select * from emp where ename like '%A_';
-- find names having 5 chars and 3rd char as L
select * from emp where length(ename)=5 and ename like '__L%';

-- stats with M , haivng LL together and should be more than 5 char


select * from emp
where ename like 'M%LL%' and length(ename) >5

---
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%';

-- joined on day 23of the month


select * from emp where to_char(hiredate, 'dd') =23;
select * from emp where to_char(HIREDATE,'DD/MON')= '23/JAN';

-- Day 10 Aggregate functions


max , min , sum , count and avg - they return aggreated/single valve

-- even two / more values are same , stil we get single value

-- sample data
100
200
100
300
300
150

count === > 6


max ===> 300
min == > 100
sum ==> 1150
avg == > sum/count

select count(empno) from emp;


select max(sal), min(sal), avg(sal), sum(sal) from emp;

create table test (value number);


insert all
into test values(100)
into test values(200)
into test values(300)
into test values(300)
into test values(150)
into test values(150)
into test values(null)
select * from dual;

***** all aggregate functions ignores null


** why ? if null values are considered for computation, final output will also be
null
select count(value) ,sum(value) from test;

** if we want to find total number of rows in a table , we must use count(*)

value count(value) count(*) count(1)


count(8)
total non null values each row marked as *
-----------------------------------------------------------------------------------
--------------------------------
* 1 100 6 8 8 8
* 1 200
* 1 100
* 1 300
* 1 300
* 1 150
* 1 null
* 1 null

------------------------ Group by

insert into emp values( 8888, 'Santosh', 'Manager', 7698, to_date('3-12-


1981','dd-mm-yyyy'), 950, null, null);
insert into emp values( 9999, 'srivivas', 'CLERK', 7782, to_date('23-1-1982','dd-
mm-yyyy'), 1300, null, null);

select count(*)
from emp
group by deptno;

select count(*), deptno


from emp
group by deptno
order by deptno asc;

select count(*), job


from emp
group by job
order by job asc;

-- find max salary of each dept


-- ** we can use column alias in order by
select deptno , max(sal) maxsalary
from emp
group by deptno
order by maxsalary desc;

-- find total emp, max sal, min sal of each job

---------------- day 11 -- multi column grouping

select distinct job from emp;


select distinct deptno from emp order by deptno desc;

t
--------
id
1
1
1
2
3
3
4

select distinct id from t;


1
2
3
4

create table t ( id1 number , id2 number);

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;

select distinct id1, id2 from t order by 1;

ID1 ID2
1 1
1 2
2 2
2 3
3 3

select count(id1), sum(id1) from t group by id1;


select count(id2), sum(id2) from t group by id2;

select count(*) , id1,id2


from t
group by id1, id2
order by id1;

------------
insert all
into t values(null,null)
into t values(null,null)
select * from dual;

select count(*) , id1,id2


from t
group by id1, id2
order by id1;

--------
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

-- avg salaries of clerk in deptno 20,30


select avg(sal)
from emp
where deptno in (20,30) and job ='CLERK';

---- day 12
12th Dec 2022
************ Joins

create table emp as select * from scott.emp;


create table dept as select * from scott.dept;

insert into emp values( 8888, 'Santosh', 'Manager', 7698, to_date('3-12-


1981','dd-mm-yyyy'), 950, null, null);
insert into emp values( 9999, 'srivivas', 'CLERK', 7782, to_date('23-1-1982','dd-
mm-yyyy'), 1300, null, null);

insert into dept values ( 50, 'TECH SUPPORT' , 'BANGALORE')

-- join : is a techinque to extract data from multiple tables


SELECT
ename, job, -- emp
dname , loc -- dept
from dept;

-- Join is key word to join two tables


-- on is key word to build relation among two tables

select ename, job, dname , loc


from emp join dept on emp.deptno = dept.deptno;

-- ORA-00918: column ambiguously defined


-- only when common column included in select
select ename, job, deptno, dname , loc
from emp join dept on emp.deptno = dept.deptno;

-- to overcome above error we prefix table to common column


select ename, job, dept.deptno, dname , loc
from emp join dept on emp.deptno = dept.deptno;

--- use of table alias in select statement


-- below example e and d are table alias

select empno, ename, job, d.deptno, e.deptno,


dname,loc from emp e join dept d on e.deptno= d.deptno;

-- Use of table alias in join


select ename employee_name, -- column alias
job,
d.deptno, -- table alias
dname ,
loc, sal + nvl(comm,0) as totalsal
from emp e join dept d on e.deptno = d.deptno;

-- Table alias Giving meaning full name table


-- column alias Giving meaning full name columns

select empno employee_id,


ename employee_name,
job, d.deptno, e.deptno,
dname,loc from emp e join dept d on e.deptno= d.deptno;

********************************
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)

select ename, job, dname , loc, d.deptno


from emp e join dept d on e.deptno=d.deptno;

-- using inner word


select ename, job, dname , loc, d.deptno
from emp e inner join dept d on e.deptno=d.deptno;

********************************
--- -- 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
*******************************

select ename, job, dname , loc, d.deptno


from emp e left join dept d on e.deptno=d.deptno;

***** 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

unmatched records will have null

*******************************
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

-- ename, dname,loc , projectname


select ename, dname,loc , projectname
from employee e
join dept d on e.deptno = d.deptno
join project p on e.projectid=p.projecid;

select ename, dname, project, Basic+HRA+DA as salary


from emp e join empsalary s on e.empid=s.empid
join project p on e.projectid=p.projecid
join dept d on e.deptno = d.deptno;

--------------------------------

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;

create table Sales(product_id number references Product(Product_id),store_id number


references Stores(store_id), qty number);
insert into sales values (111, 456,10);
insert into sales values (112, 457,20);
insert into sales values (112, 457,100);
select * from sales;

1) find total worth of each sale


select product_name, store_name , price* qty sales_amount
from product p join sales s on p.product_id= s.product_id
join stores st on s.store_id= st.store_id;

2) total sales value of each product

select product_name , sum(price* qty) sales_amount


from product p join sales s on p.product_id= s.product_id
group by product_name

3) total sales value of each product if, product not soled , then sales amout
shoudl be zero

select product_name , nvl( sum(price* qty),0) sales_amount


from product p left join sales s on p.product_id= s.product_id
group by product_name

4) store_name , product_name and total_number qty sold

flikart Product_2 120


amazon Product_1 10

select store_name , product_name, sum(qty)


from product p join sales sl on p.product_id = sl.product_id
join stores s on sl.Store_id = s.Store_id
group by store_name , product_name;

select store_name , product_name, nvl( sum(qty),0) total_sales_qty


from product p left join sales sl on p.product_id = sl.product_id
left join stores s on sl.Store_id = s.Store_id
group by store_name , product_name
order by total_sales_qty desc;

5) find the prodduct it does not having any sales


select store_name , product_name
from product p left join sales sl on p.product_id = sl.product_id
left join stores s on sl.Store_id = s.Store_id
where store_name is null;

6) find stores does not having any sales

select store_name , product_name


from product p right join sales sl on p.product_id = sl.product_id
right join stores s on sl.Store_id = s.Store_id
where product_name is null;

---------------- from interview

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

select c1, c2 from A full join B on a.c1=b.c2;


2,2
2,2
3,3
3,3
5, null
5 , null
Null,null
null,1
null,1
null, null

--------- constraints notes

-------- 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

** unique key: No duplicate , but allow nulls. phone , email


How many nulls allows ? null <> null : Unique allows multiple nulls
we can have multiple UK constraint on a table

** Not Null : No null values allowed. but values can be duplciated

** check : allows only permited list of values example gender ( M F ) , Sal < 10000

** default : if values are not passed to column, default values is consider

** 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

candidate potential primary key , but we dont use it is PK

create table student


(
rollnum number,
sname varchar2(50),
subject varchar2(10),
phone number,
gender varchar2(1)
);
-- below is all bad data ( data violation)
insert into student values ( 1,'Virat','SQL',12345,'M');
insert into student values ( 1,'ABD','SQL',12345,'M');
insert into student values ( NULL,'Kepller','SQL',12345,'M');

create table student


(
rollnum number primary key,
sname varchar2(50) not null,
subject varchar2(10) check ( subject in( 'm','k','e','s')),
phone number,
gender varchar2(1) check ( gender in ( 'M','F'))
);
insert into student values ( 1,'Virat','SQL',12345,'M');
insert into student values ( 1,'ABD','SQL',12345,'M');
insert into student values ( NULL,'Kepller','SQL',12345,'M');
insert into student values ( 2,Null,'SQL',12345,'M');
insert into student values ( 3,'ABD','SQL',12345,'G');

-- End of Day -4
-- example unique constraint

create table student


(
rollnum number primary key,
sname varchar2(50) not null,
subject varchar2(10) check ( subject in( 'm','k','e','s')),
phone number unique,
gender varchar2(1) check ( gender in ( 'M','F'))
);

insert into student values ( 1,'ABD','m',12345,'F');


insert into student values ( 2,'Rahuk','m',NULL,'M');
insert into student values ( 23,'Kohli','m',NULL,'M');

-- example of default constraint


-- If value is not passed in insert , Default values is consider instead of NULL
--if we pass value to default columns , it overwrites default value

drop table student;


create table student
(
rollnum number primary key,
sname varchar2(50) not null,
subject varchar2(10) check ( subject in( 'm','k','e','s')),
phone number unique,
gender varchar2(1) check ( gender in ( 'M','F')),
DOJ date default sysdate
);

insert into student(rollnum,sname,subject,phone, gender)


values ( 1,'ABD','m',12345,'M');
insert into student values ( 2,'Rahuk','m',NULL,'M', sysdate +1);

select * from student;

create table test


(
id number primary key,
phone number primary key,
name varchar2(10)
);

*** candidate key : potential key for PK


** table must be hvae only one PK and can hve multiple UK

create table test


(
id number primary key,
phone number unique,
name varchar2(10) unique
);

**** composite keys


** constraint can be defined on multiple columns
** table level constraint

** Primary : not null + unique

create table student


(
rollnum number primary key,
first_name varchar2(10),
last_name varchar2(10),
constraint name_uk unique(first_name,last_name)
);

insert into student values(1,'vinay','kumar');


insert into student values(2,'vinay','A');

-- invalid dup on fn+ln


insert into student values(3,'vinay','A');

insert into student values(4,'vinay',NULL);


insert into student values(5,NULL,NULL);
insert into student values(6,NULL,NULL);

FN LN
--------
vinay kumar
vinay alabur

-- drop table student;


** aditinal PK : not null + unique
create table student
(
rollnum number primary key,
first_name varchar2(10) not null,
last_name varchar2(10),
constraint name_uk unique(first_name)
);
insert into student values(1,'sachin', 'kumar');

-- invalid
insert into student values(2,'sachin', 'kumar');
insert into student values(2,NULL, 'kumar');

-- example of conposite PK

drop table student;


create table student
(
first_name varchar2(10) ,
last_name varchar2(10),
constraint name_PK primary key (first_name , last_name)
);
insert into student values('a', 'b');
insert into student values('a', 'c');

-- 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)

1st BF leads into Reduendent : Duplicate date

2nd Normal Form


It is should be 1st Normal Form
** All attributes ( Non Key columns ) must be depedent on the primary key
** if any Non Dependent columns must be moved into another table

** Data in each table can be managed/ operate independently

3rd Normal Form


It should be in the Second Normal form.
** And it should not have Transitive Dependency.

*** Foreign key

create table student


(
sid number primary key,
sname varchar2(10) not null,
email varchar2(10) unique,
phone varchar2(10) not null,
constraint uk_phone unique(phone)
);
alter table student modify email varchar2(20);

insert into student values(1,'Neeraj' , '[email protected]', 12345);


insert into student values(2,'Meeraj' , '[email protected]', 56789);

create table subject


(
slno number primary key,
sid number references student(sid),
subject varchar2(1),
score number check ( score > 0 and score < 100)
);

insert into subject ( 1, 1,'K', 60);


insert into subject values ( 1, 1,'K', 60);
insert into subject values ( 2, 1,'E', 60);
insert into subject values ( 3, 1,'M', 90);

-- invalid FK violation
insert into subject values ( 4, 3,'M', 90);
select * from subject;

create table student


(
rollnum number not null,
name varchar2(10) ,
gender varchar2(1),
dob date
);

select * from student;


**** how do we see structure of table
describe student;

insert into student values(1,'Sachin' , 'M', sysdate);


-- date : dd-mon-yyyy
insert into student values(2, 'Deepu' , null , '01-jan-2022' );
insert into student values(3, null, null, null );
insert into student(rollnum , name) values ( 4,'Vinay');

-- subsitute value should be of same dataType of colum Type


select
nvl(rollnum ,'No Roll num'),
nvl(name,'No Name') ,
nvl(gender, '1')
from student;

compitable data type convertion


number == > char ( yes ) 123 ==> '123'
char == > number (No) '$'

******************************
-- Psudo columns : rownum , rowid
-- Fetch top / bottom records

-- copy table from exisiting table along with data


-- create table as select CTAS
create table emp_backup as select * from emp;
select * from emp_backup;

-- removing all rows using delet


delete from emp_backup;
rollback;

-- drop table : will remove table as well as data


drop table emp_backup;
-- copy table from exisiting table with NO data
-- only strucutre , no data
create table emp_backup
as select * from emp where 1=2;
select * from emp_backup;

create table emp_backup2


as select * from emp where null=null;
select * from emp_backup2;

-------------- crate table with only requried data


create table empdeptno10
as select * from emp where deptno=10;
select * from empdeptno10;

------- Psudo columns


-- rowuum is psudo column
-- indicates, order in which records are fetched from table
-- rownum is always starts with 1 and increment by 1 after each record fetched from
table
-- if reocrds are not fetched , rownum will not increment
select rownum, ename,job from emp;
select rownum, ename , deptno from emp where deptno=30;

select rownum , e.* from emp e where rownum <=5;


-- step 1 rownum 1 : where 1<=5 --- True
-- step 2 rownum 2 : where 2<=5 --- True
-- step 5 rownum 5 : where 5<=5 --- True
-- step 6 rownum 6 : where 6<=5 --- False rownum ==> 6

-- fetch only first record


select rownum , e.* from emp e where rownum =1 ;

-- fetch only Three record


select rownum , e.* from emp e where rownum <= 3;

-- no recods wil be fetched


select rownum , e.* from emp e where rownum = 3;

-- create table with just 10 records


-- rownum =10 SHOULD NOT BE USED
create table emp11
as select * from emp where rownum <=10;

--- rowid
-- it represents address of record with in table
-- record inserted first will have min rowid and last will have max of rowid

-- record insert first in table


select * from emp
where rowid = ( select min(rowid) from emp );

-- record insert last in the max


select * from emp
where rowid = ( select max(rowid) from emp);

-- 2nd last record inserted in the table


select * from emp where rowid =
(
select max(rowid) from emp
where rowid < ( select max(rowid) from emp)
);

-- 2nd max salary


select max(sal) from emp where sal <
(
select max(sal) from emp
);

-- person taking 2nd max salary


select * from emp where sal=
(
select max(sal) from emp where sal <
(
select max(sal) from emp
)
);

-- limit : mysql
-- top : sql server
-- fetch first 3 rows only : oracle

-- what is the max sal of emp


select max(sal) from emp;

-- emp taking max salary


select * from emp where sal = ( select max(sal) from emp);

-- get top 5 salaries of emp table


select * from emp
order by sal desc
fetch first 5 rows only;

-- get low 5 salaries of emp table


select * from emp
order by sal
fetch first 5 rows only;

--- get 5th max salary


-- 5TH LOWEST SALARY
select * from emp
order by sal asc
offset 4 rows fetch first 1 row only;

-- 5th , 6th LOWEST SALARY


select * from emp
order by sal asc
offset 4 rows fetch first 2 row only;
-- first 3 records
select * from emp
order by rowid asc
fetch first 3 rows only;

-- last 3 records
select * from emp
order by rowid desc
fetch first 3 rows only;

-- 2nd max sal using the offset


select * from emp
order by sal desc
offset 1 rows fetch first 1 rows only;

--- set operators

create table deptsales( empid int);

insert all
into deptsales values(1)
into deptsales values(2)
into deptsales values(3)
select * from dual;

create table deptmarketing( empid int);

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

-- union all gives combained output of 2 selects : ** with duplicate **

select empid from deptsales


union all
select empid from deptmarketing;

1
2
3
1
2
5
7

-- union v/s unionall


no duplicate with duplicate
slow faster ( does not check duplicate values)

-- 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;

select empid from deptmarketing


minus
select empid from deptsales;

---------- More examples

student arts music


-------- ----------------- ----------
sid sid sid
1 1 1
2 2
3 3
4
5 5
6 6 6
7
8 8
9 9
10

-- students joined for both arts and music class(1,6)


-- student joined only for arts ( 3,8)
-- student joined only for music ( 2,5,9)
-- student joined for either arts or muisc( 1,2,3,5,6,8,9)
-- student not Joined for any clas ( 4,7,10)

--- interview question

create table test ( id int);


insert into test
select level from dual connect by level<=10

------ 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%';

--- find names having 5 char and having A


select * from emp where length(ename)=5 and ename like '%A%';

ename like '%A'

Ename return
A yes
aA yes
bbA yes
AbbA yes
bAbA yes
abba No

ename like 'A%'

Ename return
A Yes
aA no
bbA no
AbbA Yes
bAbA No
abba No

-- _ represents must any one char

-- A in the 2nd place


select * from emp where ename like '_A%';

-- A in 3rd place
select * from emp where ename like '__A%';
select * from emp where substr(ename,3,1) ='A';

-- 3rd last char shuld be A


select * from emp where ename like '%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

upper(substr(name, -5,1)) ='N'


return
ignited yes
IgNited yes
IGNITED yes

select 'emp name is ' || ename from emp;


select 'emp name is ' || ename || ' working for job ' || job from emp;

------ sub quries

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');

-- deptno does having any emp


select * from dept where deptno not in ( select deptno from emp);

-- find all emp having same manager as of FORD


select * from emp where mgr=(
select mgr from emp where ename ='FORD')

--- find all emp working in same deptno of MILLER


SELECT * FROM EMP WHERE DEPTNO = (
select deptno from emp where ename ='MILLER')

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

-- total number for customer in each city


-- city having only one custmer
-- total order placed for date 12-DEC-2022
-- total items sold for every day
-- order details placed by custenr uuu on 13-dec-2022
-- total order placed by each city

-- using sub quries


customer who placed item milk
customer belong to BANG and not placed milk
customer not bought any item ( usign sub query and joins)

---- normalization

----- where v/s having

------- views

----- Any All

You might also like