Unit 3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 27

Unit -3 Interactive SQL and Performance Tunning

Introduction to SQL
Every data table that we have created so far has stored data for us. All this data would server
very little purpose if it could not be retrieved. In order to retrieve this data one needs to be
able to talks to the tables. The SQL allow user of the database to communicate with the
database.

Advantages of SQL:
1. Database management (using queries, tables).
2. Window based.
3. Can hold millions of data.
4. easy to access.
5. Extremely powerful and flexible.
6. Compatible with every major database engine.

Types of SQL:
1. Interactive SQL:
It is used for interactive directly with the database where the output of
operation is used for human consumption. Once a command is specified it is executed
and the output can be immediately viewed by the user.
2. Embedded SQL:
In this commands are SQL commands that are written in some other
languages such as COBOL, C, visual basic, java etc.

SQL Server Data Types

Oracle String data types

CHAR(size) It is used to store character data within the predefined length. It


can be stored up to 2000 bytes.

NCHAR(size) It is used to store national character data within the predefined


length. It can be stored up to 2000 bytes.

VARCHAR2(size) It is used to store variable string data within the predefined


length. It can be stored up to 4000 byte.

VARCHAR(SIZE) It is the same as VARCHAR2(size). You can also use


VARCHAR(size), but it is suggested to use VARCHAR2(size)

NVARCHAR2(size It is used to store Unicode string data within the predefined


) length. We have to must specify the size of NVARCHAR2 data
type. It can be stored up to 4000 bytes.

Oracle Numeric Data Types


NUMBER(p, s) It contains precision p and scale s. The precision p can range
from 1 to 38, and the scale s can range from -84 to 127.

FLOAT(p) It is a subtype of the NUMBER data type. The precision p can


range from 1 to 126.

BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes,


including length byte.

BINARY_DOUBLE It is used for double binary precision (64-bit). It requires 9


bytes, including length byte.

Oracle Date and Time Data Types

DATE It is used to store a valid date-time format with a fixed length. Its
range varies from January 1, 4712 BC to December 31, 9999 AD.

TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time


hh:mm:ss format.

Components of SQL
 DDL Commands
 DML Commands:
 DCL Commands:
 DQL Commands:

DDL Commands:
The DDL commands are as follows

