Friday, March 28, 2025

SQL 36 - 40


---------------  Session 36 --------------

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

Invisible Group Function


Note :  in all relational databases we cna also use invisible group functions within having clause because whenever we are using Group func in group by clause queries then database servers internally stores all other group functions results within database.


Query to display dpeart , sum(sal) having more than 3 employye in dept


select dept, sum(sal) from employee group by dept having count(emp) >3; ---here count is invisible group func



ORDER BY CLAUSE :

========================


Order by clause is used to sorting rows either in ascending or descending order. Along with order by clause we are using 2 optional clauses. These are


ASC

DESC


By default its Asc.


select * from table order by column [asc/desc];


Note :  in order by clause we can also use alias name or expression.


select ename , sal , sal*12 annsalfrom emp order by annsal desc;


OR



select ename , sal , sal*12 annsalfrom emp order by sal*12 desc;



Order by number;


Note : in order by clause we can also use number in place of column names. But these number represents column position within select list.


select ename , sal from table order by 1;


1 means ename, sal means 2--


All databases Null value treated as highlest values.


NOte : We can also use Null value in order by clasue.In this case Null value treated as highest value if you want to control these Null value within Order by clause then oracle provided Null first / Nulls last clause along with Order by clause


Syntax :

select * from table 

order by [asc/desc][nulls first/nulls last];


select ename , comm from emp  order by comm desc;


select ename , comm from emp order by comm desc nulls last; 

                                             ==================

 

------------------- SEssion 37 ----------------

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



Note :  We can also use more than oacle sorting data based on single colne column within order by clause  but in this  case orumn. that column must be left first column within order by clause.  If that column having duplicate data then that group only sorted in second column.


select deptno, sal from emp order by deptno asc, sal desc;


Syntax of :

======================================

select columns from tbale

where condition

Group by  column names

Having Conditon

order by columnname [asc/desc];

=======================================


select deptno , count(*) 

from emp 

where sal >1000

group by deptno

having count(*)>3

order by deptno;


Order of execution of an Select statement:

==========================================

Parsing

----> Syntax

----> Semantics


Execution

====

From 

WHERE

Group BY

HAVING

SELECT

Distinct 

ORDER BY



Rollup ,  Cube :

===============


Oracle 8i introduced rollup , cube clauses. These clauses are optional clauses used along with group by clause only. These clauses are used to calculate subtotal, granttotal automatically.


Syntax :

select col1,col2.... from table group by rollup(col1, col2...);



select col1,col2.... from table group by cube(col1, col2...);


Note : whenever group by clause having single colunmn then Rollup , Cube clauses returns same result.

in this case these clauses returns Grant Total Automatically.

select  deptno, sum(sal) from emp group by rollup(deptno);

select  deptno, sum(sal) from emp group by cube(deptno);



Generally rollup is used to calculate subtotal based on a single column  at a time whereas if we want to calculate subtotal based on all grouping columns then we must use cube. In these two cases Grant total is automatically displayed.


Ex1:

select deptno, job , sum(sal)  from emp  group by rollup(deptno, job);

select deptno, job , sum(sal)  from emp  group by rollup(job,deptno);


Ex2:

select deptno,job , sum(sal)  from emp group by cube(deptno , job) order by 1,2;


---------------------------Session 38 -------------

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



Number Functions :

=================


Number func are operate over number data.


1) abs() : - It is used to convert negative sign into +ve sign.


select abs(-50) from dual; ---50


2) Mod(m,n) : - it will gives reminder after m divide by n.


select mod(10,5) form dual; ---0


it is useful to show Even row , odd row.


3)Greatest (exp1, exp2......expn) , Least (exp1, exp2.....expn) : - Greatest return maximum value among given expression whereas LEast returns minimum value among given expression.


select greatest(3,2,4,6) from dual; -----6


InOracle SQL, the LEAST function returns the smallest value from a list of expressions, but if any of the arguments are NULL, the function will return NULL. To handle NULL values and get a non-NULL result, you can use NVL.


In Oracle SQL, the GREATEST function returns NULL if any of its arguments are NULL. To handle NULL values and get the greatest non-NULL value, use COALESCE or NVL.



Round(m,n) : -It rounds gived floated value number m based on n.


select round(1.7) from dual; ----2 (above 50%)

