0% found this document useful (0 votes)
22 views

Oracle SQL II

TCL (Transaction Control Language) commands are used to manage transactions in databases. The main TCL commands in SQL are COMMIT, ROLLBACK, and SAVEPOINT. COMMIT makes all changes permanent, ROLLBACK undoes changes to the last commit or savepoint, and SAVEPOINT temporarily stores a point in the transaction that ROLLBACK can revert to. CASE statements function like IF/THEN/ELSE and return a value based on conditions being true.

Uploaded by

srilekha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Oracle SQL II

TCL (Transaction Control Language) commands are used to manage transactions in databases. The main TCL commands in SQL are COMMIT, ROLLBACK, and SAVEPOINT. COMMIT makes all changes permanent, ROLLBACK undoes changes to the last commit or savepoint, and SAVEPOINT temporarily stores a point in the transaction that ROLLBACK can revert to. CASE statements function like IF/THEN/ELSE and return a value based on conditions being true.

Uploaded by

srilekha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Why TCL?

Transaction Control Language(TCL) commands are used to manage


transactions in the database.

These are used to manage the changes made to the data in a table
by DML statements. It also allows statements to be grouped
together into logical transactions.

TCL commands in Oracle SQL


There are following 3 commands in SQL :

1.Commit

2.Rollback

3.Savepoint

1. COMMIT
This command is used to make a transaction permanent in a database. So it can be said
that commit command saves the work done as it ends the current transaction by making
permanent changes during the transaction. The syntax for this command is as below.

COMMIT;

For instance, we want to update the location of an employee in the table “EMPLOYEE”.
Sample EMPLOYEE table is given below:

EMP_ID EMP_NAME EMP_LOC

1000 Amit Pune

2000 Raju mumbai

3000 Ram Chennai


Table
Let us update the EMP_ LOC for Amit as below:

Query:
UPDATE EMPLOYEE SET EMP_ LOC = 'Chennai' WHERE EMP_NAME= 'Amit';
COMMIT;
The update transaction is completed with the commit command as above and the usage
of the above statements will update the location of the employee ‘Amit’ and the change
will be saved in the database permanently.
The updated table is as shown below:

EMP_ID EMP_NAME EMP_LOC

1000 Amit Chennai

2000 Raju mumbai

3000 Ram chennai

Updated Table

2. ROLLBACK
This command is used to restore the database to its original state since the last
command that was committed. The syntax of the Rollback command is as below:

ROLLBACK;
Also, the ROLLBACK command is used along with savepoint command to leap to a save
point in a transaction. The syntax for the same is as below:

ROLLBACK TO <savepoint_name>;
Let us take the example of the EMPLOYEE table as cited above. Let us consider that we
have updated EMP_LOC for Raju to Bangalore later and realize that the update was
done mistakenly as below. Then we can restore the EMP_LOC for ‘Raju’ to Hyderabad
again by using the Rollback command as below.

Query:
UPDATE EMPLOYEE SET EMP_LOC= 'Bangalore' WHERE EMP_NAME = 'Amit';
ROLLBACK;
After the wrong update the table is as below:

EMP_ID EMP_NAME EMP_LOC

1000 Amit Stockholm

2000 Raju Bangalore

3000 Ram Hyderabad

Before Rollback

After the Rollback is performed, the location for Amit is restored to the last committed
state as shown below.

After the Rollback is performed, the location for Amit is restored to the last committed
state as shown below.
EMP_ID EMP_NAME EMP_LOC

1000 Amit Hyderabad

2000 Raju Bangalore

3000 Ram Hyderabad


After Rollback
3. SAVEPOINT
This command is used to save the transaction temporarily. So the users can rollback to
the required point of the transaction. The syntax for using this command is as below:

SAVEPOINT savepoint_name;
Let us take the example of a table “ORDERS” with columns as ORDER_ID and
ITEM_NAME.

ORDER_ID ITEM_NAME

100 Laptop

200 Mobile
Order table
Let us insert the below values to the ORDERS table below and perform the updates
using savepoint.

Query:
INSERT INTO ORDERS VALUES ('300' , 'CELL PHONE');
COMMIT;
UPDATE ORDERS SET ITEM_NAME = 'SMART PHONE' WHERE ORDER_ID= '300';
SAVEPOINT A;
INSERT INTO ORDERS VALUES ('400' , 'mixer');
SAVEPOINT B;
Now the ORDERS table will be as below:
Now the ORDERS table will be as below:

ORDER_ID ITEM_NAME

100 LAPTOP

290 MOBILE

300 SMART PHONE

400 MIXER
Savepoint
Now we can use the SAVEPOINT command to Rollback the transaction. Let us Rollback
the transaction to savepoint A.
Query:
ROLLBACK TO A;
The ORDERS table will be as below:

ORDER_ID ITEM_NAME

100 LAPTOP

200 MOBILE

300 SMART PHONE

Savepoint
The TCL commands in SQL provides the privilege to rollback the transaction if the data
is updated in the tables by mistake. It performs a permanent change to the database by
locking the data using the commit command. Also with the help of savepoint command,
users can save the transactions temporarily and if required, can also perform rollback
using the savepoint.