1. CREATE TABLE
The CREATE TABLE statement is used to create a new table in a database.
Tables are organized into rows and columns; and each table must have a name.
Syntax:
CREATE TABLE <table_name >
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
Example
CREATE TABLE Persons
( PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Optput: Persons

PersonID LastName FirstName Address City

2. The ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an
existing table. Tables can be modified in two ways.
1. New column can be added.
2. The datatype of existing columns can be modified.

Syntax
1. ALTER TABLE table_name ADD column_name datatype

2. ALTER TABLE table_name MODIFY column_name datatype

3. ALETR TABLE table_name DROP column Column_Name


Examples:
Alter table persons Add DateofBirth date;
Alter table persons modify address varchar2 (20)
Alter table persons drop column city;

3. RENAME TABLE Statement


It is used to rename the name of existing table.
Syntax:

Rename <table name > to<new table name>

Example

Rename persons to book

4. DROP TABLE Statement

The DROP TABLE statement is used to delete a table definition from the database.
Once the command executed the table definition uis removed from the system and your table
does not exist any more

Syntax:
DROP TABLE table_name

Example
Drop table book
5. TRUNCATE TABLE Statement
To delete all the rows from the table i.e. making table empty is done by using
truncate table command.

Syntax:
TRUNCATE TABLE table_name

Example:
Truncate table book
6 .Desc Commands
The table structure can be seen with the help of describe command.
Syntax:
Desc <table name>
Example
Desc emp

DML Commands:
The DML commands are as follows

1. INSERT COMMAND
It is used to add new rows to your table.
Syntax:
Insert into <table name> (columan_name1, column_name2…..column_nameN)
Values (value1, value2, …...valueN)
Example
Insert into Emp (Emp_id,Emp_name,Salary,Deptno) values(1,’xyz’,10000,10)

2. UPDATE COMMAND
It is used to change or modify the data values in the table.
Syntax:
Update <table name> set <column-name=value1> where <condition>
Example
Update Emp set Emp_name=’ABC’ where emp_id=1

3. DELETE COMMAND
It is used to delete rows permanently that satisfy yiur where condition.It does not
remove your table definition
Syntax:

Delete from <table name> where <condition>


Example
Delete from emp where Emp_id=2

DCL Command
Data Control Language (DCL) is used to control privilege in Database. To
perform any operation in the database, such as for creating tables, sequences or views we
need privileges. Privileges are of two types,
 System: creating session, table etc are all types of system privilege.
 Object: any command or query to work on tables comes under object privilege.

DCL defines two commands,
1. Grant:
This command is used to give permission to user to do operations on the other
user‘s object.

Syntax: Grant<object privileges>on<object name>to<username>[with grant option] ;

Example: Grant select, update on emp to user1;

2. Revoke:
This command is used to withdraw the privileges that have been granted to a user.
Syntax: Revoke <object privileges>on<object name>from <username> ;

Example:Revoke select, update on emp from user1;

TCL command
Transaction Control Language (TCL) commands are used to manage transactions
in database. These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.

Commit command
Commit command is used to permanently save any transaction into database.
Following is Commit command's syntax,
commit;

Rollback command
This command restores the database to last committed state. It is also use with
savepoint command to jump to a savepoint in a transaction.
Following is Rollback command's syntax,
rollback to savepoint-name;

Savepoint command
savepoint command is used to temporarily save a transaction so that you can
rollback to that point whenever necessary.
Following is savepoint command's syntax,
savepointsavepoint-name;

Example of Savepoint and Rollback


Following is the class table,
ID NAME

1 Abhi

2 Adam

4 Alex
Lets use some SQL queries on the above table and see the results.
INSERT into class values(5,'Rahul');
commit;
UPDATE class set name='abhijit' where id='5';
savepointA;
INSERT into class values(6,'Chris');
savepointB;
INSERT into class values(7,'Bravo');
savepointC;
SELECT * from class;
The resultant table will look like,
ID NAME

1 Abhi

2 Adam

4 Alex

5 Abhijit

6 Chris

7 Bravo

Now rollback to savepoint B


rollback to B;
SELECT * from class;
The resultant table will look like
ID NAME

1 Abhi

2 Adam

4 Alex

5 Abhijit

6 Chris
Now rollback to savepoint A
rollback to A;
SELECT * from class;

The result table will look like

ID NAME
1 Abhi

2 Adam

4 Alex

5 Abhijit

DQL Command:

SELECT COMMAND
It is used to display all/particular records from the table. The basic structure of
an SQL expression consist of three clauses; SELECT, FROM, WHERE.
 SELECT => It corresponds to the projection operation of the relational algebra. It is
used
to list the attributes desired in the result of query.
 FROM => It corresponds to Cartesian product operation of relational algebra. It
lists
the relation to be scanned in the elevation of experiments.
 WHERE => It corresponds to selection predicate of relational algebra. It consist of
predicate involving attributes at the relation that appear in the from
clause.
Synatax:
Select * from <table name>;
Select < column_name1,……column_nameN) from <table name>
Select < column_name1,……column_nameN) from <table name> where <condition>

Example
Select * from Emp;
Select Emp_id,Salary from Emp;
Select Emp_id,salary from Emp where salary >10000

SQL Operators:
1. Arithmetic operation
Arithmetic operators are used to perform mathematical functions in
SQL.

Operator Definition
+ Addition
- Subtraction
* Multiplication
/ Division

Example
Select Emp_id , salary+500. From Emp
Select Emp_id , salary-bonus from Emp
Select Emp_id , salary*5 from Emp
Select Emp_id , salary/10 from Emp

2. Logical Operator
These operators compare two conditions at a time to determine whether a row can
be selected for output when retrieving data.

Logical operator Description


OR For the row to be selected at least one condition must be true
AND For the row to be selected all the condition must be true
NOT For the row to be selected the specified condition must be
false

Example
Select * from Emp where salary>=5000 AND salary>=50000
Select * from Emp where job=’clerk’ OR job=’manager’
Select * from Emp where not job=’clerk’

3. Comparison Operator
These are used to compare one expression with another. The result of
comparison are true, false or unknown