select round(1.23456,3) from dual; -------1.234 


select round(1.23456,3) from dual; ---1.235


Execution:


Step1 :1.234 (here remainign is 56 which is above 50%(out od 100))


Step2 :1.234 added 1 in last 1.235


Round always check remaining number if remaining number is above 50% then automatically 1 added into the rounded number.



select round(1285.674,-1) from dual;


1285.674 ----1290


Execution :

step1  : 1280 ( 5  is replaced with 0.5 is above 50% out of 10 )


step 2 :

1280

+     1 

1290

select round(1485,-2) from dual ;   -2 means before decimal 2 number will be zero and those 2 number above 50% then add 1 in 3rd NUMBER



output : 1500


Trunc(m,n) : =  it truncates given floated value number m based on n it doesnot check remianing

number is above or below 50%.


select TRUNC(1.9) from dual ---1.9

select TRUNC(1.23456,3) from dual --- 1.234


Ceil() , Floor() :- These fucntions always returns integer.

Ceil return neartest greatest INTEGER

Floor returns neartest lowet integer 


ceil(1.4) ---2

floor(1.8)---1



 -- JOINS ---

 

 Joins are used to retrivedata from multiple tables.

 In all relational databases when we are joining n tables then we must use n-1 joining conditions.

 

 Oracle server having following type of joins. These are

 1)Equi join or Inner Joins

 2)Non Equi Join

 3)Self Join

 4)Outer Join

 

 THese joins are also known as  ORacle 8i joins along with these joins oracle 9i onwards oracle also supports ANSI standart joins same like all relational databases. These joins are called as 9i joins or ANSI joins

 

 9i or ANSI joins

 

 1) Inner join

 2) LEft outer join

 3)Right outer join

 4) Full outer join

 5) Natural Join

 

 

 

---------------  Session 39 --------------

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

if there is no join mention then internally oracle use Cross join LIKE

select * from table1, tbale2...........it will be cross join.


In oracle we can also retreive data from multiple tables  without using joining condition. In this case oracle internally uses default join. In Oracle default join is Cross join.

Cross Join internally works based on cartesian product.

Syntax :

select col1, col2...

from tbale1, table2...;

EQUI JOIN :

==========

Based on equallity condition ( by using equality operator )we are retriving data from multiple tables. Here joining conditional columns must belongs to same data type.

When tables having common columns then we can use EQUI Join.

Syntax:

select col1, col2...

from table1, table2....

where table1.col=table2.col;  -------this is joining condition.

select ename , deprno from

emp, dept

where emp.deptno=dept.deptno;------throw ambigous column

In all relational database when we are try to display common columns in joins then database servers returns ambiguity error. To overcome this problem for avoiding ambiguity error then we must speicify table name along with commong cloumn name by dot operator.

Syntax:

Tablename.commonvcolumnname;

Note : 

Generally for avoiding future ambiguity then we must specify tblaename along withevery column name by using dot operator within select list.

Using Alias Name: 

=================

In all relational database for improve performance of the joins then we can also use alias name within join queries that is in this case first we must create alais name ithin from clause thenonly those aliasname must be specify in place of table name within seelct list nd also within joining condition.

Syntax:

from tablename aliasname1

These table alaisname are alsocalled as referrence names fot the tables. These table aliasname must be different names.

Ex :

select ename , d.deptno from emp e, dept d

where e.deptno=d.deptno;

Note:

In oracle EQUI JOIn always returns matching rows only.


NON EQUI JOIN :

============== 

Non equi mean other than equal to like < , > , 

BAsed on other than equality operator( < , <= , >, >=, <> ,  between...)

we are  retrving data from mulitple tables.



Ex : 

select * from test1 , test2 where  test1.deptno>=test2.deptno;


Execution :  

========= 

same one value from first table compare with all value from second table.


---------------  Session 40 --------------

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


Joins means comparing VALUES 


Note : 

In oracle whenever one table one column value lies between another table 2 columnsthen also we are retreiving data from those tables by using non equi join.

In this case this join also called as Between....And join.

Ex: 

select * from emp , salgrade where sal between lowsal and hisal;

select * from emp, salgrade where sal>=losal and sal<=hisal;


EQUI Join Queries:

================== 

1) query to display employee who are wokring in the location Chicago from emp and dept tables by using Equi Join

