You are on page 1of 24

SQL

In 1979 Oracle Corporation introduced the first commercially available implementation of SQL.
SQL is a non-procedural language. We specify what information we require not how to get it.
SQL is 4th generation language
Worked with SQL plus 3.1, 3.3
Latest version SQL plus 8.1 with Oracle 8I

Data definition language

Table
Create table
Create table table_name (
Column_name1 datatype (size) column level constraint,
Column_name2 datatype (size) column level constraint,
Table level constraints);

Properties of Table_name
• Name must be begin with letter.
• Case insensitive
• Must be 30 chatacters.
• Name must not be a reserved word of SQL.

Properties of Column_name
• Name must be begin with latter.
• Case insensitive.
• Must be 30 characters.
• Name must not be a reserved word of SQL.
• Column_names in a table must be unique
• Number of columns 256.This limit is removed in latest version.

Datatypes
Varchar/Varchar2(w)
• Variable length character.
• Value up to width 2000 bytes.
• Width has to be mentioned
• Oracle provides non-padding comparison for the varchar
columns.I.e.(SQL)<>(SQL)
• Considering a column assigned with varchar2 datatype of size 30
characters. If the user enters 10 characters, then the column length is
10 bytes but not 30 bytes.
Char or char(w)
• Fixed length character
• Value up to width 255 bytes.
• Default is 1 if size is not mentioned.
• Oracle provides padding comparison for the char columns. So that (SQL
)=(SQL)
• Suppose if the total characters are less than the width of the field, oracle
adds blank Characters at end. If length is more, it gives error.
Number
floating-point number with precision of 38 significant digits
Number(w)
integer numbers with precision w i.e. total digits
Number(w,s)
• floating point number with precision of w significant digits and s number
of digits on right side of the decimal.
• If the given value exceeds the column scale ,then the value will be
rounded.
Date
• Date values from Jan 1 4712 BC to Dec 31 4712 ad. Time information
also stored.
• Occupies 7 bytes of length
• Default format is 'dd-mon-yy'
Long
• Variable length character values up to 2 GB.
• Only one long column allowed per table.
• Primary key or unique constraint can not be allowed on long column
• Procedures can not accept long datatype as arguments
Raw
• Used for storing graphic images or digital sound
• Maximum size is 255 bytes
• Only storage & retrieval is allowed . No other manipulation is allowed.
• This data type can be indexed.
Long raw
• Used for storing graphic images or digital sound
• Maximum size is 2 GB
• Only storage & retrieval is allowed . No other manipulation is allowed.
• This data type can not be indexed.
Rowid
Values of this rowid are hexadecimal strings representing the address of
the each row.
Block.row.file
Block – is a hexadecimal string identifying the data block of the data file
containing the row. Is a 6-character value and depends on operating
system.
Row - is a hexadecimal string identifying the row in the data block.
Is a 4-character value
File - is a hexadecimal string identifying the database file containing the
row.
Is a 4-character value
This is a unique value created for each & every row in a table by the
database.
Constraints
• To enforce the rules at a table level whenever a row is inserted or deleted or
updates, The constraint must be satisfied for the operation to succeed.
• Constraints are 2 types. Table level & column level.

Table level constraint is the part of table definition


Ex: create table table_name(
Column_1 datatype,
Column_2 datatype,
Column_3 datatype,
unique(Column_1,column2))

column level constraint is the part of column definition,


Ex: create table table_name(
Column_1 datatype unique,
Column_2 datatype,
Column_3 datatype)

Some constraints can be given at column level or at table level


Ex. Unique, check, primary, foreign keys. But only if they are for single
column

Table level constraints will be given when there are more than one column is
participated in constraint. Other than that there is no functional difference
between column level and table level.

Some constraints can be given at table level.


Ex: not null, null, default – these are column level only

• All constraints are stored in data dictionary.


• Each constraint can be given a name. If name is given, it is easy to refer that
constraint Otherwise name is generated automatically in the form sys_cn where
n is a unique number.
Null/Not null
• Specify the column can not accept null values.
• If you don’t specify that ,null is the default.

create table table_name(


Column_name datatype not null)
or
create table table_name(
Column_name datatype constraint nn_column_name not null)
where nn_column_name is the constraint name.

This constraint can not be given at the end of the table definition like
Create table test (
Column1 char,
Column2 date
Constraint cn_1 not null (column1)); -- This is not allowed.

Default
• Specify the column can take a default value when given value is null.
• We can give literal and expressions and functions such as sysdate as
default
• We can not give another column as default.

create table table_name(


Column_name varchar2(10) default 'oracle')
or
create table table_name(
Column_name datatype constraint de_column_name default 'oracle')
where de_column_name is the constraint name.

This constraint can not be given at the end of the table definition like
Create table test (
Column1 char,
Column2 date
Constraint cn_1 default (column1)); .. this is not allowed.

