Simple SQL Notes
Simple SQL Notes
Data Base- Collection of related records and store the data in the form of tables which consists of rows and columns.
Creating user steps
->Alter session set “_oracle_script”=true;
->Create user Raj identified by 123456;
->Grant connect, resource to Raj;
Change password of user
->Alter user Raj identified by 1234;
Dropping user steps
->revoke connect, resource from Raj;
->Drop user Raj;
Mainly SQL divided into 5 types
1.DDL (Data Definition language) These are implicit commands no need to commit – Create, Alter, Drop, Truncate,
Rename.
2.DML (Data Manipulation language) These are explicit commands so we must commit – Insert, Update, Delete.
3.TCL (Transaction control language) – Commit, Rollback, Savepoint.
4.DQL/DRL (Data query language/Data Retrieval language) – Select.
5.DCL (Data control language) – Grant, Revoke.
1.DDL commands: -
->Create table emp (empno number, ename varchar2(50), doj date);
->Alter table emp add (sal number (10,2));
Alter table emp modify (sal number (16,2));
Alter table emp drop(sal);
Alter table emp Rename column sal to salary;
->Drop table emp;
->Truncate table emp;
->Rename emp to employee;
2.DML commands: -
->Insert into emp values(101,’kamal’,’04-Jun-2021’,20000);
Insert into emo (empno, ename) values (101,’kamal’);
->Update emp set sal=10000 where empno=101;
Update emp set ename=’kamalraj’ where empno=101;
->Delete from emp where empno=102;
5. DCL commands: -
->Grant select, insert on emp to Raj;
Grant All on emp to Raj; All means (all commands)
Grant All on emp to public;
Grant insert (empno, ename) on emp to Raj;
->Revoke All on emp from Public;
Revoke insert on emp from Raj, system;
Revoke select, insert, delete, update on emp from raj;
Date base Objects
1.Table – it is used to store the data in the form of rows and columns
2.View – logically represents subsets of data from one or more tables
3.Sequence – It is used to generate primary key values or auto numeric values
4.Index – It is used to improve performance of some queries
5.Synonym – Used to give alternate name of object or table
1|Page
CHAPTER 1-Table
Table restrictions
Table name must be unique in database
Table name should start with letter and can be 1 to 30 characters long only
Max 1000 column allowed in a table
Table names not case sensitive
Column restrictions
Column name should start with letter and can be 1 to 30 characters long only
Column name must be unique in Table
NVL2 function nvl(exp1, exp2, exp3) if exp1 is null it written exp3 , otherwise it written exp2.
Select nvl2(comm,100,200) from emp;
3|Page
Select RPAD (ename,20.’@’) from emp; it displays adding @ to right side of ename to reach char length as
20
Select LTRIM (ename, ’K’) from emp; it displays trim letter K from left side of ename
Select RLTRIM (ename, ’K’) from emp; it displays trim letter K from right side of ename
Select ename, TRIM (leading/trailing/both ‘K’ from ename) from emp; leading means 1 st letter, trailing
means last letter
Select ename, REPLACE (ename, ‘LA’, ‘KP’) from emp; it replays Letter LA with Letter KP in ename
Select ename, TRANSLATE (ename, ‘LA’, ‘KP’) from emp; it translates letter L with K and A with P in ename
Select CHR (65) from dual; it displays character of that given number
Select ASCII (A) from dual; it displays binary equallant number of that character
Number function
Select ROUND (19.655,2), ROUND (126.11, -2) from dual; it displays result as 19.66,100
Select TRUNC (19.655,2), TRUNC (126.11, -2) from dual; it displays result as 19.65,100
Select CEIL (19.001), CEIL (19), CEIL (-19.561) from dual; it displays result as 20,19,-19
Select FLOOR (19.001), FLOOR (19), FLOOR (-19.561) from dual; it displays result as 19,19,-20
Select MOD (100,10), MOD (100,12) from dual; it displays result as 0,4
Select POWER (5,2) from dual; it displays result as 25
Select SQRT (25) from dual; it displays result as 5
Select ABS (-36), ABS (0.51), ABS (15) from dual; it displays result as 36,0.51,15
Select SIGN (10), SIGN (-10) from dual; it displays result as +1, -1
Date function
Select sysdate, sysdate+1, sysdate-1, sysdate+1/24, sysdate-1/24 from dual; it displays as +1 result next date,
-1 result previous date, +1/24 result same date after one hour, -2/24 result same date before two hours
Select sysdate, ADD_MONTHS (sysdate, 2) from dual; it displays adding two months to sysdate
Select MONTHS_BETWEEN (to_date(’05-JAN-2021’), sysdate) from dual; it displays how many months
between two dates
Select NEXT_DAY (sysdate, ‘TUE’) from dual; it displays next date of given week day
Select LAST_DAY (sysdate) from dual; it displays last date of given date in the month
Select sysdate, ROUND (sysdate, ‘day’), ROUND (sysdate, ‘mon’), ROUND (sysdate, ‘year’) from dual; day
result week start date, mon result month starting date, year result year starting date for the given sysdate.
Note: -For day if sysdate is from thu it displays next week start date, for mon is sysdate is from 16th it
displays next month start date, for year if sysdate is from jul it displays next year start date.
Select sysdate, TRUNC (sysdate, ‘day’), TRUNC (sysdate, ‘mon’), TRUNC (sysdate, ‘year’) from dual; day result
week start date, mon result month starting date, year result year starting date for the given sysdate.
Conversion function
1.Number functions note: - no of 9’s should be equal to given number
Select to_char (1234,’9999D99’) from dual; it results as 1234.00
Select to_char (1234,’9.9EEEE’) from dual; it results as 1.2E+03, means scientific notation form of 1234
Select to_char (1234,’9G999’) from dual; it results 1,234
Select to_char (1234,’L9999’) from dual; it results $1234, means local currency
Select to_char (-1234,’9999MI’) from dual; it results 1234-, displays ‘– ‘symbol last position
Select to_char (-1234,’9999PR’) from dual; it results <1234>, displays -ve no between ‘<>’
Select to_char (10,’RN’), to_char (10,’rn’) from dual; it results X, x , means roman indicator of given number
Select to_char (10,’S99’), to_char(-10,’S99’), to_char (10,’99S’), to_char(-10,’99S’) from dual; it results +10,
-10, 10+, 10- , means sign indicator
Select to_char (10,’XX’) from dual; it results A, means hexa decimal value for that given number
Select to_char (105,’0999’) from dual; it results 0105
Select to_char (100-10,’999’), to_char (100-110,’999’) from dual; it results 90, -10
Select to_char (10,’C99’) from dual; it results USD10, means ISO currency indicator
4|Page
2.Date functions
Select to_char (sysdate, ‘AD’) from dual; it displays AD, means AD or BC indicator
Select to_char (sysdate, ‘AM’) from dual; it displays PM, means AM or PM indicator
Select to_char (sysdate, ‘CC’) from dual; it displays 21, means century indicator
Select to_char (sysdate, ‘D’) from dual; it displays numeric week day indicator starting from sun like 1
Select to_char (sysdate, ‘DAY’) from dual; it results full spelling of a day like SUNDAY
Select to_char (sysdate, ‘DD’) from dual; it results date part of given date
Select to_char (sysdate, ‘DDD’) from dual; it results no of days counting from jan 1 st
Select to_char (sysdate, ‘DY’) from dual; it results abbreviated week day like SUN
Select to_char (sysdate, ‘IW’) from dual; it results no of weeks counting from jan 1 st
Select to_char (sysdate, ‘YYYY’) from dual; it results year part from given date like 2021
Select to_char (sysdate, ‘YEAR’) from dual; it results full spelling of the year like twenty twenty-one
Select to_char (sysdate, ‘W’) from dual; it results week no of the given date like 1
Select to_char (sysdate, ‘WW’) from dual; it results week no from jan 1 st like 12
Note: - ‘WW’ displays normal week day from calendar, ‘IW’ displays ISO standard week day
Select to_char (sysdate, ‘Q’) from dual; it results ISO standard quarter no
Select to_char (sysdate, ‘J’) from dual; it calculates no days from jan 14 th 712 BC
Select to_char (sysdate, ‘MM’) from dual; it results numeric month like 6
Select to_char (sysdate, ‘MON’) from dual; it results abbreviated month like JUN
Select to_char (sysdate, ‘HH12’), to_char(sysdate,’HH24’) from dual; it results 9, 21, means hour no
Select to_char (sysdate, ‘MI’) from dual; it results minutes indicator
Select to_char (sysdate, ‘SS’) from dual; it results seconds indicator
Select to_char (sysdate, ‘RM’) from dual; it results roman month indicator like VI
Select to_char (sysdate, ‘DDTH-MON-YEAR’) from dual; it results 5 th-JUN -TWENTY TWENTY-ONE
Select to_char (sysdate, ‘DDTHSP-MON-YEAR’) from dual; it results FIFTH-JUN -TWENTY TWENTY-ONE
Select to_char (sysdate, ‘DDTHSPFM-MON-YEAR’) from dual; it results 5 th-JUN-TWENTY TWENTY-ONE, means
it removes blank spaces
Select to_char (sysdate, ‘JSP’) from dual; it results spelled Julien day
Integrity constraints or Data constraints
Types
1.NOT NULL
2.UNIQUE
3.PRIMARY KEY
4.DEFAULT
5.CHECK
6.FORIEGN KEY OR REFERENCIAL INTEGRITY
1.NOT NULL: - Data must enter and duplicate values allowed
Create table student (Sno number constraint Sno_NN NOT NULL);
2.UNIQUE: -no duplicate value allowed and null value allowed
Column level
Create table student (Sno number constraint Sno_UNQ UNIQUE);
Table level
Create table student (Sno number, Name varchar2(100), constraint Sno_NM_UNQ UNIQUE (Sno, Name));
3.PRIMARY KEY: -It will not accept null, duplicate values. Only one Primary key allowed on one table
Column level
Create table student (Sno number constraint Sno_PK PRIMARY KEY);
Table level
Create table student (Sno number, Name varchar2(100), constraint Sno_NM_PK PRIMARY KEY (Sno, Name));
4.DEFAULT: -
Create table student (Sno number, J_Date date constraint JOD_DF DEFAULT sysdate);
5|Page
5.CHECK: -
Create table student (Sno number constraint Sno_PK PRIMARY KEY constraint Sno_chk CHECK (Sno between
10 and 50), Location varchar2(50) constraint loc_def DEFAULT ‘HYDERABAD’ constraint loc_chk CHECK
Location in(‘HYDERABAD’,’GUNTUR’,’VIJAYAWADA’));
6.FORIEGN KEY: -
ON DELETE CASCADE: -Remove child table record automatically when parent table record is removed
ON DELETE SET NULL: -When parent table record is removed then child table record values as set null
Create table emp (deptno number constraint dn_fk references dept(deptno) ON DELETE CASCADE);
ADDING CONSTRAINT TO EXISTING TABLE
NOT NULL, DEFAULT constraints can be added by using alter …. Modify clause
Remaining all constraints can be added by using alter …. Add clause
Alter table student add constraint Sno_pk PRIMARY KEY (Sno));
Alter table student modify Sname constraint snm_nn NOT NULL;
Note:- cascade option in the drop clause is used to drop any of the dependent constraints if available
DROPPING CONSTRAINT
Alter table student drop constraint Sno_pk CASCADE;
Alter table student drop PRIMARY KEY;
Alter table student drop UNIQUE (Sno);
DISABLE CONSTRAINT
Alter table student disable constraint Sno_pk CASCADE;
ENABLE CONSTRAINT
Alter table student enable constraint Sno_pk;
TO CHECK CONSTRAINT ON A TABLE
Select * from user_constraints;
Select * from user_constraints where table_name=’student’;
Select * from user_cons_columns where table_name=’student’;
JOINS
It is used to join rows in one table to rows in another table.
Join condition we will use in where clause
If join involves more than one table oracle 1st joins 1st two tables based on condition and then compare the result
with next table and so on.
Using table alias names in join, ex: - Select * from emp e, dept d where e.deptno=d.deptno;
Types of joins
1.EQUI JOIN
2.INNER JOIN
3.NON EQUI JOIN
4.SELF JOIN
5.CARTESIAN JOIN OR CROSS JOIN OR CARTESIAN PRODUCT
6.OUTER JOIN
7.NATURAL JOIN
1.EQUI JOIN
Based on equality condition tables are joined, only matching records are displayed, to join tables both the
tables must have at least one common col with same datatype and same values but col name may be
different.
Select * from emp e, dept d where e.deptno=d.deptno;
2.INNER JOIN
Inner join will also work as same as equi join.
We use on clause for inner join
Select * from emp e inner join dept d on (e.deptno=d.deptno);
select * from emp e inner join dept d on (e.deptno=d.deptno)inner join salgrade s on (e.sal between s.LOSAL
and s.HISAL);
6|Page
3.NON EQUI JOIN
Non equi join is making by relational operator other than ‘=’
It is used to join tables If values of one column of a table falls the range between column of another table
It is used between operator so it is called between join.
Select * from emp e, salgrade s where e.sal between s.LOSAL and s.HISAL;
4.SELF JOIN
It can joins the table it self
The table alias names must use in join condition
A table contain two col with same datatype and same values then self join used.
select e.empno, e.ename "EMP NAME", m.empno "MGR NO", m.ename "MGR NAME", e.deptno from emp
e, emp m where e.mgr=m.empno and e.deptno=20;
5. CARTESIAN JOIN OR CROSS JOIN OR CARTESIAN PRODUCT
It results all combination of rows will be join between two tables.
This will be done by either omitting where clause or specify cross join clause.
Select * from emp, dept;
Select * from emp cross join dept cross join salgrade;
6.OUTER JOIN
It is used to retrieve all rows from one table but matching rows from another table.
It uses operator (+) to join tables.
(+) appear only in where clause.
These are three types
a) LEFT OUTER JOIN
b) RIGHT OUTER JOIN
c) FULL OUTER JOIN
a). LEFT OUTER JOIN
It results all rows from left table but matching records from right table.
Select * from emp e left join dept d on e.deptno=d.deptno;
select * from emp e, dept d where e.deptno=d.deptno(+);
b). RIGHT OUTER JOIN
It results all rows from right table but matching records from left table.
Select * from emp e right join dept d on e.deptno=d.deptno;
select * from emp e, dept d where e.deptno(+)=d.deptno;
c). FULL OUTER JOIN
It will fetch all rows from both tables
Select * from emp e full outer join dept d on e.deptno=d.deptno;
7.NATURAL JOIN
It will work similar like equi, inner joins. It not accept alias names.
Select * from emp natural join dept;
Natural join with USING clause
select * from emp join dept using (deptno);
select * from emp join dept using (deptno) where deptno=10;
SUB QUERIES
Types of queries
1.Root query
2.Parent query or outer query or main query
3.Child query or inner query or sub query
1.Root query
The query which is not dependent on another query is called root query
Select ename, sal from emp where deptno=10;
7|Page
2.Parent query
The query which depends on any another query is called Parent query
Select ename, sal from emp where deptno=(select deptno from dept where deptno=10);
In the above ex 1st select stmt is Parent query.
3.Child query
The query which provides values to the parent query is called Child query.
The sub query in the where clause is called nested sub query, the sub query in the from clause is called inline
view.
The sub query can be part of a column in the select stmt.
Select e.ename, e.sal, e.deptno, (select dname from dept d where d.deptno=e.deptno) dname from emp e;
There is no limit the no of sub queries in the from clause, we can have up to 250 sub queries in where clause.
Select ename, sal from emp where deptno=(select deptno from dept where deptno=10);
In the above ex 2nd select stmt is sub query.
Single row sub query operators are >, =, >=, <, <=, <>
Multi row sub query operators are in, any, all
Single row sub query
Guidelines for using sub queries
Place sub query on right side of comparison operator.
Order by clause in the sub query is not needed.
Example for simple single row sub query
Select empno, ename, sal, deptno from emp where sal<(select sal from emp where empno=7566);
Apply group function in sub query
Select empno, ename, sal, deptno from emp where sal=(select max(sal) from emp);
Apply having clause in sub query
Oracle server 1st execute the sub query and it passes to having clause in main query
Select deptno, min(sal) from emp group by deptno having min(sal)>(select min(sal) from emp where
deptno=20);
Sub query with update statement
Update emp set deptno=(select deptno from emp where empno=7521) where ename=’SADA’;
Sub query with delete statement
Delete from emp where sal =(select sal from emp where empno=7369);
Multi row sub query
IN: - it means equal to any row in sub query
Select ename, sal, deptno from emp where sal in (select max(sal) from emp group by deptno);
SOME/ANY: - compare the value to each value obtain by sub query
‘<any/some’ means less than the max value in the list
‘>any/some’ means greater than the min value in the list
select ename, sal, deptno from emp where sal<some (1250,1500,1600);
select ename, sal, deptno from emp where sal>any (select sal from emp where sal<1600);
ALL: - compare the value to each value obtain by sub query
‘<ALL’ means less than the min value in the list
‘>ALL’ means greater than the max value in the list
select ename, sal, deptno from emp where sal<ALL (select sal from emp where sal>1600);
select ename, sal, deptno from emp where sal>ALL (select sal from emp where sal<1600);
Sub query writing with multiple columns
Multiple columns can compare in the where clause by using logical operators.
Types
1.Pair wise comparison: -
Each row in the select statement must have both same values associated with each column in the group.
8|Page
Select ename, sal, deptno from emp where (deptno, sal) in (select deptno, max(sal) from emp group by
deptno) and deptno<>10;
2.Non Pair wise comparison: -
Each row in the select statement must match multiple conditions in the where clause but the values are
compared individually.
Select ename, sal, deptno from emp where deptno in (select deptno from emp group by deptno) and sal in
(select max(sal) from emp group by deptno) and deptno<>10;
Apply sub query in from clause
It is equal to a VIEW and it is called inline view.
Select d.deptno, d.dname, v.vcnt from dept d, (select deptno, count(*) vcnt from emp group by deptno) v
where d.deptno=v.deptno;
Sub select statement
Select ename, sal, (select max(sal) from emp) from emp;
Co related sub query
In this parent query processed 1st and passes the qualified column values to sub query in where clause.
EXISTS: - it returns true if sub query is success otherwise false.
Select e.empno, e.ename, e.sal, e. job, e.deptno from emp e where deptno=10 and exists (select count(*)
from emp where deptno=e.deptno and job=’ANALYST’ group by job having count(*)<5);
Note: - if sub query is true then it written main query result, otherwise it written NULL value as result.
SET OPERATORS
A set operator combines the result of two or more queries into one result.
Queries containing set operator are called compound queries.
No of columns and datatypes of the columns being selected must be same as all select statements used in
the query and names of the columns need not be same.
Types of set operators
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
1.UNION: - it will be written all rows from multiple queries by eliminating duplicate rows if any.
Select deptno, job from emp where deptno=10 UNION Select deptno, job from emp where deptno=20;
2.UNION ALL: - it will be written all rows from multiple queries by including duplicate rows if any.
Select deptno, job from emp where deptno=10 UNION ALL Select deptno, job from emp where deptno=20;
3.INTERSECT: - it written all common rows from multiple queries
Select deptno, job from emp where deptno=10 INTERSECT Select deptno, job from emp where deptno=20;
4.MINUS: - it written rows from 1st query that are not present in the second query.
Select deptno, job from emp where deptno=10 MINUS Select deptno, job from emp where deptno=20;
PRIVILEGES
Privileges are the right or permission to execute particular SQL statements. The database administrator
(DBA) is high level user the ability to grant user access to the database and its objects.
The users use the system privileges to gain access to the database and object privileges to manipulate the
content of the objects in the database.
Users can also give privileges to grant, revoke privileges to the other user or ROLEs
Types of privileges
1.System privileges: - it allows a user to perform certain actions with in the database.
2.Object privileges: - it allows a user to perform certain actions on the database objects.
USER_TAB_PRIVS_MADE : - it will store information about privileges on schema object.
USER_COL_PRIVS_MADE : - it will store information about privileges on columns object.
9|Page
ROLEs in oracle
A role is named group of Related privileges that can be granted to user.
Advantage: - Rather than assigning privileges one by one directly to the user we can create ‘ROLE’ then
assigning all privileges to that ROLE and GRANT that ROLE to multiple users and roles.
When you add or delete privileges to that role, all users and roles assigned that role automatically receive or
loose that privileges.
A role can be assigned with password
Creating simple ROLE
Create role sales_manager;
Creating a ROLE with password
Create role sales_manager identified by salesaudit;
Here ‘salesaudit’ is password of ROLE sales_manager
To change password of a ROLE
Alter role sales_manager identified by sales;
Here password changed to sales
Grant privileges to that ROLE
Grant create table, insert table to sales_manager;
Grant ROLE to the user
Grant sales_manager to system;
Here system is one user.
Revoke privilege from a ROLE
Revoke sales_manager from system;
Dropping a ROLE
Drop role sales_manager;
10 | P a g e