select ename, loc from employee  e , dept d 

where e.deptno=d.deptno

d.loc='CHICAGO';


Note:

After joining condiion if you want to filter data then we must use and operator within 8i joins whereas 9i joins we are using eithere AND operator or 

we can use where clause also.

2) Query to diaplay dname , sum(sal) form emp, dept tables by using EQUI Join 

select dname , sum(sal) from employee e, dept d 

where e.deptno=d.deptno 

group by dname;

select dname , sum(sal) from employee e, dept d 

where e.deptno=d.deptno 

group by dname

having sum(sa)>9000;

3) select dname , sum(sal) from employee e, dept d 

where e.deptno=d.deptno 

group by rollup(dname)

having sum(sa)>9000;

SELF Join :

=========== 

Joining a table to itself is called self join.  Here joining conditional column must belongs to same data type.

Generally in all relational databases self joins are used in following scenarios

1) Compare one table one column any vlaue with all other values in same column.

2) Compare 2 different column values (same datatype) in same table.

Whenwver we are using self join  then we must create table alias name within from clause. These alias name must be different names. These alias name internally behaves like exact tables when query execution time.

Syntax:

from tablename aliasname , tablename aliasname2

1) Compare one table one column any vlaue with all other values in same column.

Query to display employess who are getting same salary as scott sal from employee table by using SELF JOIN

select 

from emp e1, emp e2

where e1.ename='SCOTT'

and e1.sal=e2.sal;

 

Query to display those doctors which are workginin same hospital wiht differetnt sepciality

 

from hospital h1 , hospital h3

where h1.hospitalname=h2.hostipalname

and h1.specilaity<>h2.speciality

order by h1.id;

  

SQL 31 - 35

 ---------Session 31 ---------------

Query to display employee who joining on TUESDAY using to_char() FUNCTION


select ename from employee where to_char(hiredate , 'fmDAY')='TUESDAY';


select ename from emloyee where to_char(hiredate ,'D')='3';


Note :  in oracle whenever we are using to_char() func DAY Format , internally oracle will aloocate 9 bytes maximum memory for DAY field and when we passed day less than 9 bytes then oracle will not return anything . To Overcome this we need to use FM (fill mode) whitin to_char() function.


to_char()

to_date()


Insert date into table.

================================


Note : in oracle whenever we are passing date string into oracle predefined date functions (add_months , last_day, next_day(),months_between(),

...)then we are not required to use to_date() function explicity because in this case orace internally uses implicit convertion but here passed parameter return values must match with default date format retuen values otherwise oracle returns an error.


Ex: (implicit conversion)

select last_day('18-DEC-2025' from dual);


same logic applied in insert also.


Inserting date into Oracle Date Type columns.


create table test (col1 date);


insert into test values(sysdate);

select * from test;

insert into test values('12-Decm-2005');

insert into test values(to_date('15/05/2002' ,'dd/mm/yyyy'));


Syntax :

columnname DATE


in oracle whenever we are insertin dates ito date datatype column then we are not require to use to_date() 

func when passed date reyuren values match with default date format return values because in this case oracle internally uses implicit conversion whereas in all other cases we must use to_date() function explicitly in insert statment. 


Ex:

insert into test values(to_date('15/05/2002' ,'dd/mm/yyyy'));


-----------------Session 32 ----------------------------------


v.v.v imp


ROUND()  , TRUNC() func are used in Dates : -> 

Date datatype contains data and time.


In oracle date datatype contains 2 parts these are 

1) Date Part 

2) Time Part


select to_char(hiredate,'dd-mm-yyyy HH:MM:SS' ) from employee;


Whenever we are using Round() or TRUNC() functions the date part can be changed based on time portion and also time portion is automatically set 

to zero.


Whenever we are using Round() function then oracle server check Time portion. if time portion is >=12 noon then oracle will add 1 day into the datepart and also time portion is automatically converted into zero.



Whenever we are using Trunc() func  then oracle returns same date part when time portion >=12 noon also and also here time portion is automatically converted into zeros. 


Query to display employee who joining today

insert into employee (ename, hiredate) values('a' , sysdate);


select * from employee where horedate=sysdate;

No RECORD