Unique
• No two rows of the table can have the same value for this key. That
means if column is specified as unique , it won't allow duplicate values
in that column.
• Unique columns can be a single column or group of columns.
• Unique column allows null values.
• Unique will create an index on this column.
• Any combination of columns can be created as unique key for one table.
• Table can have any number of unique keys

create table table_name(


Column_name varchar2(10) unique)
or
create table table_name(
Column_name datatype constraint un_column_name unique)
Or
create table table_name(
Column_1 datatype,
Column_2 datatype,
unique(Column_1))
or
create table table_name(
Column_1 datatype,
Column_2 datatype,
constraint un_column_name unique(Column_1))

where un_column_name is the constraint name.

Primary key

• Same as unique but not allows null values in the column


• Same combination of columns can not be created as primary key for
one table.
• Table can have only one primary key
create table table_name(
Column_name varchar2(10) primary key);
or
create table table_name(
Column_name datatype constraint pk_table_name primary
key);
or
create table table_name(
Column_1 datatype ,
Column_2 datatype,
primary key(Column_1));
or
create table table_name(
Column_1 datatype ,
Column_2 datatype,
constraint pk_table_name primary key(Column_1));
where pk_table_name is the constraint name.

Foreign key

• Foreign key provides referential integrity rules either with in a table or


between tables
• A foreign key is used in a relationship with either a primary or unique
key.

