0% found this document useful (0 votes)
4 views17 pages

CH-3 Interactive SQL and Advanced SQL - SQL Performance Tuning

Chapter 3 covers Interactive SQL and Advanced SQL with a focus on SQL performance tuning. It discusses various SQL functions, including string and arithmetic functions, date and time functions, and aggregate functions, along with their syntax and examples. The chapter also explains the use of GROUP BY, HAVING, and ORDER BY clauses, as well as INNER and OUTER JOINs in SQL queries.

Uploaded by

sanketr.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

CH-3 Interactive SQL and Advanced SQL - SQL Performance Tuning

Chapter 3 covers Interactive SQL and Advanced SQL with a focus on SQL performance tuning. It discusses various SQL functions, including string and arithmetic functions, date and time functions, and aggregate functions, along with their syntax and examples. The chapter also explains the use of GROUP BY, HAVING, and ORDER BY clauses, as well as INNER and OUTER JOINs in SQL queries.

Uploaded by

sanketr.co
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

CHAPTER 3

Interactive SQL and Advance SQL: SQL Performance Tuning


(14 Marks)

3.1 Inbuilt Function:String,Arithmatic


3.2 Date and Time, Aggregate Function
3.3 Queries using Group by, Having, and Order by clause, joins-Inner and outer join ,sub Queries
3.4 Views
3.5 Sequences
3.6 Indexes
3.7 Composite Index
3.8 Synonyms

3.1 SQL FUNCTIONS


Q. Explain any four string functions with example. (4M)
Two Types of SQL Functions
1. Single-row functions
 Manipulate data items
 Accept arguments and return one value
 Act on each row returned
 Return one result per row
 May modify the data type
 Can be nested
Syntax: - function_name (column| expression, [arg1, arg2...])

2. Multiple-row or Group functions


Single-row functions :- There are four types of single row functions are:
1. String Functions
FUNCTION USE/DEFINITION

INITCAP Capitalizes the first letter of a string of characters

INSTR Searches a character string for a character string subset and returns the start
position and/or occurrence of the substring

LOWER Returns a character value that is all lower case

UPPER Returns a character value that is all upper case

LTRIM Trims specified characters from the left end of a string

RTRIM Trims specified characters from the right end of a string

LPAD It is used for formatting from left side by using any character.

RPAD It is used for formatting from right side by using any character.

LENGTH Returns a numeric value equivalent to the number of characters in a string of


characters

SUBSTR Returns a string of specified length from a larger character string beginning at
a specified character position
Consider following “Person” table

LastName FirstName Address City

Sharma Rajesh GM Road Pune

Keri John CAMP Pune

Kari Johnson RTO Road Banglore

1. INITCAP: - It display the initial letter as capital.


