SQL Notes
SQL Notes
Database:
It is a collection of "related and meaningful information" stored centrally at one location.
Field :
Each column in a table is called a Field or collection of related data is called a Field.
Record :
Each row in a table is called Record or collection of related fields are called Record.
SQL:
→ SQL stands for structured query language.
→ SQL was initially developed at IBM in 1970's.
→ SQL is an open source anybody can use free of cost.
→ It's pronounced as S.Q.L/sequel
→ It is a language which is used to communicate with the Relational database management systems like ORACLE,MS ACCESS,MS
SQL SERVER,MY SQL,DB2(IBM),SYBASE etc.
→ SQL is a standard language designed for accessing and managing data in relational database management systems.
→ It is used for accessing and manipulating databases such as insert,update,delete and SELECT
→ SQL is a nonprocedural language.
→ SQL is a not case sensitive language.
Query:
→ A query is a request for data or information from a database table or combination of tables.
→ Queries are used to tell what we require from the database.
to view all column information of a particular table then we use the "user_tab_columns" data dictionary.
to view a logical condition of check constraint then we need to call the "search_condition" column from "user_constraints"
data dictionary.
- if we want to view the constraint name along with the column name of a particular table then we use the "
user_cons_columns " data dictionary.
where object_type='table' and object_name='EMP'; → (always use capital inside single quote to get the data)
COMPONENTS OF SQL:
DDL
DML
DQL/DRL
TCL
DCL
Data Types:
It is used to represent what type of information is stored into the column.(What type of data you need to maintain in a column).
<col_name> CHAR(<SIZE>)
→Maximum size is 2000 byte/2000 char.
→ Default size is one byte.
→ it uses defined size irrespective of the characters we provided.
<col_name> VARCHAR2(<SIZE>)
→ Maximum size is 4000 byte/4000 char.
→ size is mandatory.
LONG DATATYPE
<col_name> long
→ It is used to represent characters or numbers.
→ Max size is 2gb
→ Only one LONG column is allowed per table.
→ LONG columns are not allowed in the WHERE clause.
DATE DATATYPES
<col_name> date
→ It is used to represent date and time information but time is optional.
→ the default date format in oracle is dd-mon-yy/dd-mon-yyyy
→ range of date datatypes is from "01-JAN-4712 BC " TO "31-DEC-9999 AD ".
Interview point
A Literal is a string that can contain a character, a number, or a date that is included in the SELECT list and that is not a column name or a
column alias. Date and character literals must be enclosed within single quotation marks (‘ ‘), number literals need not.
For exp: Select last_name||’ is a’|| job_id As “emp details” from the employee; (Here “is a” is a literal).
Blob Clob
The full form of Blob is a Binary Large Object. The full form of Clob is Character Large Object.
This is used to store large binary data. This is used to store large textual data.
This stores values in the form of binary This stores values in the form of character streams.
streams.
Using this you can store files like videos, Using this you can store files like text files, PDF
images, gifs, and audio files. documents, word documents etc.
create:
➢ it is used to create new database objects.
➢ While creating a table we provide the basic information for each column together with their data type and size.
syntax:
*******
create table tablename
(
column_name datatype(size),
column_name datatype(size),
column_name datatype(size),
............................,
.........................,
column name datatype(size)
);
➢ Once the table is created, we will receive a message "table created".
➢ if the same table name already exists in the database, then we will not be allowed to create a table again.
create table EMP(
empno number,
ename varchar2(10),
job varchar2(10),
mgr varchar2(10),
hiredate date,
sal number,
comm number,
deptno number
);
deptno number,
dname varchar2(10),
loc varchar2(10)
);
create table <table name> as select * from EMPwhere 1=1; (using select statement)
1=1 – true – to copy data along with table structure
1=0 – false – to copy table structure alone
Syntax :
CREATE GLOBAL TEMPORARY TABLE table_name(
column_1 data type,
Column_2 data type
)
ON COMMIT PRESERVE ROWS / ON COMMIT DELETE ROWS ;
describe/desc:
alter:
used to change the structure of the table.
once the table is successfully altered then we will receive a message saying "table altered"
add:
syntax:
*******
alter table <table_name> add <column_name> datatype <size>; → single column
alter table <tablename> add (<column_name> data type <size>, <column_name> data type <size>); → multiple columns
modify:
it is used to change or modify the structure of existing column data types and size.
it is used to modify the column in a table.
syntax:
alter table <table_name> modify (<column_name> <data type> <size>, <column_name> <data type> <size>); → multiple
columns
rename:
drop:
syntax:
alter table <tablename> drop column <columnname>; → single column
rename:
it is used to rename the table name.
syntax:
rename <old table name> to <new table_name>
drop:
it is used to drop the table permanently in the database.
syntax:
drop table <tablename>
truncate:(delete+commit)
it is used to remove all the records from the table.
data will be removed permanently in the database but not the table itself.
automatically implicit commit will be fired.
it can’t rollback
it works like a delete +commit.
syntax:
truncate table <tablename>
comment:
comment statement to add a comment about a table, view, snapshot, or column into the data dictionary.
syntax:
comment on table <tablename> is 'text'.
comment on column <tablename.columnname> is 'text'.
ex: select *
from user_tab_comments
where table_name='EMP';
select *
from all_col_comments where table_name = 'EMP';
➢ insert
➢ update
➢ delete
➢ merge
insert:
it is used to add new rows of data to an existing database table.
it is used to insert the data into a table.
To insert data,tables should be first available in the database and below are the ways to insert data into a table.
syntax:
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left
blank during record creation!
update:
it is used to change the existing information in the database.
it is used to modify the existing table data.
syntax:
update <tablename>
set <column1>=<value1>
[<column2>=<value2>,....,<column>=<value> where <condition>]
Specifying condition is not mandatory and if condition is not defined then the system will consider all records in the table for
update.
delete:
it is used to remove the rows from the table.
it is used to delete the data in a table without touching the table structure.
syntax:
delete from <tablename>[where <condition>];
MERGE:
It is used to transfer the data from source table to destination table.
The MERGE statement allows you to specify a condition to determine whether to update data from or insert data into the target
table.
It is used to compare the 2 table contents and make them equal.
It supports only update and insert.
Rules:
-->New records inserted
-->Old records updated
SYNTAX:
MERGE INTO <DESTINATION TABLE NAME> <ALIAS NAME>
USING <SOURCE TABLE NAME> <ALIAS NAME>
ON (<JOINING CONDITION>)
WHEN MATCHED THEN
UPDATE SET <DEST.TABLE ALIAS NAME>.<COLUMN NAME1>=<SOUR.TABLE ALIAS NAME>.<COLUMN
NAME1>,...........................................................................................
[Delete where <condition>]
WHEN NOT MATCHED THEN
INSERT(<DESTINATION TABLE COLUMNS>)VALUES(<SOURCE TABLE COLUMNS>);
all rows of the table can be truncated all rows of the table can be deleted.
single row of the table can not be truncated single row of the table can be deleted
multiple rows of the table can not be truncated multiple rows of the table can be deleted
ddl vs dml
ddl all the ddl statements are committed automatically at the end
of statement execution.
ddl statements are used for defining and managing data
structures like table,view,synonym,sequence etc.
TCL commands will be dealing with transactions only.within the transaction all the TCL commands are valid.
→ Transaction is nothing but a set of DML operations with COMMIT or ROLLBACK that means a group of DML operations with a
COMMIT or a group of DML operations with a ROLLBACK.
→ Within the database transaction will start with DML write operations.So DML read operations can be a part of the transaction but
DML read operation is not the starting point of the transaction.
SELECT → READ
commit :
to make the changes permanently stored data into the database.
Implicit commit - It is applied by the system (DDL commands)
Explicit commit - It is applied by the user
rollback :
to cancel all the transactions done till previous committed data.
Rollback is applicable for DML statements only.
ROLLBACK is just opposite to COMMIT.
ROLLBACK will undo the DML operation that we perform on a database which is not committed yet.
SYNTAX:
Rollback;
Rollback to <SAVEPOINT NAME>;
SAVEPOINT:
It is used to divide the large transaction into small transactions.
Savepoints store data within the buffer only(not in the database).
→ It is used to create a mark in the current transaction.
→ Using savepoint the transaction can be discarded up to the marked by using the rollback statement.
→ If a second savepoint is created with the same name as an earlier savepoint, the earlier savepoint is deleted.
SYNTAX:
SAVEPOINT <SAVEPOINT NAME>;
FLASHBACK TABLE:
this command is used to restore drop objects from recycle bin
SYNTAX:
FLASHBACK TABLE <TABLENAME> TO BEFORE DROP;
PURGE:
THIS COMMAND IS USED TO DROP OBJECTS FROM RECYCLE BIN PERMANENTLY.
SYNTAX:
PURGE TABLE <TABLENAME>
GRANT:
Used to give access for a table from one schema to different schema
Syntax:
GRANT ALL ON <SCHEMA NAME>.<TABLE NAME> TO <SCHEMA NAME>
clauses:
➢ select clause
➢ from clause
➢ where clause
➢ group by clause
➢ having clause
➢ order by clause
➢ distinct clause
syntax:
select <columnlist>
from <table name>
[where <condition>
groupby <condition>
having <condition>
order by <clause>
]
* represents all columns.
<Table Alias Name>.* can also be used
select clause:
it is used to retrieve the data from tables.
from clause:
it is used to retrieve the data from which table.
alias names:
it is used to provide temporary headings for columns or expressions in select statements.
they are valid in that select statement only.
they are only for display purposes.
where clause:
it is used to provide the condition
it is used to filter the data from grouped records
it won't allow group functions and alias names in where condition
eliminates non matching records.
where clause has the highest priority
group functions are not allowed(max,min,count,avg,sum).
group by clause:
it is used to group the similar data based on the columns.
it is used to group rows based on one or more columns/expressions to calculate aggregates like min,max,sum,avg,count for each
group.
by using this clause select statement to combine a group of rows based on the values as a particular column or expression.
whenever we implement a "group by " clause in a select statement, first grouping similar data based on columns and later an
aggregate function will execute on each group of data to produce an accurate result.
When we use "group by" we must use "aggregate functions" which are sum(),avg(),min(),max(),count().
ex: write a query to calculate department number wise total salary.?
having clause:
having clause added to sql because the where clause could not be used with aggregate functions.
It is used to specify the conditions on aggregate functons.it is always used along with group by clause.
it is used to filter the data from grouped data based on condition.
filtering rows after grouping data in table.it can be used along with "group by" clause.
it is similar to the where condition but is used with group functions
group functions cannot be used in where clauses.
select deptno,sum(sal)
from emp
group by deptno
having sum(sal)>9000
order by clause:
it is used to make the data in order.
it is used to arrange the select statement output in ascending order or descending order.
By default order by clause arrange values in ascending order but if we want to arrange values in descending order then we use the
"desc" keyword.
must be the last clause in the select statement.
it supports all types of data.
ex: write a query to display employee salaries in ascending and descending order?
Note: order by clause not only on column names even though we can apply on position of column or by using alias
name in select query.
select * from EMP order by 6 desc;
distinct clause:
it is used to restrict the duplicate records.
ex: select distinct sal from emp;
operators:
→ arithmetic operators
→ logical operators
→ relational operators
→ special operators
→ set operators
what is dual:
→ predefined table in oracle.
→ it has a single row and single column.
→ it is called a dummy table in oracle.
→ testing functions(predefined & user defined) functionalities.
syntax:
select * from dual;
arithmetic operators:
It is used to do the mathematical functions(arithmetical calculations) like addition, subtraction, multiplication and division. (+, -,
*, /)
Note: addition or subtraction on null will result in null (EX: 12+null = null - 5 = null) to overcome this issue we will use NVL functions
relational operators:
(=,(!=or <>),<,<=,>,>=)
relation can be build with only one values (it won't support multiple values)
logical operators:
and operator:
if both the conditions are true then it returns the result as true.
if both the conditions or if any one condition is false then it returns the result as false.
ex: display the details of employees whose salary is greater than 2000 and also whose salary is less than 5000.
select * from EMPwhere sal>2000 and sal<5000;
or operator:
at least one condition is true then it returns the result as true.
if both the conditions are true then it returns the result as true
if both the conditions are false then it returns the result as false.
not operator:
specified conditions must be false.
similar to not equal
ex: select * from EMPwhere not deptno=20;
same as
select * from EMPwhere deptno!=20;
special operators:
(in,like,between,is null):
special operators are used to frame the conditions while retrieving or manipulating data.
to improve the performance.
in/not in:
it is used to pick the values within the given list.
it returns true if value is available in a given list of values.
it supports all types of data.
between/not between
it is used to pick the values within the specified range.
returns true if the value specified is within the specified range.
it supports numbers and date values.
ex: all employee records are fetched whose salary is between 1000 and 2000.
select * from EMPwhere sal between 1000 and 2000;
whenever the lower bound value is larger than the upper bound then it shows "no rows selected".
like/not like:
it is used to search for a pattern in given input supports with character data only.
It uses two special characters.
a) % represents zero or more characters.
b)_(underscore) --> it represents one character only.
syntax:
select * from <tablename> where <columnname> like '<value>';
select * from <tablename> where <columnname> 2not like '<value>';
ex:
list the objects whose name start with 'c'
select object_name
from all_objects
where object_name like 'c%'
/
list the objects whose name doesn’t end with 's'
select object_name
from all_objects
where object_name not like '%s';
/
list the objects whose name contain 'a'
select object_name
from all_objects
where object_name like '%a%';
/
list the objects whose name starts with 'a' and have at least 2 characters in it
select *
from emp
where ename like 'a_%';
syntax:
select * from <tablename> where <columnname> is null;
select * from <tablename> where <columnname> is not null;
rules:
*******
→ no of columns should be the same within both select statements.
→ order of the columns should be same
→ data types of the columns must be matched.
1)union all
2)union
3)intersect
4)minus
union all:
it displays all the values along with duplicate values also.
two queries must have the equal number of columns.
syntax:
select * from <table name 1>
union all
select * from<table name 2>;
union:
it is used to combine the results of two or more select statements.
however it will eliminate duplicate rows from its result set.
in case of union, number of columns and datatype must be same in both the tables
syntax:
select * from <table name 1>
union
select * from<table name 2>;
intersect:
intersect operation is used to combine two select statements, but it only returns the records which are common from both select
statements.
In case of intersect the number of columns and datatype must be the same.
syntax:
select * from <table name 1>
intersect
select * from<table name 2>;
minus:
The minus operation eliminates common results of two select statements and returns only those in the final result which
belongs to the first set of the result.
syntax:
select * from <table name 1>
minus
select * from<table name 2>;
Functions:
To perform a task and must return value.
oracle supports two types of functions.they are
Pre-define/built in functions
(use in sql and pl/sql)
single row functions (scalar functions)
These functions return a single row or group of values.
power(m,n):
it gives the power of a given expression.
m→ value
n→ exponent
ex : select power(2,4), power(4,8), power(0,0), power(null,null) from dual;
sqrt(m):
it gives the square root of a given number.
input value must be positive.
ex: select sqrt(2), sqrt(8), sqrt(0), sqrt(null) from dual;
mod(m,n):
gives remainder after m/n operation.
M→ value
n→ divisor
ex: select mod(1,5), mod(5,2), mod(0,0), mod(null,null) from dual;
ceil(m):
it displays the next highest value.
it returns a value which is greater than or equal to the given value.
ex: select ceil(2), ceil(2.01), ceil(23.65), ceil(245.21), ceil(4567.78), ceil(-23.1), ceil(-456.90), ceil(-3451.091) from dual;
floor(m):
it displays the next lowest value.
The purpose of the floor function is it returns the integer values which are equal to the specified number or less than the specified
number.
ex : select floor(2), floor(2.90), floor(13.12), floor(45.7), floor(980.213), floor(5678.213), floor(-123), floor(-123.21), floor(-1456.765)
from dual;
round(m,[n]):
it rounds the value up to a given number of positions.
it checks the condition and rounds value to some specified decimal.
n → decimal points
ex: select round(1234.98), round(778.34), round(45.65), round(678.21,1), round(765.989,2), round(6789.7654,3) from dual;
trunc(m,[n]):
→ it works similar to that of round,but it won't check the condition.
→ return a number with some digits truncated.
ex: select trunc(123.4), trunc(123.45,0) ,trunc(123.453,1), trunc(123.453,2), trunc(123.45,-1), trunc(123.45,-2) from dual;
abs(m)
it gives the absolute value of n.
if n is -ve it converts to positive.
ex: select abs(10),abs(-5),abs(0),abs(null) from dual;
sign(n):
→ if n is +ve gives 1
→ if n is -ve gives -1
→ if n is 0 gives 0
ascii(m):
select ascii('a') from dual;
select ascii('a') from dual;
select ascii('0') from dual;
b)string functions
upper(string)
it is used to convert the string into upper characters.
ex: select upper('oracle') from dual;
lower(s):
it is used to convert the string into lower characters.
ex: select lower(oracle) from dual;
initcap(s):
it is used to convert the first character into the upper character in a given string.
ex: select initcap('oracle') from dual;
length(s):
it is used to display the number of characters in a given string.
ex: select length('asdefrgt:%"12343098**') from dual;
reverse(s):
it is used to reverse the given string.
ex: select reverse('oracle') from dual;
concat(s,s):
it is used to merge the two strings
ex: select concat('oracle','pvt limited') from dual;
we have to use '||' symbol while merging more than two strings.
ex: select 'oracle'||'india'||'ltd' from dual;
trim(s from s):
trim is used to remove the characters from both sides of a given string.
to remove unwanted spaces or unwanted characters from both sides of the given string.
ex: select trim('x' from 'xxxxxxoraclexxxx') from dual;
l/r trim(s,[s]):
ltrim is used to remove the character from the left end of the given string, if the character is found.
it is used to remove the character from the right end of the given string,if the character is found.
to remove unwanted spaces or unwanted characters from the left or right side of the given string.
ex:
select ltrim(' oracle') from dual;
select ltrim('oracle','o') from dual;
select rtrim('oracle','cl') from dual;
lpad() / rpad():
it is used to add the character from the left end / right end.
The lpad()/rpad() function pads the left/right side of a string with a specific set of characters.
to fill a string with a specific character on the left/right side of the given string.
syntax:
lpad(string,length,[string])
rpad(string,length,[string])
translate(s,s,s):
it is used to translate the character wise in a given string,if the character is found.
to translate a single character with another single character.
it is not possible to translate the entire string.
ex : select translate('prashanth', 'anth', 'pqrs') from dual;
replace(s,s,s):
it is used to replace an entire string.
to replace one string with another string.
it is not possible to replace more than one string.
ex : select replace('prashanth', 'anth', 'pqrs') from dual;
substr(s,m,n):
it is used to display the set of characters in a given string.
it is used to extract a particular portion of a string.
s→ string
m-- > position
n→ no.of.characters
s→ string
c→ character → which is the character we want find out the position
m→ starting search position (+1 / -1 )
n→ occurrence → we want find out the occurrence(repeated characters) if no such character exists it will return 0.
ex:
select instr('hello welcome','e',1,4) from dual;--> -->-->-->0
select instr('hello welcome','e',-1,3) from dual;--> -->-->-->2
decode():
In Oracle, the DECODE function allows us to add procedural if-then-else logic to the query. DECODE compares the expression to
each search value one by one. If expression is equal to a search, then the corresponding result is returned by the Oracle Database
syntax:
decode( col_name, compare_value, return_value, [,compare, return_value] ... [,default_return_value] )
Interview point
DECODE VS CASE
syntax:
case
when condition1 then result1
when condition2 then result2
when condition then result
else result
end;
ex:
select job,deptno,
case when deptno=10 and job='manager' then 'mgr'
when deptno=20 and job='analyst' then 'als'
when deptno=30 and job='salesman' then 'sman'
else job
end
from emp;
ex:
upper(ename)upper,
lower(job)lower,
initcap(ename) initcap,
length(ename) length,
ename||' its working as a'||job as concat,
reverse(ename) reverse,
ltrim(ename ,'S') ltrim,
rtrim(ename, 'S') rtrim,
trim('S' from ename) trim,
lpad(ename,10,'*')lpad,
rpad(ename,10,'*') rpad,
translate(ename,'K','I') translate,
substr(ename,1,1)||substr(ename,-1,1)substr,
decode(deptno,10,'ten',20,'twenty',deptno) decode_result,
case
when deptno=10 and job='MANAGER' then 'mgr'
when deptno=20 and job='ANALYST' then 'als'
when deptno=30 and job='SALESMAN' then 'sman'
else job
end case_result
from emp;
c)date functions
sysdate:
it is used to display the server system date.
ex: select sysdate+10 from dual;
current date:
it is used to display the client system date.
ex: select current_date from dual;
months_between(date1, date2):
It is used to display the number of months between two dates.
ex: select months_between('05-jan-81','05-jan-80') from dual;
next_day(date,’day’):
it is used to display the upcoming date on which required day falls.
ex: select next_day(sysdate,'sun') from dual;
last_day(date):
It is used to display the last day of the month.
ex: select last_day(sysdate) from dual;
trunc(date,’ ’):
it is used to cutdown the date based on year/mon/day/hh/mi depending on requirement
ex: select to_char(sysdate,'dd-mon-yyyy hh:mi:ss'), to_char(trunc(sysdate,'mi'), 'dd-mon-yyyy hh:mi:ss') from dual;
extract:
it is used to extract a portion of a date value.
syntax:
extract ((year |month |day |hour |minute|second | timezone_hour | timezone_mnute | timezone_region | timezone_abbrevation)
from date)
=============================================================
date formats:
d→ name of day in a week
dd → name of day in a month
ddd→ name of day in a year
dy→ first 3 characters of the day.
day→ complete characters of the day.
mm→ number of the months in the year
mon→ first three characters of the month.
month→ complete characters of the month.
y→ last digit of the year
yy→ last two digits of the year.
yyy→ last three digits of the year.
yyyy→ four digits of the year.
Year → to print year in letters.
hh→ an hour of the day.
hh24→ 24 hours format.
mi→ minutes of the year
ss→ seconds of the year
fs→ fraction of seconds
w→ week of the month
ww→ week of the year
q→ quarter of the year
year formats:
yyyy - 2022
yy - 22
year - twenty twenty two
cc - century 22
ad / bc - ad year / bc year
month format:
mm - month number
mon - first three char from month spelling
month- full name of month
day formats:
ddd - day of the year.
dd - day of the month.
d - day of the week
sun - 1
mon - 2
tue - 3
wen - 4
thu - 5
fri - 6
sat - 7
quarter format:
q - one digit quarter of the year
1 - jan - mar
2 - apr - jun
3 - jul - sep
4 - oct - dec
week format:
ww - week of the year
w - week of month
time format:
hh - hour part
hh24 - 24 hrs format
mi - minute part
ss - seconds part
am / pm - am time (or) pm time
ex:
select empno,ename,job,sal,hiredate,
months_between(sysdate,hiredate),
months_between(sysdate,hiredate)/12,
round(months_between(sysdate,hiredate)/12),
ceil(months_between(sysdate,hiredate)/12) ceil,
floor(months_between(sysdate,hiredate)/12) floor
months_between(hiredate,sysdate),
months_between(hiredate,sysdate)/12,
round(months_between(hiredate,sysdate)/12)
from emp;
d)conversion functions
to_char(date,[<format>]):
it is used to convert system format into user format.
it is used to convert the number into character and also it converts the date into character.
ex:
select to_char(sysdate,'dd-mon-yyyy hh24:mi:ss') from dual;
select to_char(sysdate,'ddd dd d day dy DAY DY DD') from dual;
select to_char(sysdate,'yyyy yy year cc ad') from dual;
select to_char(sysdate,'mm mon month MM MON MONTH') from dual;
select to_char(sysdate,'q') from dual;
select to_char(sysdate,'ww w') from dual;
select to_char(sysdate,'hh:mi:ss am') from dual;
select to_char(12346,'99,99,999.99')from dual;
select 1234,to_char(1234,'9999d99')from dual; → decimal indicator(it return specified position of the decimal character)
select to_char(5634,'9.9eeee') from dual; → (it returns a numeric value using scientific notation)
select to_char(1234567,'99g99g9999') from dual; → (it returns the specified of the group separator)
select to_char(1234,'l9999') from dual; → it returns the specified position of the local currency symbol, after l there should be max
number
select -20000,to_char(-20000,'l99g999d99pr')from dual;
select to_char(2000,'9999s') from dual;
to_date(string,[format]):
it is used to convert user format into system format.
it is used to convert the string into date format.
ex: select to_date('january 22,2021', 'month dd,yyyy') from dual;
to_number:
it is used to translate a value of char or varchar datatype to number format.
ex: select to_number('$4328','$9999') from dual
sum
it returns the sum value of the column.
it is an aggregate function
it ignores null values.
it will give the sum of the values to the specified function.
ex :select sum(comm),sum(distinct comm) from emp;
rollup:
rollup is calculating subtotals and grand totals
rollup extension produces group subtotals from right to left and a grand total
ex:select deptno,job,sum(sal) from emp
group by rollup(deptno, job);
grouping id functionality:
************************
both column values are not null → grouping id it will print 0
one column value is not null and one column value is null → 1
one column value is null and second column value is not null → 2
both columns values is null → 3
ex:
select deptno,job,sum(sal) sumsal,
grouping_id(deptno,job)subtotal
from emp
group by rollup/cube(deptno,job)
order by 1,2;
cube:
cube extension will generate subtotals for all combinations of the dimensions specified.
avg:
it will give the average value.
it returns the average value of the column.
it ignores null values.
ex :select avg(comm),avg(distinct comm) from emp;
min():
it will give the minimum of the values of the specified column.
it ignores null values.
ex: select min(sal),min(distinct sql) from emp;
max:
it will give the maximum of the values of the specified column.
it ignores null values.
ex: select max(sal),max(distinct sql) from emp;
count():
it will give the number of rows in the specified column.
if '*' is used to return all rows,including duplicates and nulls.
three types,
i) count(*) →counting all rows (duplicates & nulls) in a table.
ii) count(<column name>) → counting all values including duplicate values but not null values from a column.
iii) count(distinct <column name>) → → counting unique values from a column.here "distinct" keyword is eliminating
duplicate values.
ANALYTICAL FUNCTIONS:
Analytical functions to calculate an aggregate value based on a group of rows and return multiple/all rows of each group.
-->They differ from aggregate functions in that they return multiple rows for each group.
ANALYTICAL FUNCTION NAME() OVER ([PARTITION BY <COLUMN NAME>] ORDER BY <COLUMN NAME><>ASC/DESC]
EX: SELECT EMP.*,SUM(SAL) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC) FROM EMP;
ROW_NUMBER
To assign different rank numbers to the same value.
ROW_NUMBER() OVER ([PARTITION BY <COLUMN NAME>] ORDER BY <COLUMN NAME><>ASC/DESC]
RANK
To assign the same rank number to the same value but skipping the next sequence rank number in the order.
DENSE_RANK
To assign the same rank number to the same value but without skipping the next sequence rank number in the order.
EX:
select empno,
ename,
job,
sal,
deptno,
row_number() OVER (partition by deptno order by sal desc)row_number,
rank() OVER (partition by deptno ORDER BY sal desc) rank,
dense_rank() OVER (partition by deptno ORDER BY sal desc) dense_rank
from emp;
LAG
It is used to access previous row data along with current data.
LAG(expression [,offset[,default_value]]) OVER(ORDER BY columns)
Expression – column
Offset – position of previous data
Default – will return default value if in case offset is out of range.
EX:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LAG(SAL,1,0) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)PREV_ROW
FROM EMP;
LEAD
It is used to access the subsequent row data along with current row data.
LEAD(expression [,offset[,default_value]]) OVER(ORDER BY columns)
EX:
SELECT EMPNO,ENAME,SAL,DEPTNO,
LEAD(SAL,1,0) OVER (PARTITION BY DEPTNO ORDER BY SAL DESC)PREV_ROW
FROM EMP;
general functions:
user:
it will return the name of the present session user(schema).
syntax:
select user from dual;
Or
Show user;
uid:
it returns the user id value for the current session.
syntax:
select uid from dual;
userenv('parameters'):
The parameter list of userenv is shown in the below table.
syntax:
select userenv('lang') from dual; → returns iso abbreviation language name.
select userenv('language') from dual; → returns the language and territory of the current session.
select userenv('sessionid') from dual; → returns the auditing session number.
select userenv('terminal') from dual; → returns the operating system identifier of the current session
greatest:
it is used to find the greatest value in the available or provided expression values.
ex:
select greatest(10,4,9,20) from dual;
select greatest('a','e','i','o','u') from dual;
select greatest (to_date('11-jan-1981','dd-mon-yyyy'), to_date('16-dec-1982','dd-mon-yyyy'), to_date('12-mar-1980','dd-mon-
yyyy')) "greatest" from dual;
least:
it is used to find the least value in the available or provided expression values.
ex:
select least(12,34,77,8,66) "least" from dual;
select least (to_date('11-jan-1981','dd-mon-yyyy'), to_date('16-dec-1982','dd-mon-yyyy'), to_date('12-mar-1980','dd-mon-yyyy'))
"least" from dual;
nvl
it assigns the value to the column if it is null.
The nvl() function accepts two arguments. if e1 evaluates to null, then nvl(e1,e2) function returns e2.
if e1 evaluates to non-null, the nvl() function returns e1.
nvl2:
if exp1 is null it returns exp3,if exp1 is not null it returns exp2
nullif:
if exp1 and exp2 results are same it returns null value otherwise it returns exp1 result.
ex: select nullif(100,50*2),nullif(200,15*9),nullif(600,300+300) from dual;
coalesce:
it picks the first not null values.
ex: select coalesce(100+null,128-null+1000,12*null,268,2120,3281) from dual;
➢ check constraints
it is used to check the condition
allows a valid range of values only.
it is used to validate the data based on the condition.
to check values with user defined conditions before accepting values into a column.
it can be defined at column level or table level.
ex :
create table xx_check(
sno number,
sname varchar2(20),
fee number check(fee>=3000),
marks number constraint chs1 check(marks between 0 and 100),
jdate date
);
ex:
create table xx_check_1(
sname varchar2(20),
sno number(3),
marks number(3),
constraint student_c1_marks_1 check(marks between 0 and 100)
);
how to add constraints to an existing table:
============================================
syntax:
alter table <tn> add constraint <constraint key name> <constraint type> (<column name>);
➢ not null constraints
it is used to allow only not null values.
it does not allow null values.
it can be defined at column level only.
not null constraint does not support "table level".
ex:
create table xx_stu(
sno number not null,
sname varchar2(30)
);
➢ default constraints
it is used to insert default values when no values are given.
it will accept null values and will display null values.
ex:
create table xx_emp_default
(
empno number,
ename varchar2(20),
sal number default 1000
);
ex:
create table xx_emp_primay_key(
empno number primary key,
ename varchar2(20) ,
sal number
);
ex:
create table xx_cpk_con(
sno number,
sname varchar2(20),
marks number,
primary key(sno,sname)
);
note : when we apply a primary key constraint on a group of columns then we call it a "composite primary key" constraint.
In this mechanism individual columns are accepting duplicate values but duplicate combinations of column data are not allowed.
ex:
create table xx_unique_con (
sno number,
sname varchar2(10),
marks number,
unique(sno,sname)
);
note:
→ when we apply a unique constraint on a group of columns then we call it a "composite unique" constraint.
→ in this mechanism individual columns are accepting duplicate values but duplicate combinations of column data is not allowed.
syntax:
<common column name of child> <dt>[size] references
<parent table name>(<common column name of parent>)
ex:
parent table:
create table dept_parent (
deptno number primary key,
dname varchar2(20),
loc varchar2(20)
);
chaild table:
create table emp_child(
empno number primary key,
ename varchar2(20),
sal number,
deptno number(2) references dept_parent(deptno)
);
Interview point
What is normalization in primary key and foreign key?
Normalization is the process of organizing data in a database in such a way that data redundancy is minimized and data integrity is maximized.
In Oracle, normalization involves organizing data into tables and defining relationships between those tables using primary keys and foreign keys.
The goal of normalization is to eliminate data redundancy, which reduces storage space and improves data consistency.
note :
once we establish relationship between tables there are two rules are come into picture.those are
insertion rule:
we cannot insert values into foreign key(references key) columns those values are not existing under the primary key column of
the parent table.
integrity constraint (scott.sys_c005468) violated - parent key not found.
deletion rule:
when we try to delete a record from parent table and those associated records are available in child table then oracle returns an
error
ora-02292: integrity constraint (scott.sys_c005468) violated - child record found.
note:
If we want to delete a record from the parent table when they have corresponding child records in the child table then we provide
some set of rules to perform delete operations on the parent table.those rules are called "cascade rules".
i) on delete cascade
by using on delete cascade, we can delete the rows from the parent table and the corresponding child table rows deleted
automatically.
ex:
create table xx_emp2(
empno number primary key,
ename varchar2(10),
deptno number references dept_parent(deptno) on delete cascade
);
ex:
create table xx_emp3(
eid number primary key,
ename varchar2(10),
deptno int references xx_dept3(deptno) on delete set null
);
--> to overcome the above problem then we use "novalidate" keyword at the time of enable constraint.once we use "novalidate"
keywordthen constraint is enable with "novalidate" and oracle server will not check existing data in table but checking new data
while inserting time.
ex:
****
alter table <tn>enable novalidate constraint<constraint key name>;
joins:
it is used to retrieve the data from more than 1 table.
when we are retrieving data from multiple tables based on the "where" clause condition then we call the non-ansi format join.
When we are retrieving data from multiple tables with "on" / "using" clause conditions then we call the ansi format join.
syntax:
select * from table name1,table name2 where <join condition>;
select * from <table name1> <join key> <table name2 > on <join condition>;
types of joins:
simple join
equi join
retrieving data from multiple tables based on "equal operator(=)" is called equi join.
equi join always retrieves only matching data/matching rows only.
common column or common field data type must be matched.
syntax:
select * from tablename1, tablename2
where <table name1>.<common col> = <table name2>.<common col>;
(or)
where <tn1 alias name>.<common col> = <tn2 alias name>.<common col>;
natural join
Natural join is similar to equi join. When we use natural join we should have a common column name. this column datatype must be matched.
Whenever we are using natural join there is no need to write a joining condition explicitly because internally the oracle server is preparing a joining
condition based on an "equal operator(=)" with common column name automatically.
By using natural join we avoid duplicate columns while retrieving data from multiple tables.
syntax:
select * from tablename1 natural join tablename2 ;
inner join
inner join is similar to equi join.retrieving data from multiple tables with "on" clause condition.
ansi syntax:
select * from tablename1 inner join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;
outer join
In the above equi/inner join we are retrieving only matching rows but not unmatching rows from multiple tables.
so to overcome this problem then we use "outer joins".
ansi format:
select * from tablename1 left outer join / left join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;
ansi format:
select * from tablename1 right outer join / right join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;
ansi format:
select * from tablename1 full outer join / full join tablename2
on <table name1>.<common column> = <table name2>.<common column>;
(or)
on <tn1 alias name>.<common column> = <tn2 alias name>.<common column>;
self join
joining a table data by itself is called self join.
in self join a row in one table joined with the row of the same table.
we can create any number of alias names on a single table. Each alias name should be a different name when we compare a
column value within the same table.
non-ansi syntax:
select * from <tn1>,<tn2>,<tn3>,.........<tn n>
where <condition1> and <condition2> and <conditions>..........;
ansi syntax:
select * from <tn1> <join key> <tn2>
on <condition1> <join key> <tn3> on <condition2> <join key> <tn4> on <condition2> ............;
If you want to fetch multiple data types from multiple tables we can write join queries but unnecessarily don't write any join query. It will degrade your
database performance or it will decrease your query performance that's why we need to write subqueries.
If you want to get data from one table based on the input value of another table we can use subqueries instead of join.
A query inside another query is called a subquery or nested query or child query.
→ Outer query always depends on the result of inner query.
→ The result set returned by the inner query will be used as input to the outer query.
→ A Subquery is having two components those are,
i) INNER / CHILD / SUBQUERY
ii) OUTER / PARENT / MAIN QUERY
Syntax:
SELECT * FROM <TN> WHERE <CONDITION> (SELECT * FROM ..................(SELECT * FROM ..........(SELECT * FROM .....)));
AS PER THE EXECUTION PROCESS OF SUBQUERY IT AGAIN CLASSIFIED INTO TWO CATEGORIES.
Interview point:
EX:
Display DNAME for EMPNO 7654.
SELECT DNAME FROM DEPT WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE EMPNO=7654);
If a quarry used in place of a column name that is called scalar quarry. It wont allow more than 1 value
ex :select ename ,(select dname from dept where emp.deptno = dept.deptno) dept from emp ;
IN OPERATOR:
The IN operator returns TRUE if the comparison value is contained in the list it accepts multiple values.
EX: SELECT ENAME,SAL FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO);
ANY
IT IS USED TO COMPARE ANY OF THE VALUES IN THE GIVEN LIST.
A > ANY(10,20,30) accept all values above 10
A < ANY(10,20,30) accept all values below 30
ALL
IS USED TO COMPARE ALL OF THE VALUES IN THE GIVEN LIST.
A > All(10,20,30) accept all values above 30
A < All(10,20,30) accept all values below 10
INLINE VIEW
It works like a query,which is having the query in from clause or instead of table.
It is a special type of subquery in oracle. Providing a select query in place of table name in select statement.
SELECT * FROM (<SELECT QUERY>); -->-INLINE VIEW
gen. subquery is not allowed to use the "order by" clause. so that we use "inline view".
gen. column alias names are not allowed to be used in "where" clause condition.so that we use "inline view ".
EX:FIRST 5 RECORDS
CORRELATED SUBQUERIES:
IN CORRELATED SUBQUERY FIRST OUTER QUERY IS EXECUTED AND LATER INNER QUERY WILL EXECUTE.
→ Generally in non correlated subquery child queries are executed first whereas in correlated subquery parent queries are
executed first.
→ In correlated subquery we must create an alias name in the parent query table and pass that alias name into the child query
where clause.
→ Correlated subqueries are used for row by row processing.
→ Each subquery is executed once for every row of the outer query.
Syntax:
SELECT column1, column2, ....FROM table1 aliasname1
WHERE column1 operator
(SELECT column1, column2 FROM table2 aliasname2
WHERE aliasname2.columnname = aliasname1.columnname);
EX: Write a query to find the highest earning employee in each department?
EXISTS OPERATOR:
→ it is a special operator which is used in correlated subquery only.
This operator is used to check whether row / rows exist in the table or not.
→ it returns either true (or) false. if the subquery returns at least one row then returns true or else if the subquery does not return
any row then returns false.
WHERE EXISTS(<SELECT STATEMENT>)
note: when we use the exists operator in where clause condition there is no need to mention a column name explicitly because internally oracle
server will take column name of a table by default.
SELECT * FROM DEPT D WHERE EXISTS(SELECT DEPTNO FROM EMP E WHERE E.DEPTNO=D.DEPTNO);
SYNONYM
Synonym is an alternative name or Permanent alias name given to the table, view, sequence, stored procedure, function or packages for the user's
convenience to use it.
→ Synonyms can be created for the entire object only.
→ It is used to hold the owner of the table.
→ It works like a mirror image of the tables.
→ It does not have its own structure.
→ It depends on the tables.
→ Synonym is a permanent alias name for a single Base table or view.
→ It supports DML and DQL,DCL operations.
→ Synonyms can be PUBLIC or PRIVATE.
→ By default the synonym is PRIVATE.
→ All synonyms are created in user_synonyms, all_synonyms table.
Note :
→ If any changes in the synonym are automatically reflected into the table and vice versa.
→ Synonym is a dependent object whereas table is independent object, which means if a table is dropped then synonym stops its working.
If a table is recalled back then the synonym will start working.
Private Synonym :
→ It is used to create a private synonym in the current schema and accessed within that schema only.
SYNTAX:
CREATE OR REPLACE SYNONYM <SCHEMANAME>.<SYNONYM NAME> FOR <SCHEMANAME>.<TABLENAME>;
Public Synonym:
This synonym is created from a user, which has got DBA privileges.
When a public synonym is created and if the same object gets accessed from another user, table name should not be used as qualifier.
SYNTAX:
CREATE OR REPLACE [PUBLIC]SYNONYM <SCHEMANAME>.<SYNONYM NAME> FOR <SCHEMANAME>.<TABLENAME>;
DROPPING A SYNONYM:
DROP [PUBLIC] SYNONYM <synonym_name>;
PUBLIC synonyms can be dropped from a user, which has got DBA privileges.
Drawbacks of Synonyms:
→ We can't create synonyms on multiple tables.
→ We can't create synonyms on particular columns.
→ We can't create synonyms on a particular record.
VIEWS
We have some drawbacks in synonyms.The drawbacks will be overwritten while using views.
View is nothing but an image table or virtual table, which is created for a base table.
→ It is a virtual table to hide the base table and it works like a mirror image of the table.
→ It doesn't have its own structure.
→ It is not possible to modify the structure of the table by using views.
→ We can define views on synonyms and synonyms on views.
→ View can be created by taking all values from the base table or by taking only selected values from the base table.
→ Any modifications made through a view automatically updates the base table and vice versa.
→ View is a database object , which will store a query in compiled format, hence it is called "Stored Query".
→ View supports only DML And DQL.
→ All views are stored by all_views,user_views
NOTE :
When the base table is dropped, the view will stop working.
When the base table is back in the database, the view will start working.
Adding new columns to a table that has an associated view does not update the view's result set, even if the view uses a wildcard (*) to represent all
table columns. To incorporate new columns, you must recreate the view.
Advantages of views:
1. Provides high security
2. Improves performance
3. Network traffic gets reduces
4. Shortens SQL queries
5. Supports to perform summarized calculation fastly
6. Supports to INSERT/UPDATE/DELETE related data
7. We can retrieve the data from many tables (joins)
Type of views
Syntax:
CREATE [ OR REPLACE ] [ FORCE / NOFORCE ] VIEW view_name
AS SELECT query
[WITH READ ONLY / WITH CHECK OPTION];
EX:
CREATE OR REPLACE VIEW EMP_RO
AS
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP
WITH READ ONLY;
EX:
CREATE OR REPLACE VIEW V4
AS
SELECT EMPNO,ENAME,DEPTNO FROM EMP1 WHERE DEPTNO=20
WITH CHECK OPTION;
Complex View
It is used to define a view on multiple tables that views are called as complex views.
→ We can not perform DML operations(INSERT,UPDATE,DELETE) on complex views but by using instead of triggers we can.
→ A view is created based on a single table using the below clauses.'
Group by clause
Order by clause
Group function/Aggregate function
Joins
Subquery
Duplicate column names will not be accepted by the view while selecting data using join conditions.
when we create a view with a function then we must create an alias name for those functions otherwise oracle returns an error.
EX:
CREATE OR REPLACE VIEW V1
AS
SELECT DEPTNO,SUM(SAL) SUM_SAL,AVG(SAL) AVG_SAL,MAX(SAL) MAX_SAL, MIN(SAL) MIN_SAL
FROM EMP
WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='RESEARCH')
GROUP BY DEPTNO;
Force View
It is used to define a view without a base table.
Generally views are created based on tables but force views are created without base tables.
CREATE FORCE VIEW <VIEW NAME> AS SELECT * FROM <TN>;
Materialized Views
It is one of the views which has its own structure.
→ It does not allow the DML operations on Materialized views.
→ It is used to store the historical data
→ We can define a view on a table which has the primary key.
→ Views don't store any data whereas materialized views are storing data.
→ Even if we drop a base table, a materialized view can be accessible.
CREATE MATERIALIZED VIEW <VIEW NAME> AS SELECT * FROM <TABLENAME>;
When we update data in base table the data will be reflected in view but materialized view will not update.
If we want to perform DML operations on a materialized view we can use the following syntax.
→ ON DEMAND / ON COMMIT:
In oracle we are refreshing materialized views in two ways.
ON DEMAND:
It is a default refreshing method.
In this method we are refreshing the materialized view by using the "DBMS_MVIEW" procedure.
SYNTAX:
EXECUTE DBMS_MVIEW.REFRESH ('<MVIEW NAME>');
ON COMMIT:
→ We can refresh a materialized view without using "DBMS_MVIEW" but using the "ON COMMIT" method.
Syntax:
CREATE MATERIALIZED VIEW <VIEW NAME>
REFRESH ON COMMIT
AS SELECT * FROM <TN>;
Sequence is a database object, which is stored in a database server and it is used to generate the sequence of numbers on a particular column of
table automatically.
→ it automatically generates primary key or unique key values.
→ it can be either asc /desc order.
→ It is Used to generate the sequence number on a particular column of table automatically.
→ It is not related to any table.
→ Sequence will start generating values from its min value.
→ Default MIN Value is 1.
→ Default incremental value of sequence is +1.
→ ALL_SEQUENCES --> only sequences will be displayed
SYNTAX:
CREATE [OR REPLACE] SEQUENCE <seq_name>
[START WITH <value>] → Default MIN value is 1
[INCREMENT BY <value>] → Default 1
[MINVALUE <value>] → Default 1
[MAXVALUE <value>] → Default → 10^27 → 999999999999999999999999999
[NOCYCLE / CYCLE] → Default NOCYCLE
[NOCACHE / CACHE <size>]; → Default 20
any interval can be specified for increment. if +ve value is specified it generates the sequence of numbers in ascending order. if -ve value is specified
it generates the sequence of numbers in descending order.
start with n : this clause is used to specify the start value of a sequence.
it gets executed only for once.
start value should be >=minvalue and <=maxvalue.
minvalue n : it is used to specify the min value of a sequence.
maxvalue n : it is used to specify the max value of a sequence.
nocycle : it is a default option which is set for a sequence and that sequence will be not reusable.
cycle : it is used to make a sequence repeat with respect to generating the numbers between min value to max value and vice versa.
no cache:
It is the default parameter. When we create a sequence with "no cache" parameters then the set of sequence values are stored into database
memory.
Every time we want to access sequence numbers then the oracle server will go to database memory and return to the user. so that it will degrade
the performance of an application.
cache n:
when we create a sequence with a "cache " parameter then the system is allocating temp. memory(cache) and in this memory we will store the set
sequence numbers.whenever user wants to access sequence numbers then oracle server will go to cache memory and return to the user.
accessing data from cache is much faster than accessing data from database.it will increase the performance of an application. here "n" represents
the size of the cache file. minimum size of cache is 2kb and maximum size of cache is 20kb.
Restriction :
1. Can't be used at DELETE command
2. Can't be used at Inner queries
3. Can't be used with DISTINCT operator
4. Can't be used at Group By Clause
ALTERING A SEQUENCE:
Sequences which are created can be altered w.r.to minvalue, maxvalue, increment by value... etc. It does not support changing the START
value.
Syntax:
DROPPING A SEQUENCE:
A sequence which is created can be dropped using DROP SEQUENCE command.
DROP SEQUENCE seq_name;
Pseudo Columns:
A Pseudo column behaves like a table column,but it is not actually stored in the table.
You can select from Pseudo columns, but you can not insert, update and delete their values.
SYSDATE
It displays the system date.
SELECT SYSDATE FROM DUAL;
SYSTIMESTAMP
It displays the date and time
SELECT SYSTIMESTAMP FROM DUAL;
CURRVAL
It returns the current value of the sequence.
Sequence_name.CURRVAL → can be used in place of values given for a col.
NEXTVAL
It returns the increment value of the sequence.
Sequence_name.nextval
ROWID
ROWID is a pseudo column in a table which stores and returns row addresses in hexadecimal format In the database, each row has a unique
address.
→ The ROWID pseudocolumn returns the address of the row.
→ Generated automatically while inserting records into a table
→ ROWID is alphanumeric.
→ ROWID is the permanent unique identifier in the database.
→ A user can access a row quickly and easily using its ROWID.
→ ROWID can also be used to delete the duplicate records from a table.
→ It consists of Object id, Data file id, Block id & Record id. It is Reusable.
ROWNUM
Generated sequences for query output.
→ It is a dynamic value automatically retrieved along with Select statement output.
→ ROWNUM is numeric.
→ ROWNUM is temporary.It won't be stored in the database.
EX: SELECT ROWID ROW_ID,ROWNUM,ENAME,SAL FROM EMP;
We can't use rowid or rownum in where clause, we can achieve by using inline view
LEVEL:
It will arrange the select statement output in Inverted tree structure ( Hierarchical Tree ) and gives the position of row in Tree.
( Returns Number )
The Level Pseudocolumn returns 1 for a root row,2 for a child of a root and so on.
A root row is the highest row within an inverted tree.
A parent row is any row that has children.
A child row is any non-rooted row
A leaf row is any row or node without children.
INDEXES:
index is a database object which is used to retrieve data from a table fastly.
A database index will work as a book index page in a text book. In a text book by using an index page we can retrieve a particular topic from a text
book very quickly. The same as by using database index objects we can retrieve a particular row from a table very fastly.
By using indexes we can save time and improve the performance of databases.
index objects can be created on a particular column (or) columns of a table and these columns are called "index key columns".
index uses rowid to fetch data from the table.
All databases are supporting the following two types of searching mechanisms those are,
table scan(default)
It is a default scanning mechanism for retrieving data from tables. In this mechanism oracle server is scanning entire table(top - bottom)
Index scan
In the index scan mechanism oracle server scans only indexed columns from a table.
TYPES OF INDEXES:
Btree Index
It stands for Balanced Trees.
It is an ordered list of values divided into ranges along with the row id information stored in the index segment.
B-tree indexes are suitable for containing a high number of values.
1)Simple Index
When we create an index on a single column then we call it a simple index.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME>);
2)Composite Index
When we create an index on multiple columns then we call it a Composite index.
SYNTAX:
CREATE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME1>,<COLUMN NAME2>,..........);
3)Unique Index
When we create an index based on a "UNIQUE CONSTRAINT" column, it is called a unique index.
Unique indexes do not allow duplicate values.
SYNTAX:
CREATE UNIQUE INDEX <INDEX NAME> ON <TN>(<COLUMN NAME1>,<COLUMN NAME2>,..........);
Bitmap Index
It is created on distinct values of a particular column.
→ Generally Bitmap indexes are created on low cardinality of columns.
→ When we create a Bitmap index internally oracle server is preparing a Bitmap indexed table with bit numbers 1 and 0.
cardinality:
it refers to the uniqueness of data values contained in a particular column of table.
cardinality of column = no.of distinct values of a column/ no.of rows in a table
syntax:
create bitmap index <index name> on <tn>(<column name>);
DYNAMIC SQL:
→ DYNAMIC SQL IS A PROGRAMMING TECHNIQUE TO BUILD SQL STATEMENTS AT RUNTIME.
→ Both compilation and execution happens at run time. It will be useful when we don't have the values (of column or table
name)till run time.
EX:
Table_NAME := '&TNAME ' ; → will ask for input where ever it find & symbol
A number := :number ; → will give the same value to all the :number that we used in a single query.(commonly known as bind
parameter)
We can use’ &&Tname’ to store the values permanently into ‘&Tname’ till server disconnects
Select * from (select Dense_rank()over(order by SALdesc) s_no, emp.* from emp) where s_no = &Highest_values ;