create table table_name(


Column_name varchar2(10) references
table_name(Column_name)
or
create table table_name(
Column_name varchar2(10), constraint
fk_table_name references
table_name(Column_name))
Or
create table table_name(
Column_1 varchar2(10),
Column_2 varchar2(10),
foreign key(Column_1) references
table_name(Column_name))
or
create table table_name(
Column_1 varchar2(10),
Column_2 varchar2(10),
constraint fk_table_name foreign key(Column_1)
references table_name(Column_name))

where fk_table_name is the constraint name.

There is an option for foreign key ...on delete cascade

create table table_name(


Column_name varchar2(10), constraint fk_table_name foreign
key(Column_name) refers table_name(Column_name) on
delete cascade)

This means whenever parent record is deleted, all child records will be
deleted automatically.

Check

The check constraint defines a condition that each row must satisfy

create table table_name(


salary number(8,2) check(salary >3000))
or
create table table_name(
salary number(8,2), constraint ck_table_name check(salary
>3000))
or
create table table_name(
salary1 number(8,2),
salary2 number(8,2),
check(salary >3000))
or
create table table_name(
salary1 number(8,2),
salary2 number(8,2),
constraint ck_table_name check(salary >3000))

At the end of each constraint we can mention disable /enable to specify whether
it is enable or disable. By default all constraints are enable.

Creating a table from another table

Create table table_name (column_name1, column_name2....) As select statement.

• Table will be created with data.


• Constraint information will be inherited from the selected table.
• Select statement should have well defined names but not expressions or literals
• The column names can be avoided. If column names are given, the number of columns
must equal to number of columns in the select statement.

Alter the table

Once table is created we can not do following things


Table name
We can change table name using rename command
Rename oldtable_name to new_table_name
column
We can add columns using alter command
alter table table_name add new column datatype(size)

We can not modify column name

We can delete columns using drop column (this has been introduced in oracle 8I)
alter table drop column col_name
Datatype
We can change the datatype when column is empty
alter table table_name modify column_name new_datatype(size)
Size
We can extend the size of the column at any time
But we can reduce the column size when it is empty
alter table table_name modify column_name datatype(new size)
Constraint
Not null /null –
alter table table_name modify column_name not null/ null
alter table table_name modify column_name constraint cn_1 not null/ null

we can not use add constraint for not null or null like
alter table table_name add constraint cn_1 column_name not null/ null - - this is
not allowed

Default –
alter table table_name modify column_name default ‘oracle’
alter table table_name modify column_name constraint cn_1 default ‘oracle’

we can not use add constraint for default like


alter table table_name add constraint cn_1 column_name default ‘oracle’ - - this
is not allowed

check
alter table table_name modify column_name check(column_name > 100)
or
alter table table_name modify column_name constraint cn_1
check(column_name > 100)
or
alter table table_name add check(column_name > 100)
or
alter table table_name add constraint cn_1 check(column_name > 100)

unique
alter table table_name modify column_name unique
or
alter table table_name modify column_name constraint cn_1 unique
or
alter table table_name add unique(column_name)
or
alter table table_name add constraint cn_1 unique(column_name)

primary key
alter table table_name modify column_name primary key
or
alter table table_name modify column_name constraint cn_1 primary key
or
alter table table_name add primary key (column_name)
or
alter table table_name add constraint cn_1 primary key(column_name)

foreign key
alter table table_name modify column_name references tab1(col1)
or
alter table table_name modify column_name constraint cn_1 references
tab1(col1)
or
alter table table_name add foreign key(column_name) references tab1(col1)
or
alter table table_name add constraint cn_1 foreign key(column_name)
references tab1(col1)

Whatever the constraint adding it should satisfy the existed data. EX not
null can only be applied when there is no null value in that column.

We can drop/enable/disable the constraints

alter table table_name drop constraint ck_table_name


or
alter table table_name drop constraint ck_table_name cascade
This cascade option will remove all other constraint related with this constraint.
Or
alter table table_name enable constraint ck_table_name

Alter table command fails if another user has an open transaction on the specified
table.

Drop table

To remove the definition of table from the database, we can use drop command.
drop table table_name [cascade constraints]

Things will be happened when table is dropped.

• All data & indexes with it will be removed


• All views, procedures, triggers and synonyms will remain, but they will be invalid. And will
be valid when the table is recreated.

The cascade constraints option will remove dependent referential integrity constraints.

Comment table

Use this command to create a comment on a table or a column in table up to 255


characters.

To comment on table

comment on table table_name is 'this table is created for maintenance'

To comment on column
comment on table table_name.column_name is 'this table is created for maintenance'

To remove the comment


comment on table table_name is ''

Comments will be stored in all_col_comments or user_col_comments

Rename table

We can change the name of the table.


Rename old table to new table.
Integrity constraints, indexes, and grants on the old table are automatically transferred to
the new object.
Oracle invalidates all the objects like views, stored procedures, and triggers, which are
using old name.

Truncate table

This command allows removing the data from table.


Compare to delete command ,truncate does not maintain rollback segments.It flushed the
data very efficiently.
Truncate table table_name [reuse/drop storage]
Drop storage – reallocates the space used by the table to other objects. This is default
Reuse storage - To retain or reuse space for same table.

Desc or describe table_name


To describe the structure of the table. We can use this command.

Procedure
Create
Create or replace procedure proc_name(parameter list) is
Declare
Local variables
ex.. price number ----here we should not mention width or size of the
variable..like char(4) or number(2)
Begin
Executable statements
Exceptionm handling
End

Parameters are different modes.


IN, OUT, INOUT
IN- this is to pass the value to procedure and can not be modified in side the procedure
OUT- this is to return the value from procedure
INOUT- this is to pass and as well as return the value in procedure

Ex:
create or replace procedure update_data is

screening_st_share number;
screening_fed_share number;

cursor screen_cur is
select st_share,
fed_share,
pr_id,
from tepms_screening;

begin

/* process on screening record by record


FOR trans IN screen_cur LOOP */

screening_st_share := trans.st_share;
screening_fed_share := trans.fed_share;

/*This is award amount for latest */


select cur_awd
into :latest_award_amount
from tepms_award_adjustments
where pr_id = :screening_project_id and
AWARD_ID = select max(AWARD_ID)
from tepms_award_adjustments
where pr_id = :screening_project_id;

/*find out the ration of shares*/


state_percentage = :screening_st_share/:latest_award_amount

fed_percentage = :screening_fed_share/:latest_award_amount
/*this is for update of the st_share,fed_share fileds in
tepms_award_adjustments table*/
update tepms_award_adjustments
set st_share = NEW_AWD * :state_percentage,
fed_share = NEW_AWD * :fed_percentage
where pr_id = :screening_project_id;
end loop;

end update_data;

To run the procedure


Exec procedure name(parameters)

Alter Procedure
This is not to change the definition of the procedure but to compile the stored procedure.
Alter procedure proc1 compile

Function

Create
CREATE or replace function function_name(parameter list) return data_type is ---
(datatype can be number, varchar…etc)
Declare
Local variables|
Begin
Executable statements
Exception handling
End

Alter function
This is not to change the definition of the function but to compile the function.
Alter function fun11 compile

Index

Create index
An index is a database object that contains an entry for each value that appears in the
indexed column(s) which provides direct and fast access to rows
Create [unique] index ind_1 on table_name(column1[asc/desc],column2[asc/desc])
Unique – for avoid duplicate values with that index – by default no unique. That means it
allows the duplicate records.
ASC/DESC – the indexes are always created in ascending order, we can change that
order

An index can have maximum of 16 columns


The index entry becomes the concatenation of all data values from each column
We can create any number of indexes on a same table with different order of columns

Alter Index
This is used to rebuild the index on table
Alter index ind1 rebuild

Database Triggers

A database trigger is a stored procedure that is fired when an insert, update or delete statement is
issued against the associated table.
CREATE
Create or replace trigger trigger_name [before/after] [insert/update/delete] on table-name
[for each statement/ for each row] [when <condition>];
FOR EACH STATEMENT is default.
There are 2 system variables---:new and :old. Which returns the old and new value
of the column data in table.
The values in these variables can be used in database triggers for manipulation

ALTER
We can enable, disable and compile the triggers by using ALTER statement
When trigger is created by default it is enable only.
Alter trigger_name enable/disable/compile;

DROP
We can drop the triggers by using DROP statement
drop trigger_name;

View
A view is imaginary table and it contains no data and the tables upon which a view is based are
called base tables.
Create
Create view view_name(column alias) as query with check option constraint)
Alter
Alter is used to compile the view
Alter view view_name compile