TCL commands in SQL helps in maintaining the consistency and integrity of the data.
The database can be restored to the last committed state as well as modifications made
can be saved permanently with the help of TCL. The developers should have a keen
understanding of TCL to build a robust system. I hope this article finds you very
informative and helpful to you guys. If you like this article or if you have any issues with
the same kindly comment in comments section.

 CASE Statement

Description
In SQL , the CASE statement has the functionality of an IF-THEN-ELSE statement.
You can use the CASE statement within a SQL statement.

Syntax
The syntax for the CASE statement in SQL
CASE expression

WHEN value_1 THEN result_1


WHEN value_2 THEN result_2
...
WHEN value_n THEN result_n

ELSE result

END

OR

CASE

WHEN condition_1 THEN result_1


WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n

ELSE result

END

Parameters or Arguments
expression
The expression that will be compared to each of the values provided. (ie:
value_1, value_2, ... value_n).
value_1, value_2, ... value_n
The values that will be used in the evaluation. Values are evaluated in the
order listed. Once a value matches expression, the CASE statement will
execute the corresponding statements and not evaluate any further.
condition_1, condition_2, ... condition_n
The conditions that will be evaluated. Conditions are evaluated in the order
listed. Once a condition is found to be true, the CASE statement will return the
result and not evaluate the conditions any further. All conditions must be the
same datatype.
result_1, result_2, ... result_n
The value returned once a condition is found to be true. All values must be the
same datatype.
Note

 If no value/condition is found to be TRUE, then the CASE statement will return


the value in the ELSE clause.
 If the ELSE clause is omitted and no condition is found to be true, then the
CASE statement will return NULL.
 Conditions are evaluated in the order listed. Once a condition is found to be
true, the CASE statement will return the result and not evaluate the conditions
any further.
 You can not use the CASE statement to control program flow, instead,
use loops and conditional statements.

Example
You could use the CASE statement in a SQL statement as follows: (includes
the expression clause)

SELECT id,name,
CASE id
WHEN 1 THEN 'one’
WHEN 2 THEN 'two’
ELSE 'others'
END
FROM emp;

Or you could write the SQL statement using the CASE statement like this: (omits
the expression clause)

SELECT id,sal,
CASE
WHEN sal = 3000 THEN 'lowsal'
WHEN sal>3000 THEN 'highsal'
ELSE 'othersal'
END
FROM emp;
One thing to note is that the ELSE condition within the CASE statement is optional. It
could have been omitted. .
Your SQL statement would look as follows:

Comparing 2 Conditions
Here is an example that demonstrates how to use the CASE statement to compare
different conditions:

SELECT
CASE
WHEN sal < 1000 THEN 'lowsal'
WHEN name = ‘ram’ THEN 'welcome'
END
FROM emp;

Just remember that conditions are evaluated in the order listed. Once a condition is
found to be true, the CASE statement will return the result and not evaluate the
conditions any further. So be careful when choosing the order that you list your
conditions.

create table customer(id int,cname varchar(20),address varchar(20))

insert into customer values(1,'john','hyd')


insert into customer values(2,'hari','banglore')
insert into customer values(3,'sita','chennai')
insert into customer values(4,'sai','pune')
insert into customer values(5,'siva','mumbai')

simple case

select id,cname,address,
case cname
when 'john' then'johny'
when 'sita' then 'seetha'
when 'sai' then 'srisai'
else
'customers'
end as 'others'
from customer
Searched Case

select id,job,sal,
case
when sal>6000 then 'highsal'
when sal<6000 then 'lowsal'
when sal=6000 then 'moderate sal'
else
'others'
end as 'saldetails'
from emp

RANK, DENSE_RANK and ROW_NUMBER functions in


SQL
 The RANK, DENSE_RANK and ROW_NUMBER functions are used to get the
increasing integer value, based on the ordering of rows by imposing ORDER
BY clause in SELECT statement.
 When we use RANK, DENSE_RANK or ROW_NUMBER functions, the
ORDER BY clause is required and PARTITION BY clause is optional.
 When we use PARTITION BY clause, the selected data will get partitioned,
and the integer value is reset to 1 when the partition changes.

 
For this example, I have created a table called Employees in which I have added
three columns EMPID, Name, and Salary respectively. To create table and column,
as given below.
 
Creating a table 

CREATE TABLE [dbo].[Employee](  

    [EMPID] [varchar2](30) NOT NULL,  

    [Name] [varchar2](150) NULL,  

    [Salary] [number] NULL  

)   

Insert some data into this table, script as follows


1. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP101', 'Vishal', 15000)  
2. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP102', 'Sam', 20000)  
3. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP105', 'Ravi', 10000)  
4. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP106', 'Mahesh', 18000)  

The table is created and data is inserted. Now, let’s see how these about RANK,
DENSE_RANK and ROW_NUMBER functions behave.
 
For this, we can write Select statement as shown below.

1. select EMPID, Name,Salary,  
2. RANK() over (order by Salary desc) as _Rank,  
3. DENSE_RANK () over (order by Salary desc) as DenseRank ,  
4. ROW_NUMBER() over (order by Salary desc) as RowNumber from Emp
loyee  