Operator Definition
= Equality
!=,<> Inequality
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example

Select * from Emp where salary =10000


Select * from Emp where salary !=10000
Select * from Emp where salary >10000
Select * from Emp where salary <10000
Select * from Emp where salary <=10000
Select * from Emp where salary >=10000

4. Symbolic Comparison operator(Range Searching & Pattern Matching)

Operator Description
IN Equal to any members of
NOT IN Not equal to any members of
IS NULL Tests for NULL
LIKE Return true when first expression
matches second
NOT LIKE Display all rows from table where data
does not match with condition
ALL Compare a value to every value in the
list
ANY,SOME Compare a value to each value in the
list
BETWEEN X and Y >=X and <=Y
EXITS True if sub query returns at least one
row

Example
Select * from Emp where job IN (‘clerk’,’ manager’)
Select * from Emp where salary NOT IN (5000, 10000)
Select * from Emp where job = ANY (‘clerk’, ’manager’)
Select * from Emp where job = SOME (‘clerk’, ’manager’)
Select * from Emp where Emp_name LIKE ‘xy%’
Select * from Emp where salary IS NULL
Select * from Emp where Emp_name NOT LIKE ‘xy%’
Select * from Emp where salary > ALL (5000, 10000)
Select * from Emp where salary BETWEEN 5000 and 30000

Set Operators
It combines the results of two separate queries into a single result. The set
operators are presented by special keywords Union, Union all, Intersection, Minus.

Union

UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and datatype
must be same in both the tables.
Example of UNION

The First table, The Second table,

ID Name
2 adam

1 abhi
3 Chester

2 adam

Union SQL query will be,


select * from First UNION select * from second

The result table will look like,

ID NAME

1 abhi

2 adam

3 Chester

Union All

This operation is similar to Union. But it also shows the duplicate rows.
Example of Union All

Union All query will be like,


select * from First UNION ALL select * from second

The result table will look like,


ID NAME

1 abhi

2 adam

2 adam

3 Chester

Intersect

Intersect operation is used to combine two SELECT statements, but it only


retuns the records which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same.
Example of Intersect

Intersect query will be,


select * from First INTERSECT select * from second

The result table will look like

ID NAME

2 adam

Minus

Minus operation combines result of two Select statements and return only those
result which belongs to first set of result..
Example of Minus

Minus query will be,


select * from First MINUS select * from second
The result table will look like,

ID NAME

1 abhi

Clauses
SQL WHERE Clause

The WHERE clause is used to filter records.

It is used to extract only those records that fulfill a specified condition.

Syntax

SELECT column1, column2, ...


FROM table_name
WHERE condition;

Example

SELECT * FROM Customers


WHERE Country='Mexico';
SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set by one or more
columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in a descending order, you can use the DESC keyword.

Syntax:

SELECT column_name, column_name


FROM table_name
ORDER BY column_name ASC|DESC, column_name ASC|DESC;

Example
SELECT * FROM Emp ORDER BY Emp_name;
SELECT * FROM Emp ORDER BY salary DESC;
GROUP BY Statement
The GROUP BY statement is used in conjunction with the aggregate functions to
group the result-set by one or more columns.

Syntax:

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name;

Example
Select deptno,sum(salary) from Emp GROUP By Deptno;

The HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not
be used with aggregate functions.It is used to filter data based on the group function.

Syntax:

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Example
Select deptno,SUM(salary) from Emp GROUP BY deptno HAVING SUM(salary)>15000

SQL JOIN
An SQL JOIN clause is used to combine rows from two or more tables, based
on a common field between them.

1. SQL INNER JOIN


The INNER JOIN keyword selects all rows from both tables as long as there
is a match between the columns in both tables.

Syntax:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
INNER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

2. SQL OUTER JOIN

1 .LEFT OUTER JOIN


The LEFT JOIN keyword returns all rows from the left table (table1), with
the matching rows in the right table (table2). The result is NULL in the right side
when there is no match.
Syntax:

SELECT column_name(s)
FROM table1
LEFT OUTER JOIN table2
ON table1.column_name=table2.column_name;

Example

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

2. RIGHT OUTER JOIN