Advantages of views
They provide table security by restricting access to a predetermined set of rows or
columns of a table
We can do insert/update/delete on views as similar to tables provided with some conditions.
Insert – the columns of the base table other than view columns should be null
And primary key column should be selected in view definition
Update – primary key column should be selected in view definition
Delete - primary key column should be selected in view definition

Views query can not select pseudo columns like currval and nextval.
If a view’s query contains joins, set operators, group functions and distinct clause then deletion,
updating and insertion can not be done.
The changes performed in a view will affect the base table and vice versa.

There are other types of views besides normal view


1. Partition view – view query contains UNION ALL operator
Ex .. create view view name as select … from table1 union all select … from table2

2. Object view

Synonym
A synonym is a database object, which is used an alias (alternative name) for a table, view or
sequence.
They are used to
Simplify SQL statements
Mask the name and owner of an object
Provide public access to an object
Create [public/private] synonym synonym-name for table_name
Public – available to all database users
Private – Available to only that user

Sequence

A sequence is a database object, which can generate unique, sequential integer values.
It can be used to automatically generate primary key or unique key values.
A sequence can be either an ascending or a descending sequence.

Create
Create sequence seq_name increment by n start with n [maxvalue n][nomaxvalue][minvalue
n][nominvalue] [cycle/ nocycle][cache/nocache][order][noorder];
Cycle – means once it reaches max value it starts again at min value – default is nocycle
Cache – means oracle pre-allocates sequence numbers and keeps them in memory for
faster access.
To get the current value is sequence_name.currval
To get the next value is sequence_name.nextval
Alter
Alter sequence seq_name increment by n start with n [maxvalue n][nomaxvalue][minvalue
n][nominvalue] [cycle/ nocycle][cache/nocache][order][noorder];

Locks
Locks are used to ensure data integrity while allowing maximum concurrent access to the data by
unlimited users

Types of locks According to the way locks are applied


1. Implicit locking
2. Explicit locking

Implicit locking

This will be done automatically by DBA based on the DDL or DML processed.
Readers of data do not wait for other readers or writers.
Writers of data do not wait for other readers
Writers of data have to wait for other writers if they attempt tp update the same rows at
the same time.
Explicit locking

A lock can be put by an operator or trigger is called explicit locking


Oracle provides two levels of automatic locking Table level & row level

There are two ways of locking the table or rows


1. Select ………for update (row level locking)
2. Lock table statement (table level locking)

1. Select … for update


Can not be used with distinct and group by clause
Can not be used with set operators and group functions
Row level locking.

2 Lock table statement


Table level locking
Lock table table_name in share/share update/exclusive mode;

Share lock
Locks the table allowing other users to only query but not insert, update
or delete rows in table
Multiple users can place share locks on the same table at the same time

Share update lock


Locks the only rows that are effected.
Allowing other users to query, insert, update, delete or even lock the
other rows in table

Exclusive lock
Same as share lock but only one user can place this lock mode on the
table at a time. Where as share lock can be placed, by many users on
same table

If the rows or table , are already locked by another user, then Oracle will wait for
the lock to be released by a commit or rollback statements. How ever we can use
NOWAIT option to cause Oracle to terminate the statement.
A rollback to save point releases all locks acquired, up to the named save point
are released

Data manipulation language

Insert

Used to add rows in to table.


Insert into table _name values (values_list)

If only values for some columns are to be inserted then we have to use
Insert into table _name (column_list) values(values);

For character and date values to be encoded in quotes.

Insert with substitution variables


Insert into table _name values(&Column_name)
It will prompt for every time.

Insert into table _name values(&&Column_name)


It will prompt for first time and that value will be used for subsequent records.

Inserting a date value into table

When inserting a date value the format dd-mon-yy is usually used. The date contains time
information default midnight 00:00:00
For retrieval or inserting date format could be used.

To insert
Insert into table_name values(to_date(‘11/11/2001’,’dd/mm/yyyy’));

To retrieve
Select to_char(date_field,’mm/dd/yyyy’) from table_name..
Any format can be used.

Insert from other table

Insert into table (column list) select columns from table.

Update

Update statement allows to change values in the table

Update table_name
Set Column_name = [value/Column_name/expression/subquery]
Where condition

Delete

Delete from table [where condition] or


Delete table [where condition]

Commit work

• Make changes in the current transaction permanent.


• Erases all save points in the transaction
• Ends the transaction
• Releases the transaction locks
• Key word work is optional.
• Automatic commit occurs when DDL command is given or normal disconnects from the
database.
• We can use auto commit by using set command
• Set auto commit on, Set auto commit off

Save Point

Savepoint s1

Savepoint s2