Syntax: - INITCAP (‘String')
Example:- SQL> Select Initcap(city) from Person;

Result Table:-
City

Pune

Pune

Banglore

2. LOWER & UPPER:- Returns a character value that is all lower/ Upper case
Syntax: - Lower (‘String')
Upper (‘String’)
Example:- SQL> Select lower(city) from Person;
SQL> Select upper (city) from Person;
Result Table:-
City City
pune PUNE
pune PUNE
banglore BANGLORE

3. Ltrim & Rtrim: - It trims or cuts the character from left or right.
Syntax: - Ltrim(‘String‘,’trim text’)
Rtrim (‘String’, ‘trim text’)
Example:- SQL> Select Ltrim(‘Pune’, ‘P’) from Person;
SQL> Select Rtrim (‘Pune’, ‘e’) from Person;
Result Table:-
City City
une pun
une pun
banglore banglore
4. Translate: - It is used to translate the given character from input string.
Syntax: - Translate (‘main string’ , ‘string to replaced’, ‘ string to be replaced by’)
Example:- SQL> Select translate (‘Banglore’, ‘B’ , ‘ M’) from Person;
Result Table:-
City
pune
pune
Manglore

5. Substr: - It returns the substring from specified position.


Syntax: - Substr (‘main string’ , position, character to be replaced’)
Example:- SQL> Select Substr (city, 1, 3) from Person;

Result Table:-
City(Substr)
Pun
pun
Man

6. LPAD & RPAD: - It is used for formatting from left & right side by using any character.
Syntax: - Lpad (‘main string’ , length, character to be padded’)
Rpad (‘main string’, length, character to be padded’)
Example:- SQL> Select Lpad (city, 10, ‘ * ’) from Person;
SQL> Select Rpad (city, 10, ‘& ’) from Person;
Result table:-

City City
******Pune Pune &&&&&&
******Pune Pune &&&&&&
**Banglore Banglore &&

7. Concatenation: - It is used to concatenate combining two strings.


Syntax: - String || String
Example:- SQL> Select ( ‘the first name is’ || firstname || ‘ and city is ’ || city) from
Person;

Result Table:-
the first name is rajesh and city is pune

the first name is john and city is pune

the first name is johnson and city is banglore

8. Length: - It is used to calculate the length of given string.


Syntax: - length (‘string’)
Example:- SQL> Select length (city) from Person;
Result Table:-
City(Length)
4
4
8
2. Arithmetic/Numeric Function

Function Description Syntax Example Output

ABS It returns the absolute value of ‘n’. ABS(-15.36) SQL> Select ABS(- 15.36
(absolute) 15.36) from dual;
Power It returns m raised to the nth Power (m, n) SQL> select power (3,2) 6
power. Nth must be an integer ”raised” from dual;
else an error is returned.

Round Round the value of number x to y round(X, [Y]) SQL> select round 140.23
(X,Y) decimal places. (140.234, 2) from dual;
SQRT Returns square root of n. sqrt(n) select sqrt(25) from 5
dual;
GREATEST Returns a greatest value in a list of Greatest select greatest(4,5,17) 17
expressions. (expr1,expr2,e from dual;
xpr3…exprn)
LEAST Returns the least value in a list of least(expr1,ex select least(4,5,17) from 4
expressions. pr2,…..,exprn) dual;
;
MOD Returns the remainder of a first mod(m, n) select mod(15,7) from 1
number divided by second dual;
number passed a parameter.

3.2 Date and Time, Aggregate Function:

3.2.1 DATE & TIME FUNCTIONS


Q. Explain any four date functions with example.(4M)

• Oracle stores dates in an internal numeric format: century, year, month, day, hours, minutes,
seconds.
• The default date format is DD-MM-YY.
• SYSDATE is a function returning date and time.
• DUAL is a dummy table used to view SYSDATE.

Function Description Return Value


Used to find number of months between d1 and d2
months_between(d1,d2)
Example: Select months_between (‘05-Sep-1996‘, 3
Where, d1 and d2 are dates
‘05-Dec-1996‘) from dual;
Returns date after adding the number of months
add_months (d, n)
specified with the function.
Where, d is date, n no of 16-Dec-17
Example: Select add_months(‘16-Sep-17’,3) from
months to be added
dual;
Returns the date of the first weekday named char that
Next_day ( d, char)
is after the date named by date.
Where d is date, char- day of 06-Sep-17
Example: Select next_day (‘01-Sep-2017‘,
week
‘Wednesday‘) from dual;
Returns the last day of the month that contains date
Last_day (d)
d. 31-Aug-17
Where, d is date
Example: Select last_day (‘1-Aug-17’) from dual;
3.2.2 GROUP FUNCTION/AGGREGATE FUNCTIONS
Q. What is an aggregate function?
Q. Explain any four aggregate functions with example.(4M)
• An aggregate function perform a calculation on set of values and return a single value.
Usually these functions ignore NULL values(except for COUNT).
• The general syntax for most of the aggregate functions is as follows:
• Syntax:- Aggregate_function ([DISTINCT|ALL] expression)
• Some of the commonly used aggregate functions are :
i. SUM
Sno Fname Salary Position
ii. COUNT
iii. AVG SL100 John 30000.00 Manager
iv. MIN SL101 Susan 24000.00 Manager
v. MAX SL102 David 12000.00 Project Manager
• Consider following table:- SL103 Ann 12000.00 Project Manager
SL104 Mary 9000.00 Project Manager

Function Description Output

Avg(column) Returns: The average of the values in a specified column.


Syntax:- SELECT AVG(column_name) FROM table_name
WHERE condition;
Example:-
SQL>Select avg (salary) from staff;
17400
SQL> Select Avg(salary) from staff where position= ‘manager’; 27000
SUM(column) Returns: The sum of the values in a specified column.
Syntax:- SELECT SUM(column_name) FROM table_name
WHERE condition;
Example:-
SQL>Select sum (salary) from staff;
87000
SQL> Select sum(salary) from staff where position= ‘manager’; 54000
MAX(column) Returns: MAX () returns the largest value of a column.
Syntax:- SELECT max(column_name) FROM table_name;
Example:-
SQL>Select max (salary) from staff; 30000

MIN(column) Returns: MIN () returns the smallest value of a column.


Syntax:- SELECT min(column_name) FROM table_name;
Example:-
SQL>Select min (salary) from staff; 9000

Count(column) Returns: The number of values in the specified column.


Syntax:- SELECT COUNT(column_name) FROM table_name
WHERE condition;
Example:- SQL>Select count (Sno ) from staff; 5
SQL>SELECT COUNT(Sno) FROM Staff WHERE position = 2
‘Manager’;
3.3 Queries using Group by, Having, and Order by clause , joins-Inner and outer join ,sub Queries

3.3.1 USE OF GROUP BY CLAUSE


Q. Explain group by clause.(2M)
Q. Define group by clause.(2M)
Q. Explain group by clause with suitable example.(4M)

• 1. GROUP BY: It helps to arrange similar data into groups. It is also used with SQL functions to
group the result from one or more tables.
• Syntax:- SELECT column_name, sum(column_name) FROM table GROUP BY column_name;

• Consider following Table:-


C_Code Company Turnover(Cr)
B1 Atlas 9500

B2 Infosys 4500
“Sales” Table
B3 Wipro 7100
B1 Atlas 2500
B2 Infosys 3500
• Example:- SELECT c_code, company, sum(turnover) FROM sales GROUP BY company;

Turnover(C
C_Code Company r)

B1 Atlas 12000

Resultant Table
B2 Infosys 8000
B3 Wipro 7100

3.3.2 HAVING CLAUSE


Q. Explain having clause with example.(4M)
• The HAVING clause is used in SQL because the WHERE keyword could not be used with
aggregate functions. The HAYING clause is used with GROUP BY clause .We often use
aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.
• Syntax:-
SELECT column, sum (column) FROM table GROUP BY column HAVING sum (column)
condition value;
• Example:-
SELECT c_code, company, sum (turnover)
FROM sales GROUP BY company
HAVING sum (amount)>10000;
Resultant Table

C_Code Company Turnover(Cr)

B1 Atlas 12000
3.3.3 ORDER BY CLAUSE
Q. Explain order by clause with suitable example.(4M)
• ORDER BY clause is used to display a selected set of fields from a relation in an ordered
approach (desc/asc) base on some field.
• Oracle sorts query results in ascending order by default.
• Syntax:-
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2... column] [DESC/ASC]];
• For Example: If you want to sort the staff table by salary of the staff.
• SQL> SELECT name, salary FROM staff ORDER BY salary;