You can see the below output that RANK, DENSE_RANK and ROW_NUMBER
functions give the same output and returning integer values based on highest salary.
 

 
 
I am assuming you have got what RANK, DENSE_RANK and ROW_NUMBER
functions do.
 
RANK vs DENSE_RANK vs ROW_NUMBER functions
 
Now, let’s see what is the difference between those functions. For this, we need to
insert some duplicate salary into this table. The script below will insert some more
data with same salary.

1. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP108', 'Rahul', 20000)  
2. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP109', 'menaka', 15000)  
3. INSERT [dbo].[Employee] ([EMPID], [Name], [Salary]) VALUES 
('EMP111', 'akshay', 20000)  

Now, you can see the table which has got some duplicate salary records.
 

 
Now, we can see the different between RANK, DENSE_RANK and ROW_NUMBER
functions by executing the same SELECT statement which we executed before.

 
 
 
Here, in above figure, you can see that ROW_NUMBER function does not have any
changes. It keeps increasing integer by one and it is not caring about duplicate
values.
 
In RANK, DENSE_RANK function, it is looking for duplicate values. The integer
value is increasing by one but if the same value (Salary) is present in the table, then
the same integer value is given to all the rows having the same value(Salary), as
marked in sky blue color.
In RANK function, the next row after the duplicate values (salary),marked in red
color, will not give the integer value as next rank but instead of it, it skips those ranks
and gives what is the next incremented rank. In the above case, the first three values
are having same salary so it gives same rank to them but in next row, it gives as 4, It
skips two and three as first three rows have same ranks.
 
In DENSE_RANK function, it will not skip any rank. This means the next row after
the duplicate value (salary) rows will have the next rank in the sequence.
 
Sequence

Description
In Oracle, you can create an autonumber field by using sequences. A sequence is
an object in Oracle that is used to generate a number sequence. This can be useful
when you need to create a unique number to act as a primary key.

Create Sequence
You may wish to create a sequence in Oracle to handle an autonumber field.

Syntax
The syntax to create a sequence in Oracle is:

CREATE SEQUENCE sequence_name


MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
Nocycle/cycle
Nocache/cahe;

INCREMENT BY

Specify the interval between sequence numbers. This integer value can be any
positive or negative integer, but it cannot be 0. This value can have 28 or fewer
digits. The absolute of this value must be less than the difference
of MAXVALUE and MINVALUE. If this value is negative, then the sequence descends. If
the value is positive, then the sequence ascends. If you omit this clause, then the
interval defaults to 1.
START WITH

Specify the first sequence number to be generated. Use this clause to start an
ascending sequence at a value greater than its minimum or to start a descending
sequence at a value less than its maximum. For ascending sequences, the default
value is the minimum value of the sequence. For descending sequences, the default
value is the maximum value of the sequence. This integer value can have 28 or
fewer digits.

MAXVALUE

Specify the maximum value the sequence can generate. This integer value can have
28 or fewer digits. MAXVALUE must be equal to or greater than START WITH and must
be greater than MINVALUE.

NOMAXVALUE

Specify NOMAXVALUE to indicate a maximum value of 1027 for an ascending sequence


or -1 for a descending sequence. This is the default.

MINVALUE

Specify the minimum value of the sequence. This integer value can have 28 or
fewer digits. MINVALUE must be less than or equal to START WITH and must be less
than MAXVALUE.

NOMINVALUE

Specify NOMINVALUE to indicate a minimum value of 1 for an ascending sequence or


-1026 for a descending sequence. This is the default.

CYCLE

Specify CYCLE to indicate that the sequence continues to generate values after


reaching either its maximum or minimum value. After an ascending sequence
reaches its maximum value, it generates its minimum value. After a descending
sequence reaches its minimum, it generates its maximum value.

NOCYCLE

Specify NOCYCLE to indicate that the sequence cannot generate more values after
reaching its maximum or minimum value. This is the default.

CACHE

Specify how many values of the sequence the database preallocates and keeps in
memory for faster access. This integer value can have 28 or fewer digits. The
minimum value for this parameter is 2. For sequences that cycle, this value must be
less than the number of values in the cycle. You cannot cache more values than
will fit in a given cycle of sequence numbers.
(

NOCACHE

Specify NOCACHE to indicate that values of the sequence are not preallocated. If you
omit both CACHE and NOCACHE, the database caches 20 sequence numbers by default.

ORDER

Specify ORDER to guarantee that sequence numbers are generated in order of


request. This clause is useful if you are using the sequence numbers as timestamps.
Guaranteeing order is usually not important for sequences used to generate primary
keys.

ORDER isnecessary only to guarantee ordered generation if you are using Oracle


Database with Real Application Clusters. If you are using exclusive mode,
sequence numbers are always generated in order.
NOORDER

Specify NOORDER if you do not want to guarantee sequence numbers are generated in


order of request. This is the default.

Example

Creating a Sequence: Example


CREATE SEQUENCE customers_seq
START WITH 1000
INCREMENT BY 1
NOCACHE
NOCYCLE;

You might also like