• Can be used to divide a transaction into smaller portions


• The maximum save points for user process is 5. This limit can be changed.
• If you create second save point with same name then first save point will be deleted

Rollback [work] to [Savepoint]

Rollback statement is used to undo work

Ends the transaction


Undoes all changes in current transaction
Erased all save points in that transaction

Releases the transaction locks

Query language

Arithmetic operators

Select ename , sal * 12 from EMP;


Select ename , sal + 12 from EMP;
Select ename , sal - 12 from EMP;
Select ename , sal / 12 from EMP;

Concatenation operator (||)

More than one column can be concatenated to make one single column
Select empno||ename from EMP
Select empno||”-“||ename from EMP

Logical operators

= > >= < <= <> !=

SQL operators

Between .. And
Select ename , sal / 12 from EMP where sal between 1000 and 2000;
In
Select ename , sal / 12 from EMP where sal in(1000,2000);
Select ename , sal / 12 from EMP where sal in(select query);
Like
Select ename , sal / 12 from emp where ename like ‘%smith%’;
Select ename , sal / 12 from emp where ename like ‘------‘; it gives all records with name
length is 5 characters
Is null
Select ename , sal / 12 from EMP where sal is null;

Conditional operators
And, Or, Not

Set operators

Rules for using set operators


1. select statements must select the same number of columns
2. corresponding columns must be of the same data type
3. column names from the first set will come as headings
4. order by clause appears at the end of the statement

Restriction
Filtering the rows from data table using where condition.
All rows can be retrieved or only some rows that satisfy the condition can be retrieved.
Projection
Selecting only some columns from data table.
Product (cartition product)
is the result from two sets of data are concatenated often produces a very large new set
Union
Results from more than one SQL query can be combined.
Select ename from emp where sal => 1000
Union
Select ename from emp where sal < 2000

Only unique rows will be retrieved.


Union all
Equivalent to product - returns all rows from all sets
Intersection
Results from more than one SQL query can be combined.
Select ename from emp where sal => 1000
intersection
Select ename from emp where sal < 2000
Only common rows will be retrieved.

Difference(minus)
Results from first set after discarding the common rows.
Select ename from emp where sal => 1000
minus
Select ename from emp where sal < 2000
Divide
Join
It is the result when rows from 2 sets of data are concatenated according to specified
conditions.
3 types of joins
simple join
equi join – join with ‘=’ symbol
Non-equi join – join with other than ‘=’ symbol
self join
select emp.emp_no,e.ename
from emp, emp e
where emp.emp_no = e.mgr_no
outer join
an outer join returns all the rows returned by simple join as well as those rows
one table that do not match any row from the other table. The symbol (+)
represents outer join.
select c.*, o.*
from customer c,order_info o
where c.cutid (+)= o.custid

In addition to c records , this statement will return rows from o which does not
have matching rows in c
If you want records from a table, do not put + sign for that table.
Distinct

To eliminate duplicate values in the result we can use distinct.


Select distinct empname from emp;

Multiple columns could be specified after distinct. Distinct affects all selected columns
Must be given immd after select.

Order by

To order the result from the SQL query order by clause can be used.
Order by must be the last clause in the select statement

Select ename from emp order by eno

Default order is ascending.


We can specify the order by ASS or Desc
We can use more than one column for order by

To order by a column, it is not necessary to have selected it.

Column aliases

We can have our own headings for SQL result. By default Column_name will be heading
Select ename sal * 12 MYSAL, Comm from emp;
No spaces exists in alias unless the alias in “ “

Functions

Types of functions

• Character
• Number
• Date
• Conversion
• Function that accept any data type
• Group or aggregate

Character functions

Chr(n)
It returns the character having the binary equivalent to n in the database
character set.
Chr(67) returns ‘C’
ASCII(‘C’)
It returns the numeric value in the database character set.
ASCII(‘C’) returns 67
Lower(Column_name/value)
Upper(Column_name/value)
Initcap(Column_name/value)
Concat(char1,char2)
Lpad(column_name, n,’ string’)
Pads the column or literal value from the left to a total width of n character
positions. The leading space are filled with string
Select lpad(ename,20,’*’)
***************smith
If ename is 10 characters long then 10 * s will be padded at left of the ename
Rpad (column_name, n, ’string’)
Pads the column or literal value from the right to a total width of n character
positions. The tailing space are filled with string
Select rpad(ename,20,’*’)
smith***************
If ename is 10 characters long then 10 * s will be padded at right of the ename
Substr(column-name/value,pos,number of characters)
If number of characters are omitted, it returns up to end of the string
Instr(Column_name/value,’string’)
Gives the character Position of the first accurrence of the string in the column or
value.

Select dname ,instr(dname,’A’) from dept;


Dname instr(dname,’A’)
Accounting 1

Instr(col/value,’string’,pos,n)
Gives the character Position of the first accurrence of the string in the
column or value starting at the pos.