Fname Salary

Mary 9000.00

David 12000.00
Resultant Table

Ann 12000.00

Susan 24000.00

John 30000.00

Fname Salary

• SQL> SELECT name, salary John 30000.00

FROM Staff Susan 24000.00

ORDER BY name, salary DESC; David 12000.00

Ann 12000.00

Resultant Table Mary 9000.00

3.3.4 JOIN - INNER JOIN AND OUTER JOIN


Q. Explain Inner join and Outer join with example.(4M)
Q. Explain various types of joins with example.(4M)

emp dept
Eno Ename Salary Deptno Deptno Deptname Location
1 Ajay 7000 10 10 100 Pune
2 Amar 8000 10 20 102 Mumbai
3 Neeta 5000 20 30 103 Nagpur
4 Karan 6000 40
INNER JOIN:
INNER JOIN is also referred to as an EQUIJOIN. The INNER JOIN displays records that
have similar values in both tables.
This is a simple JOIN in which the result is based on matched data as per the condition
specified in the query.

Inner Join Syntax :


SELECT column_name_list FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name = table_name2.column_name;
Inner Join Example :
SELECT * FROM emp INNER JOIN dept ON emp.Empid = dept.Empid;

ENO ENAME SALARY DEPTNO DEPTNO DEPTNAME LOCATION


1 Ajay 7000 10 10 IT Pune
2 Amar 8000 10 10 IT Pune
3 Neeta 5000 20 20 HR Mumbai

OUTER JOIN:
Outer Join is based on both matched and unmatched data. Outer Joins subdivide
further into,
• Left Outer Join
• Right Outer Join
• Full Outer Join
1. Left Outer Join
• The LEFT JOIN keyword returns all records from the left table (table-I), and the matched records
from the right table (table-2). The result is NULL from the right side, if there is no match.

o Left Outer Join syntax :


SELECT column-name-list FROM table-name1
LEFT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
o Left Outer Join Example:
SELECT * FROM emp LEFT OUTER JOIN dept ON emp.Deptno = dept.Deptno;