The RIGHT JOIN keyword returns all rows from the right table (table2), with
the matching rows in the left table (table1). The result is NULL in the left side when there is
no match.

Syntax:
SELECT column_name(s)
FROM table1
RIGHT OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Orders.OrderID, Employees.FirstName
FROM Orders
RIGHT JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
ORDER BY Orders.OrderID;

3. FULL OUTER JOIN


The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from
the right table (table2).The FULL OUTER JOIN keyword combines the result of both LEFT
and RIGHT joins.

Syntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

Nested Query

In SQL, a nested query involves a query that is placed within another query.
Output of the inner query is used by the outer query. A nested query has two
SELECT statements: one for the inner query and another for the outer query.

Syntax of Nested Queries

The basic syntax of a nested query involves placing one query inside of
another query. Inner query or subquery is executed first and returns a set of
values that are then used by the outer query. The syntax for a nested query
is as follows:
SELECT column1, column2, ...
FROM table1
WHERE column1 IN ( SELECT column1
FROM table2

WHERE condition )

Examples

Consider the following sample table to execute nested queries on these.

Table: employees table

emp_id emp_name dept_id

1 John 1

2 Mary 2

3 Bob 1

4 Alice 3

5 Tom 1

Table: departments table

dept_id dept_name

1 Sales

2 Marketing

3 Finance

Table: sales table

sale_id emp_id sale_amt

1 1 1000
2 2 2000

3 3 3000

4 1 4000

5 5 5000

6 3 6000

7 2 7000

Example 1: Find the names of all employees in the Sales department.

Required query

SELECT emp_name
FROM employees
WHERE dept_id IN (SELECT dept_id
FROM departments
WHERE dept_name = 'Sales');

Output

emp_name

John

Bob

Tom

Example 2: Find the names of all employees who have made a sale

Required query

SELECT emp_name
FROM employees
WHERE EXISTS (SELECT emp_id
FROM sales
WHERE employees.emp_id = sales.emp_id);
Output

emp_name

John

Mary

Bob

Alice

Tom

This query selects all employees from the "employees" table where there
exists a sale record in the "sales" table for that employee.

Functions
Numeric functions
SQL numeric functions are used primarily for numeric
manipulation and/or mathematical calculations. The following
table details the numeric functions –
Sr.N
Function & Description
o.

ABS()
1
Returns the absolute value of numeric expression.

ACOS()
2 Returns the arccosine of numeric expression. Returns
NULL if the value is not in the range -1 to 1.

ASIN()
3 Returns the arcsine of numeric expression. Returns
NULL if value is not in the range -1 to 1

ATAN()
4
Returns the arctangent of numeric expression.
ATN2()
5 Returns the arctangent of the two variables passed to
it.

CEILING()
Returns the smallest (closest to negative infinity)
6
integer value that is greater than or equal to this
value.

COS()
7
Returns the trigonometric cosine of the given value.

COT()
8 Returns the trigonometric cotangent of the given
value.

DEGREES()
9 Returns numeric expression converted from radians to
degrees.

EXP()
10 Returns the base of the natural logarithm (e) raised to
the power of passed numeric expression.

FLOOR()
11 Returns the largest integer value that is not greater
than passed numeric expression.

LOG()
12 Returns the natural logarithm of the passed numeric
expression.

LOG10()
13 Returns the base-10 logarithm of the passed numeric
expression.

PI()
14
Returns the value of pi

POWER()
15 Returns the value of one expression raised to the
power of another expression

16 RADIANS()
Returns the value of passed expression converted
from degrees to radians.

RAND()
17
Returns the random value between 0 and 1.

ROUND()
Returns numeric expression rounded to an integer.
18
Can be used to round an expression to a number of
decimal points

SIGN()
19 Returns the sign of a number, indicating whether it is
positive, negative, or zero.

SIN()
20 Returns the sine of numeric expression given in
radians.

SQRT()
21 Returns the non-negative square root of numeric
expression.

TAN()
22 Returns the tangent of numeric expression expressed
in radians.

String Function:
Character functions accept character as a input and return either character or
number values.
Sr no.
Function Description
1
Initcap(str) Converts first letter of string to capital
letter. Example: Select initcap(‗rdbms‘)
from dual;
2
Lower(char) Converts a string to all lowercase
characters. Example: Select
lower(‗RDBMS‘) from dual;