Select dname ,instr(dname,’C’,1,2) from dept;


Dname instr(dname,’c’,1,2)
Accounting 3
LTRIM
Ltrim(Column_name/val)—trims leading spaces
Ltrim(Column_name/val,’char’) – trims leading specified character in the value
RTRIM
Rtrim(Column_name/val)—trims tailing spaces
Rtrim(Column_name/val,’char’) – trims tailing specified character in the value
Soundex
Returns a character string sound a like
Select ename from emp where Soundex(ename) = ‘FRED’
Ename
Ford
Length
Returns length of the string in characters.
Translate
Translate(col/val,’fromchar’,’tochar’)
Used for character substitution
If tochar is omitted, from char will be removed from the column/value

Replace
replace(col/val,’fromstring’,’tostring’)
Used for string substitution
If tostring is omitted, fromstring will be removed from the column/value
Replace is superset of translate

Number functions

Round(col/val,n)
N is the number of positions after decimal to be rounded.
If n is omitted then no decimal points.
Round(45.932) = 46
Round(45.932,1) = 45.9
Round(42.932,-1) = 40
Round(42.932,-2) = 42.93

Trunc(col/val,n)
N is the number of positions after decimal to be rounded.
If n is omitted then no decimal points.
trunc(45.932) = 45
trunc(45.932,1) = 45.9
trunc(42.932,-1) = 40
trunc(42.932,2) = 42.93
Ceil
Ceil(col/val)
Finds the smallest integer greater than or equal to the column/value
Ceil(45.980) = 46

Floor
floor(col/val)
Finds the largest integer less than or equal to the column/value
Floor(46.980) = 46

SQRT
Sign
Power(col/val,n)

Abs(col/val)
Finds the absolute value
Abs(-35) = 35

Mod(value1,value2)

Date Functions

Date + number = adds number of days to date and gives a date


Date – number= subtracts number of days from date and gives a date
Date – Date = gives number of days

Months_between(date1,date2) – returns the number of months between the two dates


Add_months(date1,n) – returns the date after adding n months to the date1

Next_day(date1,day of week/day number) – gives date of the next day after that day of
week or after that many days
Nextday(sysdate,3)
Nextday(sysdate,’Monday’)

Last_day(date1) – return the date of the last day in the month mentioned in date1

New_time(date1, Z1, Z2 ) – returns the date and time in time zone


Z1 and Z2 can be the following values
EST, EDT – eastern standard or daylight time
CST, CDT – central standard or daylight time
MST, MDT – mountain standard or daylight time
PST, PDT – pacific standard or daylight time
GMT – greenwich mean time

Sysdate – return the current date of the server

Conversion Functions

To_char(date/number,’format’)
To_number(char contains number)
To_date(‘char’,’format’)

Functions that accept any datatype as argument

Decode(col/expression,search1,result1,search2,result2 ……default)
Decode(job,’clerk’,’is a clerk’,’manager’,’is a manager’… ‘supervisor’)

NVL function

If a column in a row is lack of data in it, then the data will be said to be null
A null value take up one byte of internal storage overhead
If a column has null value we can see it any more in SQL result.
We can handle this using NVL function.
Select ename,sal* 12 + nvl(comm,0) annsal from emp
If Comm is null it returns 0 as a value.

Greatest(col/val1,col/val2)
Least(col/val1,col/val2)

Group /Aggregate functions


AVG - Select avg(sal) from emp;
Count-
Max-
Min-
Stddiv-
Sum-
Group by

Select * from emp where sal = 1000


Group by job

Any column or expression in the select list, which is not an aggregate function, must be in the
group by clause

Having clause

Using the having clause we can specify which group to be displayed.


To show the average salary for all dept employee more than 3 people
Select dept no, avg(sal)
From emp group by dept no
Having count(*) > 3;

Data dictionary

It consists of a set of tables and views which provides read only reference guide about the
database.

Transaction processing

A transaction is an operation against the database, which comprises a series of changes to one or
more tables

Two classes of transactions


1. DML transaction: Consists of any number of DML statements
2. DDL transaction : which consists of one DDL statement

For every transaction either all the changes made to the database are made permanent or none of
the changes are carried out.

A transaction starts with a DML or DDL statement and ends with any of the following
Commit/rollback
DDL command
Certain errors
Log off
Exit from SQL
Machine failure

When a transaction is interrupted by a serious error for example a system failure, the entire
transaction is automatically rolled back.

Pseudo-columns

Sysdate
Level – used in tree SQL
Nextval – next value in sequence after incrementing the current val by the specifed value in
increment by clause. First time it gives the initial value that is min value given in sequence definition

Currval – current value of sequence

Dual
Dual is a dummy table owned by sys user
It contains one column named dummy and one row with the value ‘X’

Sub Query
A sub Query is a select statement that is nested with in another select statement and which return
result set