In oracle whenever we are comparing date by using equality operator in where clause then oracle doesnot return proper result because whenever we are comparing dates by using equality operator then oracle server not only compares date part but also internally compares time part.

To overcome this problem if we want to retrieve proper result then we must set time portion to zeros by using Trunc() function.


select * from employee where trunc(hiredate)=trunc(sysdate);


Note : In this case we can also retrive data by using to_date() function without using trunc() function.


select * from employee 



Note:  In oracle whenever we are inserting sysdate into date datatype column then oracle internally automatically insert current time of the system whereas whenever we are inserting our own date by using to_date() without specifiying any  time then oracle internally automatically 

insert 0s (00:00:00) hour,min, sec. 

Whenever we are inserting time without specifing any date by usnig to_date() then oracle automatically inserts first date of the current month.



-------------    Session 33  ---------------


Note : in oracle by usin round(), trunc() func we can also display first date of the year, first date of the month by using following syntax.


Syntax :

round(date,'year')

round(date,'month')


trunc(date, 'year')

trunc(date, 'month')


select sysdate , round(sysdate+200,'year'),trunc(sysdate,'year') from dual;

14-03-25 01-01-26 01-01-25

day means first day of week.

round() will always prev or next based on date above 50% then next else prev.


Ex:  Sysdate 17-09-2021


select trunc(sysdate, 'year') from dual;---01-Jan-2021


select trunc(sysdate, 'month') from dual;---01-Sep-2021

select trunc(sysdate, 'day') from dual;---12 Sep 2021 (prev sunday)


5 date func --sysdate, add_month(), last_day() , next_day() , months_between()


Next_day() : It returns next occurence day from the specified date based on the second parameter.


Syntax: 

next_day(date,'day')


select next_day(sysdate,'Friday') from dual;

select next_day(sysdate,'wed') from dual;


Months_Between() : -- Returns number


syntax:

Months_between(date1,date2)

date1>date2 --> POSITIVE

date1<date2 -->Negative  -- we can use abosule to convert negative to positive.


it reutrns number datatype. it returns number of months between given 2 dates  here date1 must be greater than date2 oterwise this function returns negative sign.


If day of date1> day of date2  === > date1-date2/31

if day< date2  ===> (31-date1+date2)


select months_between('13-Dec-08','12-Mar-08') from dual ---9.03225

select round(months_between('13-Dec-08','12-Mar-08') ) from dual; ---9


select round(months_between(sysdate, hiredate)) from dual;


BEfore Group by we have to understand Group Functions.



Group Functions or Aggregate Functions :

======================================== 

Oracle having following func

1)max()

2)min()

3)sum()

4)avg()

5)count(*)

6)count(columnname)


Generally Group functions are operate over number of values in a table column and also returns single value.  


max() : 


max(1,2,3,4)-----wrong it take column name from table

It returns maximum value from a table column

select max(sal) from emp;


It will work on number, string , dates also.


Min():

it will also work in number, date , string.

 

 

 Group func direclty wont work in where.

 select * from table where sal=min(Sal)----wrong

 

 Avg: it returns avg from number datatype column.

 In avg will it count that ROWS.It ignores null values.

 select avg(Sal) from emp;

 

select avg(nvl(comm)) from emp;


In oracle by defalut all group function ignores Null values except count(*). If we want to count Null values in group functionthen we must use NUL() func.



sum() :  it returns total from number datatype column.


select sum(sal) from emp;



------------------ Session 34--------------

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




Count(*) :  It counts number of rows in table.

=========

select count(*) from table;


count(Columnname) : It counts number of not null values from table column.

==================

select count(*) from emp; ----14

select count(comm) from emp; ----4


Note: if we want to count number of distinct values from a table column then we can also use distinct caluse within count function.


select count(distinct deplno) from emp;-----3


Group by Clause:

=================


Group by caluse is used to divide similar data items into set of logical groups. i.e group by clause automatically reduces number of rows in each group.

This group by clause is used in select statement. 


Syntax: 


select columnname 

from table 

group by columnname;


Query to displaynumber of employee  in each department from table.

select deptno , count(*) from emp group by deptno.


Query to display no.of employee in each job

select job ,count(*) from emp group by job;



First Rule:

Note :  in all relational databases we can also use group by clause without using group functions.


Without using group fucn we cn use Group by.

select  job from employee group by job;