3 Upper(char Converts a string to all uppercase characters. Example:


) Select upper(‗rdbms‘) from dual;
4
Length(char) Find outs the length of given string.
Example: Select length(‗RDBMS‘) from
dual;

5
Ltrim(char,set) It trim from the left of character string.
Example: Select Ltrim(‗manas khan‘,
‗manas‘) from dual;
6
Rtrim(char,set) It trim from the Right of character string.
Example: Select Rtrim(‗manas khan‘,
‗khan‘) from dual;
7
Translate(char,fromstring,to It returns expr with all occurrences of each
string) character in from string replaced by its
corresponding character in to_string.
Example: Select
translate(Hickory,‘H‘,‘D‘) from dual
8
Replace(char,searchstring, It returns character string with each
[repstring]) occurrences of search string replaced with
[repstring] Example: Select replace(‗Tick
and Tock‘,‘T‘,‘Cl‘) from dual;
9
Substr(char,m,n) It returns substring of character string that
stack at m character and is of length n
Example: Select substr(Triangle‘4,5) from
dual;

10
Concatenation() It merges two or more strings or a string
and a data value together Example: Select
(‗Branch is‘|| branch_name) from
table_name;
11
Lpad(char1,length, It returns char1, left-padded to given
char2) length with the sequence of characters in
char2. Example: Select Lpad(‗SKY‘, 8,
‗*‘) from dual;

12
Rpad(char1,length ,char2 It returns char1, right-padded to given
) length with the sequence of characters in
char2. Example: Select Lpad(‗SKY‘, 8,
‗*‘) from dual;

Date functions
Date functions take values that are of data type DATE as input and return values of
datatype DATE except months_between which return number as output.

Sr no.
Function Description
1
months_between(d1,d2) Used to find number of months
Where, d1 and d2 are dates between d1 and d2. If d1 later date
then d2 ans is positive If d1 earlier
than d2 answer is negative Example:
Select months_between(‘05-MAY-
1996‘,‘05-JAN-1996‘) from dual;
2
add_months(d,n) Where,d is Returns date after adding the number
date, n no of months to be added of months specified with the function.
Example: Select
add_months(sysdate,2) from dual;
3
Next_day(d,char) Where d is Returns the date of the first weekday
date, char- day of week named ‗char‘ that is after the date
named by date. Example: Select
next_day(‘01-FEB-
2006‘,‘Wednesday‘) from dual;
4
Last_day(d) Where, d is date Returns the last day of the month that
contains date ‗d‘. Example: Select
last_day(sysdate) from dual
5
Round(date,[fmt]) Where, fmt Returns date rounded to the unit
format model Month Day Year specified by the format model ‗fmt‘.
Example: Select round(sysdate,‘day‘)
from dual;
6
Trunc(date([fmt]) Where, fmt Returns date with the time portion of
format model Month Day Year the day truncated to the unit specified
by the format model fmt. Example:
Select trunc(sysdate,‘day‘) from dual;

Aggregate function:
The aggregate functions are function that takes a collection of values as input
and returns single value as output. The general syntax of aggregate function is

Syntax:
Aggregate_function name (expression)

Useful aggregate functions:


 AVG() - Returns the average value
 COUNT() - Returns the number of rows
 MAX() - Returns the largest value
 MIN() - Returns the smallest value
 SUM() - Returns the sum
Example

Select AVG (salary) from Emp


Select COUNT (Emp_id) from Emp
Select MAX (salary) from Emp
Select MIN (salary) from Emp
Select SUM (salary) from Emp

Views
It can be defined as logical part of total data present in the table. It can be created
with the help of select command. Views are created for security reasons. Instead of coping
same table multiple times for different requirements, views can be created. View is a logical
copy of physical table. It doesn‘t exist physically. With the help of view, we can give
restricted access to users. When view is used, underlying table is invisible, thus increasing
security. Views can be used to see, insert, update and delete data from base table.

Advantages of Views:
1. Views restrict access to the data because the view can display selective columns from the
table.
2. Views can be used to make simple queries to retrieve the results of complicated queries.
3. Views provide data independence for adhoc users and application programs. One view can
be used to retrieve data from several tables.
4. Views provide groups of users to access to data according to their particular criteria. Thus
implements security and authorization.

Syntax for creating view:-


Create [OR Replace][Force /No force] view <view name>[alias name ….]
As subquery
[With CHECK OPTION [CONSTRAINT]] [With READ ONLY];

Example
Create view v1 as select * from Emp;
Create view v1 as select Emp_id,Emp_ name,deptno from Emp;

To view the record from view:


Select * from v1;

Insert into view:


It can be used to insert data to the table as well as view.
Example
Create view v2 as select * from Emp;

Insert into v2 values (1,’xyz’, 10000, 10)


The above command insert value into v2 as well as table EMP.

Update view:
It can be used to update data from the table as well as view.
Example

Create view v3 as select * from Emp;

Update v3 set salary =salary+2000;

Delete view:
It can be used to delete data from the table as well as view.
Example

Create view v4 as select * from Emp;

Delete from v4 where Emp_id=112;

View and Subqueries:


The view can be created by using sub queries as follows.
Example
Create view v5 as select Emp-id,Emp_name,salary from Emp where
deptno=_select deptno from dept1 where city=’pune’)