Ex: select dept_id from dept where emp_id = (select emp_id from emp where ename = ‘SMITH’)
We can use comparison operators =, <=, >=. <> for sub queries which returns single row
We can use operators in, not in, exists, not exists, for sub queries which returns multiple rows

The limit on the levels of nesting for a sub Query is 255

Sub query should not have order by clause

Correlated sub Query

A Correlated sub Query is a nested sub Query which is executed for each candidate row.
A Correlated sub Query is identified by the use of an outer query column in the inner query
predicate clause

Ex : select empno , ename, sal


from emp E
where sal > (select avg(sal) from emp where dept no = E.Dept no);

NOT EXTSTS Vs NOT IN

NOT EXISTS is more reliable if the sub query returns any Null values. Since not in condition
evaluates to false when nulls are included in the compared list.

TREE walking

A Relational database does not store records in a hierarchical way. Tree walking is a process,
which enables the hierarchy to be constructed

EX: Select level, dept no, empno, ename, job, sal


From emp
Connect by prior empno = mgr
Starts with MGR is null;

Terminology
Level - is a pseudo column which displays how far each node is removed from starting node
Connect by – specifies the columns where the relation ship between rows exists. This clause is
requested for a tree walk.
Prior – establishes the direction in which the tree is walked
Starts with – specifies where to start the walk.

How to find duplicate rows in a table


Select columns list….
From table1
Graoup by col1
Having count(*) > 1
How to delete duplicate rows in a table
Delete from table1
Where col1 = value and
Rowid < (select max(rowid) from table1 where col1 = value)

How to find n th highest in a table


Select salary
From emp e1
Where (n-1) = (select count(*)
From emp
Where emp.salary > E1.salary)

Or
Select level,max(sal)from emp
Where level = n
Connect by prior sal > sal
Group by level

How can we store a bmp file in database?

What is SQL buffer


An SQL Command is entered at the SQL prompt and subsequent lines are numbered. This is
called SQL buffer.
Only one statement can be current at any time with in buffer and it can be run in a number of ways.

How to check the current year is leap year or not