ENO ENAME SALARY DEPTNO DEPTNO DEPTNAME LOCATION


2 Amar 8000 10 10 IT Pune
1 Ajay 7000 10 10 IT Pune
3 Neeta 5000 20 20 HR Mumbai
4 Karan 6000 40 - - -
2. Right Outer Join
• The RIGHT JOIN keyword returns all records from the right table (table-2), and the matched
records from the left table (table-I). The result is NULL from the left side, when there is no match.

o Right Outer Join Syntax:


SELECT column-name-list FROM table-name1 RIGHT OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
o Right Outer Join Example:
SELECT * FROM emp RIGHT OUTER JOIN dept ON emp.Deptno = dept.Deptno;

ENO ENAME SALARY DEPTNO DEPTNO DEPTNAME LOCATION


1 Ajay 7000 10 10 IT Pune
2 Amar 8000 10 10 IT Pune
3 Neeta 5000 20 20 HR Mumbai
- - - - 30 Sales Nagpur

3. Full Outer Join


• The FULL OUTER JOIN keyword return all records when there is a match in either left (table-I)
or right (table-2) table records. FULL OUTER JOIN can potentially return very large result-sets.

o Full Outer Join Syntax :


SELECT column-name-list FROM table-name1 FULL OUTER JOIN table-name2
ON table-name1.column-name = table-name2.column-name;
o Full Outer Join Example:
SELECT * FROM emp FULL OUTER JOIN dept ON emp.Deptno = dept.Deptno ;

ENO ENAME SALARY DEPTNO DEPTNO DEPTNAME LOCATION


2 Amar 8000 10 10 IT Pune
1 Ajay 7000 10 10 IT Pune
3 Neeta 5000 20 20 HR Mumbai
4 Karan 6000 40 - - -
- - - - 30 Sales Nagpur
4. CROSS JOIN

In SQL, the CROSS JOIN is used to combine each row of the first table with each row of the second table. It
is also known as the Cartesian join since it returns the Cartesian product of the sets of rows from the joined
tables.

Syntax:
SELECT [column names] FROM [Table1] CROSS JOIN [Table2]

Example:
SELECT * FROM emp1 CROSS JOIN dept1;

ENO ENAME SALARY DEPTNO DEPTNO DEPTNAME LOCATION


1 Ajay 7000 10 10 IT Pune
2 Amar 8000 10 10 IT Pune
3 Neeta 5000 20 10 IT Pune
4 Karan 6000 40 10 IT Pune
1 Ajay 7000 10 20 HR Mumbai
2 Amar 8000 10 20 HR Mumbai
3 Neeta 5000 20 20 HR Mumbai
4 Karan 6000 40 20 HR Mumbai
1 Ajay 7000 10 30 Sales Nagpur
2 Amar 8000 10 30 Sales Nagpur

5. Self-join
•A self join is a join in which a table is joined with itself.
•The self join can be viewed as a join of two copies of the same table.
•The syntax of the command for joining a table to itself is almost same as that for joining two different
tables.
•To distinguish the column names from one another, aliases for the actual the table name are used, since both
the tables have the same name.
•Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed= b.common_field;

Example:
SELECT E.Name as Employee, M.Name as Manager FROM Employee E LEFT JOIN Employee M ON
E.ManagerId = M.EmployeeId
OUTPUT-

SUB QUERIES
Q. Explain Sub-query concept with example.(4M)
• A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
• Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with
the operators like =, <, >, >=, <=, IN, BETWEEN etc.
• There are a few rules that subqueries must follow:
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause, unless multiple columns are in the
main query for the subquery to compare its selected columns.
• An ORDER BY cannot be used in a subquery, although the main query can use an ORDER BY.
• The GROUP BY can be used to perform the same function as the ORDER BY in a subquery.
• Example:
• Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy
complete CUSTOMERS table into CUSTOMERS_BKP, following is the
• Syntax:
SQL> INSERT INTO CUSTOMERS_BKP
SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS) ;

3.4 VIEW
Q. What are views? Give its syntax and explain its advantages. (Views - 2 marks; Syntax - 1 mark;
Advantages (Any two) - 1 mark)
Q. Explain views with example. (Explanation of view with syntax – 3 Marks, Example - 1 Mark)
 View can be a virtual table which derived its data from one or more than one table. View can be created
using tables of same database or different database.
 View is a logical copy of physical table.
 It is used for security purposes because they provide encapsulation of the name of the table. Data is in the