View and joins:


The view can be created by joining multiple table.
Example
Create view v6 as select e.Emp_id, e.Emp_ name, e.salary,e.deptno,d.Dept_name,d.city from
Emp e, Dept d where e.deptno=d.deptno

What view cannot do?


If view is created from multiple base tables then it does not allow insertion,
updation and deletion operation.
If view is created from single base table then it allow insert, update and delete
operation on views.

Dropping views:
Drop view command is used to drop the view
Syntax
Drop view <view name>
Example
Drop view v1
SEQUENCE

Definition:
A sequence refers to a database object that is capable of generating unique and
sequential integer values.

Use:
1. It saves a time by reducing application code.
2. It is used to generate unique sequential integers.
3. It is used to create an auto number fields.
4. Sequence can be use for many tables/relations

Syntax:

Create sequence <seq_name> [increment by num] [start with num] [maxvalue num]
[minvalue
num][cycle/nocycle][cache num/nocache];

Where,

Increment by num: Used to specify the interval between sequence numbers.

Start with num: States the first sequence numbers that needs to be generated.

Minvalue num: This is used to state the minimum value of the sequence.

Maxvalue num: It states the maximum value generated by sequence.

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.

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.
No Cache: This states that there is no pre-allocation for the values of sequence.

Example:

Create sequence student_seq increment by 1 start with 1 maxvalue 60 nocycle;

Altering Sequences

If we want to change the structures or values we can alter it.

Syntax:

Alter sequences <sequence name > Variable name;


Eg. Alter sequence seq_1 maxvalue 15;

Dropping Sequences:

It is use to drop or delete the sequences we create.

Syntax:

Drop Sequence <sequence Name>

Eg. Drop sequence Seq_1

INDEX:
An index is a schema object that can speed up the retrieval of rows by
using pointer. An index provides direct and fast access to rows in a table. Indexes are created
explicitly Or automatically. Indexes are used to speed up searches/queries.

Types of Index:
Simple index (Single column): An index created on single column of a table is called a
Simple Index.
Composite (concatenated): An index created on multiple column of a single table is called a
Composite Index.
Unique indexes: They 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:
Creating simple index
Create index <index name > on <table name> <column name>
Example
Create index idx1 on Emp (Ename)
Creating multiple index
Create index <index name > on <table name> <column name1, column name2>
Example
Create index idx2 on Emp (Ename,Salary)
Creating Unique index
Create unique index <index name > on <table name> <column name>
Example
Create unique index idx3 on Emp (Ename)
Dropping Index

Drop Index <Index Name>

E.g. .

Drop index id1;

SYNONYMS
It is a name given to the table, view, sequence, stored procedure, function for the
user’s conveniences to use.

Creating synonyms:
Create synonyms command is used to create the synonyms.
Syntax

Create synonym <synonym name> for <object name>


Example

Create synonym emp_syn1 for Emp;

To view synonym:

Select * from emp_syn1

Dropping synonym:

Syntax

Drop synonym < synonym name>


Example
Drop synonym emp_syn1

You might also like