Select year,
decode(mod(year,4),0,
Decode(mod(year,400),0,’leap year’,
Decode(mod(year,100),0,’not a leap
year’,’leapyear’),’Not a leap year’) as leap_year_indicator

Set operators
Set auto [commit] on/off

PL/SQL

PL/SQL is integrated with the database server, So that the PL/SQL code can be processed quickly
and efficiently.
PL/SQL is programmatic SQL by adding some conditions to normal SQL and make it in
programmable structure.
It has both capabilities of 3rd generation of program skills and 4th generation of powerful SQL
PL/SQL is based on ADA
version is released 1.0 with Oracle 6.0
version is released 2.0 with Oracle 7.0
version is released 2.1 with Oracle 7.1
version is released 2.2 with Oracle 7.2
version is released 2.3 with Oracle 7.3
version is released 8.1 with Oracle 8.0

PL/SQL consists of One or more blocks

A block may be either an anonymous block or a subprogram

Definition of anonymous block

Declare
Temp_count number;
Pi constant number (9,5): =3.14
Variable_name tablename.column %type (this is data type of column of table)
Begin
statements
Exception handling

End

Subprograms may be procedures or triggers or functions

Host variable
Host variables includes variables declared in pre compiler programs, screen fields in SQL * forms,
and SQL plus bind variables
A column must prefix host variables, to distinguish them from declared PL/SQL variables. Ex
:fieldname

Data type conversion


PL/SQL attempts to convert data types dynamically if they are mixed with in a statement
Ex: If a number value is assigned to a char variable, then the number is dynamically translated to
char.
Character Variable = number data/Date data (accepted)
Number variable = character data (not accepted)
Date variable = character data contains date

SQL commands in PL/SQL


Each statement must be terminated by a semicolon
DDL commands are not allowed in PL/SQL
Select statement must return a single row
DML commands may process multiple rows

Testing SQL statements


Whenever SQL commands are issued , an area of memory is opened in which the command may
be processed. A cursor is an identifier to this area. SQL is a implicit cursor

Attributes of SQL implicit cursor


SQL%rowcount – the number of rows processed by the statement
SQL%found – true or false
SQL%notfound – true or false

Control statements
If statement
If condition then
Statements
Elseif condition
statements
Else
Statements
End if

Goto

For loop
For counter in 1: 200
Loop
Statements
End loop

//Loop fires in reverse direction


For counter in reverse 1: 200
Loop
Statements
End loop

// for cursors
For temp_variable in cur_1
// where cur_1 is the cursor name. This loop will open and fetch and close the cursor
Loop
End loop

While loop
While condition
Loop
End loop

Exit statement

Cursors
A work area called SQL area to execute SQL statements and store processing information
2 types of cursors
Implicit
Implicit will be created by database whenever SQL statement executes on server
Explicit cursor
Declare
Cursor c1 is select ename from emp;
Open c1;
Fetch c1 into :filed1;
Close c1;

Cursor Attributes
%found
%notfound
%rowcount
%isopen

exception handling

exceptions are identifiers in PL/SQL which may be raised during the execution of a block to
terminate its main body of actions. But we may specify an exception handler to perform final
actions before the block terminates

2 main classes of exception.

Predefined
Dup-val-on-index
Invalid-cursor
No-data-found

user defined
declare
begin
select statement
if nodata then raise insert-data

exception
when insert-data
insert into table.
end

Subprograms

Subprograms are named PL/SQL blocks that can accept parameters and can be invoked whenever
required.
PL/SQL supports two types of subprograms
Procedures & functions

Differences of function and procedure


Function should return a value. Procedure does not need of it
Function can be nested Procedure cannot be nested
Function can be used a part of expression procedure can not be..
Function is used to compute a value procedure is used to perform a task
Function can be used in sql statement Procedure can not be

Dead Lock

A dead lock occurs when two users have a lock, each on a separate object, and each wants to
acquire a lock on the other user’s object. When this happens, the first user has to wait for the
second user to release the lock and the same time second user will not release the lock until the
lock on the first users object is freed
Oracle detects deadlock automatically and solves the problem by aborting one of the two
transactions

What is the difference between %type and %rowtype


%rowtype is used to declare a record with the same types as found in the specified database table, view or
cursor.
Declare
V_emp_record emp%rowtype

%Type is used to declare a field with the same types as that of specified table’s column
Declare
V_emp_no emp.empno%type

How to print from PL/SQL code


Set serveroutput on
Begin
Dbms_output.putline(‘the code is perfect’);
End;

How to use dynamic SQL with in PL/SQL


Create or replace procedure dynsql as
Cur integer;
Rc integer;
Begin
Cur := DBMS_SQL.open_cursor;
DBMS_SQL.PARSE(cur,’ create table x ‘, DBMS_SQL.NATIVE);
Rc:= DBMS_SQL.EXECUTE(cur)
DBMS_SQL.CLOSE_CURSOR(cur)

Query Optimization in Oracle

Optimization is the process of choosing the most efficient way to execute a SQL statement.
This is an important step in the processing of any data manipulation language (DML) statement:
SELECT, INSERT, UPDATE, or DELETE.
Many different ways to execute a SQL statement often exist, for example, by varying the order in which
tables or indexes are accessed.
A part of Oracle called the optimizer chooses what it believes to be the most efficient way.
The optimizer evaluates a number of factors to select among alternative access paths.

Cost-Based and Rule-Based Optimization


To choose an execution plan for a SQL statement, the optimizer uses one of two approaches:
Cost-based or rule-based.
The Cost-Based Approach
Using the cost-based approach, the optimizer determines which execution plan is most efficient by
considering available access paths and factoring in information based on statistics in the data dictionary for
the schema objects (tables, clusters, or indexes) accessed by the statement.
The cost-based approach also considers hints, or optimization suggestions placed in a Comment in the
statement.
Conceptually, the cost-based approach consists of these steps:
The optimizer generates a set of potential execution plans for the statement based on its available access
paths and hints.
The optimizer estimates the cost of each execution plan based on the data distribution and storage
characteristics statistics for the tables, clusters, and indexes in the data dictionary.
The cost is an estimated value proportional to the expected resource use needed to execute the statement
using the execution plan.
The optimizer calculates the cost based on the estimated computer resources, including (but not limited to)
I/O, CPU time, and memory that are required to execute the statement using the plan.
The optimizer compares the costs of the execution plans and chooses the one with the smallest cost.
When to Use the Cost-Based Approach
In general, you should use the cost-based approach for all new applications;
Cost-based optimization can be used for both relational data and object types.

The rule-based approach is provided for applications that were written before cost-based optimization was
available.

The OPTIMIZER_MODE Initialization Parameter


The OPTIMIZER_MODE initialization parameter establishes the default behavior for choosing an
optimization approach for the instance. This parameter can have these values:
CHOOSE The optimizer chooses between a cost-based approach and a rule-based approach based on
whether the statistics are available for the cost-based approach. If the data dictionary
contains statistics for at least one of the accessed tables, the optimizer uses a cost-based
approach and optimizes with a goal of best throughput. If the data dictionary contains no
statistics for any of the accessed tables, the optimizer uses a rule-based approach. This is
the default value for the parameter.
ALL_ROWS The optimizer uses a cost-based approach for all SQL statements in the session regardless
of the presence of statistics and optimizes with a goal of best throughput (minimum resource
use to complete the entire statement).
FIRST_ROWS The optimizer uses a cost-based approach for all SQL statements in the session regardless
of the presence of statistics and optimizes with a goal of best response time (minimum
resource use to return the first row of the result set).
RULE The optimizer chooses a rule-based approach for all SQL statements issued to the instance
regardless of the presence of statistics.

You might also like