Note: Other than group Function columns specified after select then those all columns must be specify after 

group by clause otherwise oracle returns an error not a group by expression. 


select ename , job, sum(sal) from emp group by ename,job;


select ename, job from emp group by ename , job;


---------------  Session 35 --------------

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


Group By  Clause Execution : 

===============================

Whenever we are submitting group by clause into oracle server then oracle firstselects specified columns from group by clause and then only it returns similar data items into set of groups from that columns and also it reduces  number of rows in each group and then this result internally stored in result set table. Then only oracle server retreve select list specified columns from this result set table.


select deptno from emp group by deptno;


Execution Process:


STEP1: group by deptno;

deptno

10

20

30

10

20

10

20

30


Result set table.

10

20

30


STEP2: 

select deptno from result table.

deptno

10

20

30


Note : in all relational databases wheenever we are try to display group functions along with aonther columns 

then database servers returns an error to overcome this problem then we must use group by clause.


Step1 :

select sum(sal) from emp;


Step2:

select deptno, sum(sal) from emp;

Error : not a single group func


Solution:


select deptno, sum(sal) from emp group by deptno;


Group func works on all data other column work on row wise.


Query to display those departments  having more than 3 employee by  using group by

select deptno, count(*) from emp group by deptno where count(*)>3;--------Wrong


Solu :

select deptno, count(*) from emp group by deptno having count(*)>3;



Having CLause: 

=============  After group by clause we are not allowed to use where clause in place of this one ANSI/ISO sql provided another clause Having.

Generally if you want to restrict rows in a table then we are using where clause whereas if you want to restrict group after Group by clause then we must use having clause.



select deptno,sum(sal) from employee group by ename;-wrong  



Generally we are not allowed to use group function in where clause whereas we can also use group functions in having clause.


Query to display those dept sum(sal)having 9000 by using group by clause.  

select deptno, sum(sal) from emp group by deptno having sum(sal)>9000;


Query to dislay year and number of empl joining for year in which more than 1 emp washired from emp table using froup by clause.


select extract(year from hiredate) , count(*) from emp group by extract(year from hiredate)

having count(*)>1;

select to_char(hiredate,'yyyy') , count(*) from emp group by  to_char(hiredate,'yyyy')

having count(*)>1;


Can we use alias name in group by caluse not even in where clause --- not possible 

select to_char(hiredate,'yyyy') 'year' , count(*) from emp group by year ----wrong

having count(*)>1;






DOnot use * with group  by clause.



































 


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

SQL 

SESSION 38 Join Started


Join : are used to retrieve data from multiple tables.

In all relational databased when we are joining N tables then we must use N-1 Joining Conditins.

Oracle Server having following types of joins. These are

1) Equi Join or Inner Join

2) Non Equi Join 

3) Self Join

4) Outer Join

These joins are also called as oracle 8i joins. Along with these joins Oracle 9i onwards

oracle also supports ANSI standard joins same like all relational databases. These joins are also called as 9i joins or ANSI joins.

9i joins or ANSI joins

=======================

1) Inner Join

2) LEft OUTER Join   ---OUTER is optional here

3) RIGHT OUTER Join

4) FULL Outer Join

5) Natural Join

In Oracle we can retrieve data from multiple table without using Joining condition.

In that case oracle server internally uses default join and default join is CROSS Join (CARTESIAN PRODUCT)

select col1, col2 from table1 , table2.....;

EQUI JOIN :

============= Based on equality condition (by using equality operator). We are retrieving data from multiple table. Joining conditional columns must have same data type.


Syntax :

select col1, col2                        -----Ex.ecuting 3

from table1 , table2                          ----Executing 1

where table1.commoncol = table2.commoncolname;  ----Executing 2

Ambiguity Error: It is recommened while fetching column use table name like tablename.colname.


In all relationaldb for improvePerformance of the joins then we can also use alias name within join querys.in join condition also use table alias name.

Non Equi Join :

================  Based on other than equality operator (< , <= , >, >=, between,...) we are retriving from multiple tables.




------- SESSION 40 ----------

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


Note :  After Joining condition if you want to filter data then we must use AND operator with in 8i joins whereas in 9i joins we are using either AND operators or where clause.


select  columns from emp , dept where emp.=dept. 

and condition;


Pseudo Columns in Oracle