virtual table, not stored permanently. It displays only selected data. A view provides several benefits.
o Views can hide complexity.
o Views can be used as a security mechanism.
o Views can simplify supporting legacy code.
o Define view with its features.
o Differentiate between table & view.
3.4.1 SQL CREATE VIEW
Syntax
CREATE VIEW view_name
AS SELECT column_name(s)
FROM table_name
WHERE condition;
Where,
view_name – is the name of view.
SELECT statement- is used to define the columns & rows that you want to display in the view.

Example: Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example to create a view from the CUSTOMERS table. This view would be used to have
customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW1 AS SELECT * FROM CUSTOMERS;
SQL > SELECT * FROM CUSTOMERS_VIEW1;
This would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SQL > CREATE VIEW CUSTOMERS_VIEW2 AS SELECT name, age FROM CUSTOMERS;
SQL > SELECT * FROM CUSTOMERS_VIEW2;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+

SQL > CREATE VIEW CUSTOMERS_VIEW3 AS SELECT name, age FROM CUSTOMERS
WHERE age>25;
SQL > SELECT * FROM CUSTOMERS_VIEW3;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Hardik | 27 |
+----------+-----+
3.4.2 UPDATING A VIEWS
Syntax:
UPDATE view_name SET Col_name=New_value WHERE Condition;

Example:
SQL> UPDATE CUSTOMERS_VIEW SET Age=35 WHERE Name=‘ramesh’;

This would ultimately update the base table CUSTOMERS and the same would reflect in the view itself.
Now, try to query the base table and the SELECT statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
3.4.3 Inserting Rows into a View:
Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to
the INSERT command.

3.4.4 Deleting Rows into a View:


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands
apply to the DELETE command.
Following is an example to delete a record having AGE= 22.
SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22;
This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in the
view itself. Now, try to query the base table and the SELECT statement would produce the following result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

3.4.5 SQL Dropping a View

You can delete a view with the DROP VIEW command.


SQL DROP VIEW
Syntax SQL> DROP VIEW view_name;
Q. Consider following schema.
EMPLOYEE-DETAILS(empname,empid,DOB,salary,job)
Create a view on EMPLOYEE-DETAILS having attribute empname,empid,DOB,salary,job where salary is
greater than 20,000.
Ans:
Create view v1 as select empname,empid,DOB,salary,job from EMPLOYEE_DETAILS where
salary>20000;
Q. Consider following schema.
Depositor(Acc_no,Name,PAN,Balance)
Create a view on Depositor having attribute (Acc_no,PAN) where balance is greater than 100000.
Ans:
Create view v1 as select Acc_no,PAN from Depositor where balance>100000;

DATABASE OBJECT
Index, Sequence and Synonym are database object.

3.5 SEQUENCES
Q. What are sequence? Why it is used? Create sequence for STUDENT table. (Definition - 1 mark; Use
- 1 mark; creating valid sequence example/pattern - 2 marks)
Q. Explain sequences with example. (Definition of sequence - 1 Mark, syntax – 2 Marks, Example - 1
Mark)
 A sequence is a set of integers 1, 2, 3, 4 that are generated in order on demand.
 Sequences are commonly used in databases because many applications require each row
in a table to contain a unique value and sequences provide an easy way to generate them.
 Definition:- A sequence refers to a database object that is capable of generating unique
and sequential integer values.
 Syntax:
o CREATE SEQUENCE <seq_name> [Start with num]
[Increment by num]
[Maxvalue num]
[Minvalue num]
[Cycle/nocycle]
[Cache num/nocache];
Where,
o Increment by num: Used to specify the interval between sequence numbers.
o Start with num: States the first sequence numbers that needs to be generated.
o Minvalue num: This is used to state the minimum value of the sequence.
o Maxvalue num: It states the maximum value generated by sequence.
o Cycle: Cycle indicates that the sequence will be continued for generating the values from the starting
after reaching either its maximum value or minimum value.
o Cache: The cache option is used to pre-allocate a set of sequence numbers and keep these numbers
in the memory so that they can be accessed.
o No Cache: This states that there is no pre-allocation for the values of sequence.
Example 1:-
 SQL> CREATE SEQUENCE student_seq START with 1 INCREMENT by 1
MAXVALUE 60 nocycle;
 SQL> Sequence Created.
 On execution, oracle will create a sequence student_seq. its start with 1, incrementing the
