Beruflich Dokumente
Kultur Dokumente
m
PRACTICAL 1
TO STUDY DDL-CREATE AND DML-INSERT COMMANDS
.co
DDL (Data Definition Language)
It is a set of SQL commands used to create, modify and delete database objects such as tables,
views, indices, etc.
ss
It is normally used by DBA and database designers.
It provides commands like:
re
• CREATE: to create objects in a database.
• ALTER: to alter the schema, or logical structure, of the database.
• DROP: to delete objects from the database.
dp
• TRUNCATE: to remove all records from the table.
It provides command like SELECT. This command is a heart of SQL, and allows data
retrieval in different ways.
It is set of SQL commands used to control access to data and database. Occasionally DCL
s:/
m
• GRANT: to give access privileges to users on the database .
• REVOKE: to withdraw access privileges given to users on the database.
.co
DATA TYPES:
1. CHAR (Size): This data type is used to store character strings values of fixed length.
The size in brackets determines the number of characters the cell can hold. The
ss
maximum number of character is 255 characters. The data held is right padded with
spaces to whatever length specified.
re
2. VARCHAR (Size) / VARCHAR2 (Size): This data type is used to store variable length
alphanumeric data. The maximum character can hold is 4000 character. Inserted value
dp
will not be padded with spaces. CHAR is much faster that VARCHAR sometimes up to
50%.
3. or
NUMBER (P, S): The NUMBER data type is used to store number (fixed or floating
point). Number of virtually any magnitude may be stored up to 38 digits of precision.
The precision (p) determines the number of places to the right of the decimal. If scale is
.w
omitted then the default is zero. If precision is omitted, values are stored with their
original precision up to the maximum of 38 digits.
lit
4. DATE: This data type is used to represent date and time. To enter dates other than the
standard format, use the appropriate functions. Date time stores date in the 24-Hours
e
format. By default the time in a date field is 12:00:00 am, if no time portion is specified.
at
The default date for a date field is the first day the current month.
5. LONG: This data type is used to store variable length character strings containing up to
ajp
2GB. Long data can be used to store arrays of binary data in ASCII format. LONG
values cannot be indexed, and the normal character functions such as SUBSTR cannot be
applied. Only one LONG value can be define per table.
6. RAW: The RAW data type is used to store binary data, such as digitized picture or
/
s:/
image. Data loaded into columns of these data types are stored without any further
conversion. RAW data type can have a maximum length of 255 bytes. LONG RAW data
type can contain up to 2GB.
tp
ht
m
CONSTRAINTS:
A constraint is a rule that restricts the values that may be present in the database.
.co
Constraints can be mainly classified in to two categories.
1. Input/Output Constraints
2. Business Constraints
ss
Oracle
Constraints
re
Input/Output Business Rule
Constraints Constraints
dp
Primary Key Foreign Key Unique Key Not Null Check
• Oracle provides a primary key constraint to define primary key for a table.
constraint
• A column, defined as a primary key, cannot have duplicate values across all records
and cannot have a null value.
ajp
• Primary key helps to identify one record from another record and also helps in relating
tables with one another.
/
• If multiple columns need to be defined as primary key column, then only table level
definition is applicable.
tp
m
Primary Key Defined at Table Level using Constraint Name
.co
(
column1 datatype null/not null,
column2 datatype null/not null,
...
ss
CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column n));
re
Create Primary Key - Using ALTER statement
You can create a primary key in Oracle with the ALTER TABLE statement.
dp
ALTER TABLE table_name
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ...
column_n);
Drop Primary Key - Using ALTER statement or
You can drop a primary key in Oracle using the ALTER TABLE statement.
.w
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
lit
• This constraint is used to ensure consistency among records of the two tables.
• The table, in which a foreign key is defined, is called a foreign table, detail table or
child table.
/
• The table, of which primary key or unique key is defined, is called a primary table,
s:/
m
• Insert or update operation involving value of foreign key is not allowed, if corresponding
value does not exist in a master table.
.co
Restriction on master table :
• Master table contains a primary key, which is referred by foreign key in child table.
• Delete or update operation on records in master table are not allowed, if corresponding
ss
records are present in child table.
re
<Columnname> <Datatype>(size) REFERENCES <parenttablename>
[<columnname>][ON DELETE CASCADE]
dp
Foreign Key Defined at Table Level using Constraint Name
You can create a Foreign key in Oracle with the ALTER TABLE statement.
A foreign key with cascade delete means that if a record in the parent table is deleted, then
s:/
the corresponding records in the child table will automatically be deleted. This is called a
cascade delete in Oracle.
tp
A foreign key with a cascade delete can be defined in either a CREATE TABLE statement or
an ALTER TABLE statement.
ht
m
(
column1 datatype null/not null,
column2 datatype null/not null,
.co
...
CONSTRAINT fk_column
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ss
ON DELETE CASCADE
);
re
Create Foreign Key with ON DELETE CASCADE - Using ALTER statement
You can create a Foreign key in Oracle with the ALTER TABLE statement.
dp
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n)
REFERENCES parent_table (column1, column2, ... column_n)
ON DELETE CASCADE;
or
Drop Foreign Key - Using ALTER statement
.w
You can drop a foreign key in Oracle using the ALTER TABLE statement.
lit
Unique Constraint
ajp
• Sometime there may be requirement that column cannot contain duplicate values.
• A column, defined as a unique, cannot have duplicate values across all records.
• Though, a unique constraint does not allow duplicate values, NULL values can be
/
• A table can have more than one column defined as a unique column.
• If multiple columns need to be defined as composite unique column, then only table level
definition is applicable.
tp
m
Unique Key Defined at Column Level using Constraint Name
.co
Unique Key Defined at Table Level using Constraint Name
ss
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
re
...
dp
Create Unique Key - Using ALTER statement
You can create a Unique key in Oracle with the ALTER TABLE statement.
ALTER TABLE table_name or
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ...
column_n);
.w
Drop Unique Key - Using ALTER statement
You can drop a unique key in Oracle using the ALTER TABLE statement.
lit
Check constraint
• The check constraint is used to implement business rule. So, it is also called business rule
constraint.
• Example of business rule: A balance in any account should not be negative.
/
m
Check Constraint Defined at Column Level using Constraint Name
.co
Check Constraint Defined at Table Level using Constraint Name
ss
(
column1 datatype [ NULL | NOT NULL ],
column2 datatype [ NULL | NOT NULL ],
re
...
dp
Create Check Constraints - Using ALTER statement
You can create check constraints in Oracle with the ALTER TABLE statement.
ALTER TABLE table_name
or
ADD CONSTRAINT constraint_name CHECK (column_name condition)
[DISABLE];
.w
Drop Check Constraints - Using ALTER statement
You can drop a unique key in Oracle using the ALTER TABLE statement.
lit
• Such a column become a mandatory (compulsory) column and cannot be left empty for
any record.
tp
m
Table-1: Countries_____
.co
CA Canada 2
DE Germany 1
UK United Kingdom 1
US United States of America 2
ss
CREATE TABLE COUNTRIES_____
(COUNTRY_ID CHAR(2),
re
COUNTRY_NAME VARCHAR2(40),
REGION_ID NUMBER(4));
dp
or
.w
lit
m
ADD REGION_ID AS FOREIGN KEY using Alter query
.co
Table-2: Departments_____
ss
DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID
re
50 Shipping 124 1500
60 IT 103 1400
dp
80 Sales 149 2500
90 Executive 100 1700
110 Accounting 205 1700
190 Contracting or - 1700
m
.co
ss
re
ADD DEPARTMENT_ID AS PRIMARY KEY
dp
ADD DEPARTMENT_NAME AS NOT NULL
or
ADD Location_ID AS Foreign Key
.w
lit
Table-3: Employees_____
ajp
PHONE_NO VARCHAR2(20),
HIRE_DATE DATE,
s:/
JOB_ID VARCHAR2(10),
SALARY NUMBER(8,2),
COMMISSION_PCT NUMBER(2,2),
MANAGER_ID NUMBER(6),
tp
DEPARTMENT_ID NUMBER(4));
ht
m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht
m
Write Create table query using Constraints:
.co
ss
re
dp
or
.w
Write Insert query for Employees_____ Table
lit
m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht
m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht
m
.co
ss
re
dp
or
.w
lit
m
APPLY CHECK CONSTRAINTS ON SALARY where salary must not be less
that 2500/-
.co
Table-4: Jobs_____
ss
JOB_ID JOB_TITLE MIN_SALARY MAX_SALARY
re
AD_ASST Administration Assistant 3000 6000
AD_PRES President 20000 40000
AD_VP Administration Vice President 15000 30000
dp
IT_PROG Programmer 4000 10000
MK_MAN Marketing Manager 9000 15000
MK_REP Marketing Representative 4000 9000
SA_MAN
SA_REP
Sales Manager
Sales Representative
or 10000
6000
20000
12000
ST_CLERK Stock Clerk 2000 5000
.w
ST_MAN Stock Manager 5500 8500
lit
MAX_SALARY NUMBER(6));
at
m
Write Insert query for Jobs Table
.co
ss
re
dp
or
.w
e lit
at
/ ajp
m
Table 5: Job_grades_____
.co
A 1000 2999
B 3000 5999
C 6000 9999
D 10000 14999
ss
E 15000 24999
F 25000 40000
re
CREATE TABLE JOB_GRADES_____
(GRADE_LEVEL VARCHAR2(3),
LOWEST_SAL NUMBER,
dp
HIGHEST_SAL NUMBER);
m
Table 5: Job_history_____
.co
101 28-10-1993 15-03-1997 AC_MGR 110
101 21-09-1989 27-10-1993 AC_ACCOUNT 110
102 13-01-1993 24-07-1998 IT_PROG 60
114 24-03-1998 31-12-1999 ST_CLERK 50
ss
122 01-01-1999 31-12-1999 ST_CLERK 50
176 01-01-1999 31-12-1999 SA_MAN 80
176 24-03-1998 31-12-1998 SA_RE 80
re
200 17-09-1987 17-06-1993 AD_ASST 90
200 01-07-1994 31-12-1998 AC_ACCOUNT 90
dp
201 17-02-1996 19-12-1999 MK_REP 20
m
.co
ss
re
dp
or
.w
e lit
m
ADD JOB_ID AS FOREIGN KEY
.co
Table 6: Locations_____
ss
LOCATION_ID STREET_ADRESS POSTAL_CODE CITY STATE_PROVINCE COUNTRY_ID
re
1500 2011 Interiors Blvd 99236 California US
Francisco
1700 2004 Charade Rd 98199 Seattle Washington US
dp
1800 460 Bloor St. W. ON M5S 1X8 Toronto Ontario CA
Magdalen Centre, The
2500 OX9 9ZB Oxford Oxford UK
Oxford Science Park
m
Write Insert query for Locations Table
.co
ss
re
dp
or
ADD LOCATION_ID AS PRIMARY KEY
.w
lit
m
Table 6: Regions_____
REGION_ID REGION_NAME
.co
1 Europe
2 Americas
3 Asia
4 Middle East and Africa
ss
CREATE TABLE REGIONS_____
re
(REGION_ID NUMBER(4),
REGION_NAME VARCHAR2(25));
dp
or
.w
Write Insert query for Regions Table
lit
m
PRACTICAL 2
TO STUDY DQL-SELECT COMMANDS
ALIASES
.co
Oracle ALIASES can be used to create a temporary name for columns or tables.
• COLUMN ALIASES are used to make column headings in your result set easier to
ss
read.
• TABLE ALIASES are used to shorten your SQL to make it easier to read or when you
are performing a self-join (ie: listing the same table more than once in the FROM
re
clause).
dp
The syntax to ALIAS A COLUMN in
column_name AS alias_name
Note:
lit
• If the alias_name contains spaces, you must enclose the alias_name in quotes.
• It is acceptable to use spaces when you are aliasing a column name. However, it is not
generally good practice to use spaces when you are aliasing a table name.
e
• The alias_name is only valid within the scope of the SQL statement.
at
DISTINCT
ajp
The Oracle DISTINCT clause is used to remove duplicates from the result set. The
DISTINCT clause can only be used with SELECT statements.
FROM tables
[WHERE conditions];
tp
Note:
• When only one expression is provided in the DISTINCT clause, the query will return
the unique values for that expression.
ht
m
• When more than one expression is provided in the DISTINCT clause, the query will
retrieve unique combinations for the expressions listed.
•
.co
In Oracle, the DISTINCT clause doesn't ignore NULL values. So when using the
DISTINCT clause in your SQL statement, your result set will include NULL as a
distinct value.
ss
WHERE
The Oracle WHERE clause is used to filter the results from a SELECT, INSERT, UPDATE,
re
or DELETE statement.
The syntax for the WHERE clause
dp
WHERE conditions;
AND conditions or
The Oracle AND condition (also called the AND Operator) is used to test for two or more
.w
conditions in a SELECT, INSERT, UPDATE, or DELETE statement along with WHERE.
The syntax for the AND Condition
lit
WHERE condition1
AND condition2
...
e
AND condition_n;
at
Note:
• The Oracle AND condition allows you to test 2 or more conditions.
ajp
• The Oracle AND condition requires that all of the conditions (ie: condition1,
condition2, condition_n) be must be met for the record to be included in the result set.
OR conditions
/
The Oracle OR condition is used to test multiple conditions where records are returned when
s:/
any one of the conditions are met. It can be used in a SELECT, INSERT, UPDATE, or
DELETE statement along with WHERE.
tp
m
WHERE condition1
OR condition2
...
.co
OR condition_n;
Note:
• The Oracle OR condition allows you to test 2 or more conditions.
ss
• The Oracle OR condition requires that any of the conditions (ie: condition1, condition2,
condition_n) be must be met for the record to be included in the result set.
re
BETWEEN conditions
The Oracle BETWEEN conditions is used to retrieve values within a range in a SELECT,
dp
INSERT, UPDATE, or DELETE statement.
COMPARISION Operators
at
Comparison operators are used in the WHERE clause to determine which records to select.
Here is a list of the comparison operators that you can use in Oracle/PLSQL:
ajp
!= Not Equal
s:/
m
The syntax for the COMPARISION operator
SELECT *
.co
FROM table_name
WHERE column_name operator parameter/value;
IN condition/Operator
ss
The Oracle IN condition is used to help reduce the need to use multiple OR conditions in a
SELECT, INSERT, UPDATE, or DELETE statement.
re
The syntax for the IN condition
dp
Note:
• The Oracle IN condition will return the records where expression is value1, value2..., or
value_n.
or
• The Oracle IN condition is also called the Oracle IN operator.
.w
IS NULL condition
lit
The Oracle IS NULL condition is used to test for a NULL value. You can use the Oracle IS
NULL condition in either a SQL statement or in a block of PLSQL code.
e
expression IS NULL
Note:
ajp
LIKE condition
s:/
The Oracle LIKE condition allows wildcards to be used in the WHERE clause of a
SELECT, INSERT, UPDATE, or DELETE statement. This allows you to perform pattern
tp
matching.
The syntax for the LIKE condition
ht
m
Wildcard Explanation
% Allows you to match any string of any length (including zero length)
.co
_ Allows you to match on a single character
ss
examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the Oracle LIKE condition. You can
re
do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
dp
NOT condition
The Oracle NOT condition (also called the NOT Operator) is used to negate a condition in a
SELECT, INSERT, UPDATE, or DELETE statement. or
The syntax for the NOT condition
.w
NOT condition
lit
Note:
• The Oracle NOT condition requires that the opposite of the condition be must be met
for the record to be included in the result set.
e
at
m
Combine with BETWEEN conditions
The syntax for the NOT BETWEEN condition
.co
Expression NOT BETWEEN value1 AND value2;
ORDER BY Clause
ss
The Oracle ORDER BY clause is used to sort the records in your result set. The ORDER BY
clause can only be used in SELECT statements.
re
The syntax for the ORDER BY clause
SELECT expressions
dp
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
Note:
•
or
If the ASC or DESC modifier is not provided in the ORDER BY clause, the results will
be sorted by expression in ascending order (which is equivalent to ORDER BY
.w
expression ASC)
lit
SQL Queries
1. Describe Countries_____
e
at
2. Describe Regions_____
ajp
m
6. Retrieve data from Job_Grades_____ and assign title of the
.co
column “Grade Level”, “Minimum Salary” and “Maximum Salary”
Respectively.
ss
re
7. Retrieve the First Name, Last Name and Joining Date of the
dp
Employee, assign appropriate column name and arrange the data
as per the First Name.
or
.w
8. Display the names of employee who are Stock Clerk.
lit
11. Display all the Job id and title whose minimum salary is
greater than 5000 and maximum salary is less than 18000.
/
s:/
12. Display the entire employee name, whose hire date is between
tp
m
.co
ss
13. Display City and State whose Country ID is US
re
14. Retrieve the Employees names that are having salary greater
than 10000 in descending order.
dp
15. or
Find out the grade level for salary 23000
.w
16. Display Employee ID and Job ID for that employee who does
lit
18. Display the First and Last Name of Employees whose commission
/
percentage IS NULL.
s:/
tp
m
20. Display the First Name of Employees whose name contains ‘en’.
.co
21. Display all the record of employees whose Job ID start with
ST.
ss
re
22. Display all employees whose name start with ‘J’ and third
character is ‘n’.
dp
23. Display name, Email ID, Hire date of those employee whose
or
name is 5 character long and mobile no start with ‘59’
.w
24. Display the null value of employee and employee last name
lit
26. What will be output if you are giving LIKE predicate as ‘%\_%’
ESCAPE ‘\’ in JOBS table?
/
s:/
m
PRACTICAL 3
TO PERFORM VARIOUS AGGREGATE FUNCTIONS AND SORTING
CONCEPT ON ALL CREATED TABLES
.co
FUNCTIONS NAME
1. Group Function (Aggregate Functions)
ss
Functions that act on a set of values are called Group Functions. For ex SUM is a functions
which calculate the total set of numbers. A group functions returns a single result row for a
re
group of queried rows.
dp
Functions that act on only one value at a time are called scalar Functions. For ex LENGTH
is a function which calculates the length of one particular string value. A single row function
returns one result for every row of a queried table or view
AGGREGATE FUNCTIONS
or
•
.w
AVG
Syntax
AVG([<DISTINCT>|<ALL>]<n>)
e
• MIN
at
Syntax
ajp
MIN([<DISTINCT>|<ALL>]<expr>)
• COUNT
Syntax
COUNT([<DISTINCT>|<ALL>]<expr>)
OR
tp
COUNT(*)
ht
Returns the number of rows in the table including duplicates and with null.
m
• MAX
.co
Syntax
MAX([<DISTINCT>|<ALL>]<expr>)
ss
• SUM
re
Return Sum value of ‘n’
Syntax
dp
SUM([<DISTINCT>|<ALL>]<n>)
NUMERIC FUNCTIONS
• DUAL TABLE or
The DUAL table is a special one-row, one-column table present by default in Oracle and
.w
other database installations. In Oracle, the table has a single VARCHAR2(1) column called
DUMMY that has a value of 'X'. It is suitable for use in selecting a pseudo column such as
SYSDATE or USER
lit
• ABS
e
Syntax
ABS(n)
ajp
• POWER
Return m raised to the nth power n must be an integer, else an error is returned
/
Syntax
s:/
POWER(m,n)
Ex: Select POWER(3,2) from Dual
tp
• ROUND
Return n. rounded to m place to the right of a decimal point. If m is omitted, n is rounded
ht
to 0 places
m
Syntax
ROUND(n[,m])
.co
Ex: Select ROUND(15.19, 1) from Dual
• SQRT
ss
Syntax
re
SQRT(n)
Ex: Select SQRT(25) from Dual
dp
• EXP
Syntax or
EXP(n)
.w
Ex: Select EXP(5) from Dual
• GREATEST
lit
Syntax
e
• LEAST
ajp
Syntax
/
• MOD
tp
m
Syntax
MOD(m,n)
.co
Ex: Select MOD(15, 7) from Dual
• TRUNC
Return a number truncated to a certain number of decimal places. The decimal place
ss
value be an integer.
re
Syntax
TRUNC(number,[Decimal_place])
dp
Ex: Select TRUNC(125.815, 1), TRUNC(125.815, -2) from Dual
• FLOOR(n)
or
Return the largest integer value that is equal to or less than a number.
Syntax
.w
FLOOR(n)
Ex: Select FLOOR(24.8), FLOOR(13.15) from Dual
lit
• CEIL
Return the smallest int value that is greater than or equal to a number.
e
Syntax
at
CEIL(n)
Ex: Select CEIL(24.8), CEIL(13.15) from Dual
ajp
STRING FUNCTIONS
• LOWER
/
Syntax
LOWER(char)
tp
• INITCAP
Return a string with the first letter of each word in upper case and rest will be in lower
ht
m
Syntax
INITCAP(char)
.co
• UPPER
Syntax
ss
UPPER(char)
re
• SUBSTR
dp
omitted, the result returned is upto the last character in the string. The First position of
character is 1.
Syntax
SUBSTR(<string>,<start_position>,<length>)
or
•
.w
ANCII(<Single_character>)
Return the number code that represents the specified character. If more than one char is
lit
entered, the function will return the value for first char and ignore rest of all characters.
Syntax
e
ANSCII(<Single_Char>)
at
• INSTR
Syntax
INSTR(<string_1>,<string_2>,[<start_position>],[<nth_appeare
nce>])
/
• LENGTH
tp
Syntax
ht
LENGTH(word)
m
• LTRIM
Remove the char from the left of char with Initial char removed upto the first char not in
.co
a set.
Syntax
LTRIM(char[,set]>)
ss
Ex: Select LTRIM('AMIT','A') from Dual
• RTRIM
re
Remove the char from the final character removed after the last char not in a set.
dp
Syntax
RTRIM(char[,set]>)
Ex: Select RTRIM('AMIT','A') from Dual
• TRIM
or
.w
Remove all specifies characters either from the beginning or the ending of a string.
Syntax
lit
TRIM([Leading|Trailing|Both[<trim_char> from]]<string>)
Ex: Select TRIM(BOTH 'x' FROM 'xxAMITxx') from Dual
e
• LPAD
at
Returns char_1, left padded to length n with the sequences of character specifies in
char_2. If char2 is not specified, oracle uses blank by default.
ajp
Syntax
LPAD(char1,n[,char2])
Ex: Select LPAD('Page1',10,*) from Dual
/
•
s:/
RPAD
Returns char_1, right padded to length n with the sequences of character specifies in
char_2. If char2 is not specified, oracle uses blank by default.
tp
Syntax
RPAD(char1,n[,char2])
ht
m
CONVERSION FUNCTIONS
• TO_CHAR
.co
The TO_CHAR function converts a number or date to a string.
Syntax
TO_CHAR(n[,format])
ss
TO_CHAR(date[,format])
Ex:
re
Select TO_CHAR(1210.73, '9999.9') from Dual
Select TO_CHAR(1210.73, '$9,999.00') from Dual
dp
Select TO_CHAR(sysdate, 'yyyy/mm/dd') from Dual
Select TO_CHAR(sysdate, 'MON DDTH, YYYY') from Dual
Select TO_CHAR(sysdate, 'DDSP') from Dual
or
Select TO_CHAR(sysdate, 'MONTH DDSPTH') from Dual
.w
• TO_DATE
Syntax
TO_DATE(string[,format])
e
Ex:
at
• ADD_MONTHS
/
Syntax
ADD_MONTHS(d,n)
Where d stands for Date or date column & n stands for integer
tp
m
• LAST_DAY
Returns the last date of the Month specified with the functions
.co
Syntax
LAST_DAY(d)
Ex: Select LAST_DAY(sysdate) from Dual
ss
• MONTHS_BETWEEN
re
Returns no of months between d1 and d2
Syntax
dp
MONTHS_BETWEEN(d1,d2)
Ex: Select MONTHS_BETWEEN (TO_DATE ('2003/01/01',
'yyyy/mm/dd'), TO_DATE ('2003/03/14', 'yyyy/mm/dd')) from Dual
• NEXT_DAY
or
.w
Returns the date of the first weekday named by char that is after the date named by date.
Char must be a day of the week.
lit
Syntax
NEXT_DAY(date,char)
e
SQL Queries
ajp
m
4. Mention the minimum salary, employee name in dept. no 80
.co
5. Mention the maximum salary, Employee name whose manager ID is
149.
ss
6. Display First character capital and rest of them small in
re
Employee first and Last name, email ID must be in small character
& Job id must be in Capital Letters.
dp
or
7. Display the Job title and mention the length of Job titles.
.w
lit
m
PRACTICAL 4
TO STUDY SINGLE-ROW FUNCTIONS
.co
SQL Queries
1. Write a query to display the current date. Label the column Date
ss
2. For each employee, display the employee number, job, salary,
re
and salary increased by 15% and expressed as a whole number.
Label the column New Salary
dp
or
3. Modify your query no 4.(2) to add a column that subtracts the
old salary from the new salary. Label the column Increase
.w
lit
4. Write a query that displays the employee’s names with the first
e
length of the names, for all employees whose name starts with
J, E, or S. Give each column an appropriate label. Sort the
ajp
monthly.
ht
m
6. Display the name, hire date, number of months employed and day
.co
of the week on which the employee has started. Order the results
by the day of the week starting with Monday.
ss
re
7. Display the hire date of employees in a format that appears as
Seventh of June 1994 12:00:00 AM.
dp
or
8. Write a query to calculate the annual compensation of all
employees (sal+comm.) & round it to 0 places.
.w
lit
10. Identify which department does not have any employee without
using aggregate functions.
/
s:/
tp
ht
m
PRACTICAL 5
DISPLAYING DATA FROM MULTIPLE TABLES (JOINS)
.co
JOIN
• Sometime it is necessary to work with multiple tables as though they were a single
ss
entity.
• Then a single SQL Statement can manipulate data from all the tables.
• Tables are joined on columns that have a same datatype and data width
re
TYPES OF JOIN
dp
• INNER JOIN (or sometimes called simple join)
• LEFT OUTER JOIN (or sometimes called LEFT JOIN)
• RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
•
•
or
FULL OUTER JOIN (or sometimes called FULL JOIN)
CROSS JOIN
.w
SYNTAX:
ANSI Style
lit
ON <tablename_1>.<col_1> = <tablename_2>.<COL_2>
at
WHERE <condition>
ORDER BY <col_1>, <col_2>
ajp
THETA STYLE
<tablename_1>, <tablename_2>
s:/
m
INNER JOIN (simple join)
Chances are, you've already written a statement that uses an Oracle INNER JOIN. It is the
.co
most common type of join. Oracle INNER JOINS return all rows from multiple tables where
the join condition is met.
ss
re
dp
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
or
.w
The Oracle INNER JOIN would return the records where table1 and table2 intersect.
Another type of join is called an Oracle LEFT OUTER JOIN. This type of join returns all
rows from the Left-hand table specified in the ON condition and only those rows from the
e
other table where the joined fields are equal (join condition is met).
at
/ ajp
SELECT columns
s:/
FROM table1
LEFT JOIN table2
tp
ON table1.column = table2.column;
The Oracle LEFT OUTER JOIN would return the all records from table1 and only those
ht
m
RIGHT OUTER JOIN
Another type of join is called an Oracle RIGHT OUTER JOIN. This type of join returns all
.co
rows from the Right-hand table specified in the ON condition and only those rows from the
other table where the joined fields are equal (join condition is met).
ss
re
dp
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.column = table2.column;
or
.w
The Oracle RIGHT OUTER JOIN would return the all records from table2 and only those
records from table1 that intersect with table2.
lit
Another type of join is called an Oracle FULL OUTER JOIN. This type of join returns all
rows from the Left-hand table and Right-hand table with nulls in place where the join
at
SELECT columns
FROM table1
tp
The Oracle FULL OUTER JOIN would return the all records from both table1 and table2.
m
INTERSECT Operator
The Oracle INTERSECT operator is used to return the results of 2 or more SELECT
.co
statements. However, it only returns the rows selected by all queries or data sets. If a record
exists in one query and not in the other, it will be omitted from the INTERSECT results.
ss
re
dp
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
INTERSECT
or
SELECT expression1, expression2, ... expression_n
.w
FROM tables
[WHERE conditions];
lit
Note
• There must be same number of expressions in both SELECT statements and have
e
MINUS Operator
The Oracle MINUS operator is used to return all rows in the first SELECT statement that are
ajp
not returned by the second SELECT statement. Each SELECT statement will define a dataset.
The MINUS operator will retrieve all records from the first dataset and then remove from the
results all records from the second dataset.
/
s:/
tp
ht
m
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
.co
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables
ss
[WHERE conditions];
Note
re
• There must be same number of expressions in both SELECT statements and have
similar data types.
dp
UNION Operator
The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT
or
statements. It removes duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number of fields in
.w
the result sets with similar data types.
FROM tables
[WHERE conditions]
e
UNION
SELECT expression1, expression2, ... expression_n
at
FROM tables
[WHERE conditions];
ajp
Note
• There must be same number of expressions in both SELECT statements.
The Oracle UNION operator is used to combine the result sets of 2 or more Oracle SELECT
statements. It does not remove duplicate rows between the various SELECT statements.
Each SELECT statement within the UNION operator must have the same number of fields in
tp
m
SELECT expression1, expression2, ... expression_n
FROM tables
.co
[WHERE conditions]
UNION ALL
SELECT expression1, expression2, ... expression_n
ss
FROM tables
[WHERE conditions];
re
SQL Queries
dp
1. Give the name of employees and department name in which
particular employer is working with appropriate title.
or
.w
lit
3. Mention Employee name, salary and range of min salary and max
ajp
4. Mention Employee name, salary and Job grades for all employees.
tp
ht
m
5. List full address of all the managers with manager name.
.co
ss
6. Display first name, last name, department no for all Employees
who belongs to dept no 50 and 80.
re
dp
or
7. List the name of employees who are working in washington.
.w
8. Display all departments including those where does not have any
lit
employee.
e
at
ajp
m
10. Display those employees which contain a letter ‘e’ to their
first name and also display their last name, department, city,
.co
state and country.
ss
re
11. Display first and last name and salary for those employees
dp
who earns less than the employee earn whose no is 202.
or
.w
12. Display the first name of all employees including the first
lit
m
14. Display Job Title, full name of employees and difference
between maximum salary for the job and salary of the employee.
.co
ss
re
15. Display the name of the country, city and the department which
are running there.
dp
or
.w
16. Display the details of Job which was done by any of the
employees who is presently earning a salary on and above 10000.
e lit
at
18. Display Full Name, Job Title, starting and Ending date of
last jobs for those employees with worked without a commission
PCT.
ht
m
.co
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht
m
PRACTICAL 6
TO APPLY THE CONCEPT OF AGGREGATING DATA USING
FUNCTIONS.
.co
GROUP BY Clause
The Oracle GROUP BY clause is used in a SELECT statement to collect data across multiple
ss
records and group the results by one or more columns. The group by clauses create a data set,
containing several sets of records grouped together based on conditions.
re
SYNTAX
dp
aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;
or
HAVING Clause
.w
The Oracle HAVING clause is used in combination with the GROUP BY clause to restrict
the groups of returned rows to only those, whose the condition is TRUE. Having clause can
lit
Having imposes conditions on the group by clause, which further filters the group created by
e
SYNTAX
SELECT expression1, expression2, ... expression_n,
ajp
aggregate_function (aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING having condition;
/
s:/
statement.
m
SQL Queries
.co
ss
2. List total salary of employee whose manager is Steven.
re
dp
3. List employees who are working under each Manager.
or
4. List maximum salary of employee who is working in sales dept.
.w
lit
1999.
at
ajp
6. Find the avg salaries for each dept and mention its dept name.
/
s:/
7. Display the total salary being paid to each dept. Within each
dept.
tp
ht
m
8. Find the avg salary > 8000 for each dept displaying with dept
no.
.co
ss
9. List the Job id having avg salary more than 10000
re
10. List the department where at least two employees are working.
dp
11.
or
Display the Grade, Number of employees, and maximum salary
.w
of each grade.
e lit
13. List the no. of employees in each department where the no.
s:/
is less than 4.
tp
ht
m
PRACTICAL 7
TO SOLVE QUERIES USING THE CONCEPT OF SUB QUERY.
.co
• A sub query is a form of an SQL statement that appears inside SQL statement.
• The statement containing a sub query is called a parent statement. The parent statements use
ss
the rows returned by the sub query.
• A sub query must be enclosed in parentheses.
• A sub query must be placed on the right side of the comparison operator.
re
• Use single-row operators with single-row sub queries.
dp
Type of Sub queries
or
• Multiple row sub query: Returns one or more rows.
• Correlated sub queries: Reference one or more columns in the outer SQL statement. The sub
.w
query is known as a correlated sub query because the sub query is related to the outer SQL
statement.
lit
• Nested sub queries: Sub queries are placed within another sub query.
e
• Sub queries cannot manipulate their results internally; therefore ORDER BY clause
cannot be added into a sub query. You can use an ORDER BY clause in the main
ajp
m
SQL Queries
.co
Department.
ss
re
2. List Country Name and ID who belongs to region Europe.
dp
or
3. Display Employee ID and Name whose Job Title is Sales
.w
Representative
e lit
at
m
6. Give the name of employees having same dept as Jonathan and
having salary amount greater than 10000.
.co
ss
re
7. Create a query to display the Employee ID and First Name of all
Employees who earn more than avg salary. Sort the result in
descending order of salary.
dp
or
.w
8. Give the Employee details of employee whose Job Title is Stock
Clerk and Dept. is shipping.
e lit
at
ajp
m
10. List the name of Department who is having highest salary
credit.
.co
ss
re
11. List all the employees except ‘PRESIDENT’ & ‘MGR’ in asc
order of Salaries.
dp
or
.w
12. Display all the details of the employee whose salary is more
than the Sal of any SA_REP.
e lit
at
13. Display the department ID, full name (first and last name),
ajp
m
14. Display the details of departments managed by Kevin.
.co
ss
re
15. Display all the information about those employees who earn
second lowest salary of all the employees
dp
or
.w
16. Display the details of the current job for those employees
lit
17. Display the full name (first and last name) of manager who
is supervising 4 or more employees.
/
s:/
tp
ht
m
18. Display the detail information of those departments which
starting salary is at least 8000.
.co
ss
re
19. Display the details of those departments which max salary
is 7000 or above for those employees who already done one or
more jobs.
dp
or
.w
lit
20. Display the city of the employee who’s ID 134 and works there.
e
at
ajp
21. Display the first and last name, salary, and department ID
for those employees who earn less than the minimum salary of
/
m
22. Display the first and last name, salary, and department ID
for those employees who earn more than the minimum salary of
.co
a department which ID is 40.
ss
re
dp
or
.w
e lit
at
/ ajp
s:/
tp
ht
m
PRACTICAL 8
DATA MANIPULATION COMMANDS
.co
Modifying the structure of Tables.
• The structure of table can be modifying by using the ALTER TABLE command.
• ALTER TABLE allows changing the structure of an existing table.
ss
• With alter table queries it is possible to add, delete columns, create or destroy
indexes, change the data type of the existing columns or rename columns or table
re
itself.
dp
SYNTAX
RENAMING TABLE
Oracle allows renaming of tables. The rename operations is done atomically, which means that
no other thread can access any of the tables while the rename process is running.
tp
SYNTAX
m
UPDATING TABLE DATA
The UPDATE command is used to change or modify data values in a table.
.co
Updating all rows
SYNTAX
UPDATE <table_name>
ss
SET <column_name1> = <expression>,
<column_name2> = <expression>
re
Above query will update all the rows from the table without any intimation.
Updating specific rows
SYNTAX
dp
UPDATE <table_name>
SET <column_name1> = <expression>,
<column_name2> = <expression>
WHERE <conditions>
or
.w
Above query will update selected rows from the table that satisfy the conditions without any
intimation.
lit
DELETE TABLE
The DELETE command deletes rows from the table that satisfies the condition provided by its
e
Above query will delete all the rows from the table without any intimation.
Note:
Be careful while using delete query. User may loss all the data from the table.
/
SYNTAX
DELETE FROM <table_name>
WHERE <conditions>
tp
Above query will delete selected rows from the table that satisfy the conditions without any
intimation.
ht
m
TRUNCATING TABLES
.co
• Truncating table empties a table completely. It is similar to the Delete but practically
different.
Truncate table differs from Delete in following ways.
ss
• Truncating table drop the table and recreate empties table, which is much faster than
deleting rows one by one.
re
• Truncate opts are not transaction-safe (an error will occur if an active transaction or an
active table lock exists)
dp
• The numbers of deleted rows are not returned.
SYNTAX
SQL Queries
ajp
m
3. Create table Job from table Jobs with no record
.co
4. Insert the data into Job from Jobs whose second character should
ss
be ‘a’ and the Job ID should be 6 characters long.
re
5. Delete all the rows from Depts.
dp
or
6. Delete the details of worker whose manager id is 149.
.w
7. Rename the table Job
e lit
9. Update the value dept id to 110 where manager id is 101 and dept
ajp
id is 10.
/
s:/
m
PRACTICAL 9
TO STUDY THE CONCEPT OF CURSOR AND STORE PROCEDURE
.co
CURSORS
Oracle creates a memory area, known as context area, for processing an SQL statement,
which contains all information needed for processing the statement, for example, number of
ss
rows processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
re
A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the
cursor holds is referred to as the active set.
dp
You can name a cursor so that it could be referred to in a program to fetch and process the
rows returned by the SQL statement, one at a time. There are two types of cursors:
• Implicit cursors
or
• Explicit cursors
.w
Implicit Cursors
lit
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
e
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor
is associated with this statement. For INSERT operations, the cursor holds the data that needs
ajp
to be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
/
has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The
s:/
m
S.No Attribute & Description
1 %FOUND
.co
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more
rows or a SELECT INTO statement returned one or more rows. Otherwise, it returns
FALSE.
2 %NOTFOUND
ss
The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned no rows.
re
Otherwise, it returns FALSE.
3 %ISOPEN
dp
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
4 %ROWCOUNT
or
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement,
or returned by a SELECT INTO statement.
.w
EXAMPLE
lit
Implicit Cursor
The following program would update the table and increase salary of each customer by 500
e
and use the SQL%ROWCOUNT attribute to determine the number of rows affected:
at
DECLARE
total_rows number(2);
ajp
BEGIN
UPDATE EMPLOYEESAJPATELIT
SET SALARY = SALARY + 500;
/
IF sql%notfound THEN
s:/
END;
m
OUTPUT
20 EMPLOYEES SELECTED
PL/SQL procedure successfully completed.
.co
Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context
ss
area. An explicit cursor should be defined in the declaration section of the PL/SQL Block. It
is created on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is :
re
CURSOR cursor_name IS select_statement;
dp
Working with an explicit cursor involves four steps:
• Declaring the cursor for initializing in the memory
• Opening the cursor for allocating memory
•
•
Fetching the cursor for retrieving data or
Closing the cursor to release allocated memory
.w
Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
lit
For example:
returned by the SQL statement into it. For example, we will open above-defined cursor as
follows:
OPEN E_EMPLOYEESAJPATELIT;
/
Fetching the cursor involves accessing one row at a time. For example we will fetch rows
from the above-opened cursor as follows:
tp
m
Closing the Cursor
Closing the cursor means releasing the allocated memory. For example, we will close
.co
above-opened cursor as follows:
CLOSE E_EMPLOYEESAJPATELIT;
EXAMPLE
ss
Explicit Cursor
re
DECLARE
E_ID EMPLOYEESAJPATELIT.EMPLOYEE_ID%type;
dp
E_FNAME EMPLOYEESAJPATELIT.FIRST_NAME%type;
E_LNAME EMPLOYEESAJPATELIT.LAST_NAME%type;
CURSOR E_EMPLOYEESAJPATELIT is
SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME FROM
EMPLOYEESAJPATELIT;
BEGIN
or
OPEN E_EMPLOYEESAJPATELIT;
.w
LOOP
FETCH E_EMPLOYEESAJPATELIT into E_ID, E_FNAME, E_LNAME;
EXIT WHEN E_EMPLOYEESAJPATELIT%notfound;
lit
CLOSE E_EMPLOYEESAJPATELIT;
END;
at
OUTPUT
ajp
m
176 Jonathon Taylor
178 Kimerely Grant
200 Jennifer Whalen
.co
201 Michael Hartstein
202 Pat Fay
205 Shelley Higgins
206 William Gietz
ss
STORE PROCEDURE
A Procedure or Function is a logically grouped set of SQL and PL/SQL statements that
re
perform a specific task.
dp
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of Subprograms:
• or
Functions: these subprograms return a single value, mainly used to compute and
return a value.
• Procedures: these subprograms do not return a value directly, mainly used to perform
.w
an action.
S.No Parts & Description
lit
1 Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start with
e
exceptions, and nested subprograms. These items are local to the subprogram and cease
to exist when the subprogram completes execution.
2 Executable Part
ajp
This is a mandatory part and contains statements that perform the designated action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
/
s:/
• Performance
tp
Stored procedures are compiled once and stored in executable form, so procedure calls are
quick and efficient. Executable code is automatically cached and shared among users. This
lowers memory requirements and invocation overhead.
ht
m
By grouping SQL statements, a stored procedure allows them to be executed with a single
call. This minimizes the use of slow networks, reduces network traffic, and improves
.co
round-trip response time. OLTP applications, in particular, benefit because result set
processing eliminates network bottlenecks.
Additionally, stored procedures enable you to take advantage of the computing resources of
ss
the server. For example, you can move computation-bound procedures from client to server,
where they will execute faster. Likewise, stored functions called from SQL statements
re
enhance performance by executing application logic within the server.
dp
By designing applications around a common set of stored procedures, you can avoid
redundant coding and increase your productivity. Moreover, stored procedures let you extend
the functionality of the RDBMS. For example, stored functions called from SQL statements
enhance the power of SQL.
or
.w
• Scalability
Stored procedures increase scalability by isolating application processing on the server. In
lit
addition, automatic dependency tracking for stored procedures aids the development of
scalable applications.
e
The shared memory facilities of the Multi-Threaded Server (MTS) enable Oracle to support
at
more than 10,000 concurrent users on a single node. For more scalability, you can use the
Net8 Connection Manager to multiplex Net8 connections.
ajp
• Maintainability
Once it is validated, a stored procedure can be used with confidence in any number of
applications. If its definition changes, only the procedure is affected, not the applications that
/
calls it. This simplifies maintenance and enhancement. Also, maintaining a procedure on the
s:/
• Security
tp
You can restrict access to Oracle data by allowing users to manipulate the data only through
stored procedures that execute with their definer's privileges. For example, you can allow
access to a procedure that updates a database table, but deny access to the table itself.
ht
m
• Replication
With Oracle Advanced Replication, stored procedures can be replicated (copied) from one
.co
Oracle database to another. This feature makes them ideal for implementing a central set of
business rules. Once written, the stored procedures are replicated and distributed to work
groups and branch offices throughout the company. In this way, policies can be revised on a
central server rather than on individual servers.
ss
CREATING A PROCEDURE
re
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as follows:
dp
SYNTAX
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
or
BEGIN
.w
< procedure_body >
END procedure_name;
Where,
lit
• The optional parameter list contains name, mode and types of the parameters. IN
at
represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
ajp
EXAMPLE
s:/
dbms_output.put_line('Hello World!');
END;
/
ht
m
RUN
BEGIN
greetings;
.co
END;
DELETING A PROCEDURE
A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for
ss
deleting a procedure is:
re
SYNTAX
DROP PROCEDURE procedure-name;
dp
EXAMPLE
DROP PROCEDURE greetings;
omitted from the subprogram call. It is the default mode of parameter passing.
at
An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by value.
3 IN OUT
/
value to the caller. It can be assigned a value and the value can be read.
m
EXAMPLE-1
DECLARE
.co
a number;
b number;
c number;
ss
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
re
z:= x;
ELSE
z:= y;
dp
END IF;
END;
BEGIN
a:= 23;
b:= 45;
or
findMin(a, b, c);
.w
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
lit
OUTPUT
Minimum of (23, 45) : 23
e
EXAMPLE-2
at
DECLARE
a number;
ajp
BEGIN
a:= 23;
squareNum(a);
tp
OUTPUT
ht
m
PRACTICAL 10
TO STUDY TRANSACTION CONTROL COMMANDS
.co
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.
ss
COMMIT COMMAND
COMMIT command is used to permanently save any transaction into the database.
re
When we use any DML command like INSERT, UPDATE or DELETE, the changes made by
dp
these commands are not permanent, until the current session is closed, the changes made by
these commands can be rolled back.
or
To avoid that, we use the COMMIT command to mark the changes as permanent.
ROLLBACK COMMAND
This command restores the database to last committed state. It is also used with SAVEPOINT
e
If we have used the UPDATE command to make some changes into the database, and realize
that those changes were not required, then we can use the ROLLBACK command to rollback
ajp
those changes, if they were not committed using the COMMIT command.
ROLLBACK TO savepoint_name;
s:/
SAVEPOINT COMMAND
SAVEPOINT command is used to temporarily save a transaction so that you can roll back to
tp
m
Following is save point command's syntax,
SAVEPOINT savepoint_name;
.co
In short, using this command we can name the different states of our data in any table and
then roll back to that state using the ROLLBACK command whenever required.
Using Save point and Rollback
ss
Following is the table class,
re
ID NAME
1 Abhi
2 Adam
dp
4 Alex
Let’s use some SQL queries on the above table and see the results.
SAVEPOINT A;
SAVEPOINT B;
at
SAVEPOINT C;
ajp
ID NAME
s:/
1 Abhi
2 Adam
4 Alex
tp
5 Abhijit
6 Chris
ht
7 Bravo
m
Now let's use the ROLLBACK command to roll back the state of data to the save point B.
ROLLBACK TO B;
.co
SELECT * FROM class;
ss
ID NAME
1 Abhi
re
2 Adam
4 Alex
dp
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to the save point A
ROLLBACK TO A;
or
.w
SELECT * FROM class;
ID NAME
1 Abhi
e
2 Adam
at
4 Alex
5 Abhijit
ajp
AUTOCOMMIT
AUTOCOMMIT command automatically commits each transaction after its execution. If this
command is set, then no need to explicitly issue commit. We cannot rollback our transactions,
if AUTOCOMMIT is on. This needs to be set /unset before we begin any transactions.
/
s:/