sequence number by 1. Maximum value that it can generate is 60.
 Referencing a sequence: it is referenced in SQL statement with the NEXTVAL & CURRVAL;
 Ex.2:- CREATE Sequence seq_1 START with 1 INCREMENT by 1 MAXVALUE 999 Cycle;
 Suppose consider “info” table
“Info” Table
ID Name
1 John
2 Smith
3 Hari
 The SQL query will be,
 SQL> INSERT into info values(seq_1.nextval, ‘Anu');
 Result table will look like,
“Info” Table
ID Name
1 John
2 Smith
3 Hari
1 Anu
 Once you use nextval the sequence will increment even if you don't insert any record into the table.
 SQL> Select seq_1.currval from info;

3.5.1 Altering Sequences


 Use the ALTER SEQUENCE statement to change the increment, minimum and maximum
values, cached numbers, and behavior of an existing sequence.
 This statement affects only future sequence numbers.
 Alter sequence <seq_name>
 [Start with num]
 [Increment by num]
 [Maxvalue num] [Minvalue num]
 [Cycle/nocycle]
 [Cache num/no-cache];
 Ex.:-SQL> Alter sequence seq_1 maxvalue 1500;
 SQL> Alter sequence seq_1 cycle cache 10; (This statement turns on cycle & cache for the
seq_1 sequence.)

3.5.2 Dropping Sequences


 Use the DROP SEQUENCE statement to remove a sequence from the database.
 The sequence must be in your own schema or you must have the DROP ANY SEQUENCE
system privilege.
 Syntax:
 SQL> Drop sequence sequence_name;
 Ex.:- SQL> Drop sequence Info;
3.6 INDEXES
Q What is index? Explain types of index. (Index Definition - 2 marks; Any Two Types - 1 mark each)
Q Explain the concept of indexing with neat diagram. (Explanation - 3 Marks, Any relevant Diagram - 1
Mark)
 An index can be created in a table to find data more quickly and efficiently.
 Index provides a fast access path to column that is indexed. Indexes are stored independently from actual
data. It is mostly useful on large tables and on column that are frequently appear in WHERE clause. When
table dropped, index will also drop. More than one indexes are allow in one table.
 Type of index:
i. Simple index
ii. Unique indexes
iii. Composite index

3.6.1 CREATE INDEX


Syntax:
CREATE INDEX index_name ON table_name;
Simple index (Single column): An index created on single column of a table is called a Simple
Index.
Syntax: - CREATE INDEX index_name ON table_name (column_name);
Ex. SQL> CREATE INDEX emp_ind ON EMP (empid);

Unique indexes are used not only for performance, but also for data integrity. A unique index
does not allow any duplicate values to be inserted into the table.
Syntax: - CREATE UNIQUE INDEX index_name ON table_name (column_name);

Ex: - CREATE UNIQUE INDEX emp_ind ON EMP (empid);


Composite (concatenated): Indexes that contain two or more columns from the same table which
are useful for enforcing uniqueness in a table column where there’s no single column that can
uniquely identify a row.
Syntax;- CREATE INDEX index_name ON table_name (column1, column2);
Ex.:- CREATE INDEX emp_ind ON EMP (empid, Dept_name);

3.6.2 DROP INDEX


 An index can be dropped using SQL DROP command.
 Syntax:- DROP INDEX index_name;
 Ex.:- DROP INDEX emp_ind;

3.7 SYNONYMS
Q. What are Synonyms? Write a syntax for creating a synonym.(4M)
Q. What are Synonyms? How to create and drop synonym?(4M)
 A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and
other database objects. DML operation performed on synonym will affect the table. The main functionality
of synonym is to access the database objects between different schemas without using the schema names.
 It can provide a level of security by masking the name & owner of an object & by providing location
transparency for remote objects of a distributed database.
 You can create both public & private synonyms.
 A public synonym is owned by special user group named PUBLIC & is accessible to every user in a
database.
 A Private synonym is contained of specific user only.
3.8.1 Creating Synonyms:-
Syntax:-
CREATE SYNONYM Synonym_Name FOR table_name;
Example:-
SQL> CREATE SYNONYM Emp FOR Employee;
SQL> Synonym created.
SQL> SELECT * FROM Emp;

3.8.2 Dropping Synonyms :-


 If a synonym is no longer required, you can drop the sequence using the DROP SYNONYM
statement.
 Syntax:-
o DROP SYNONYM Synonym_Name;
o Example:-
SQL> CREATE SYNONYM Emp;
SQL> SYNONYM created.

You might also like