Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Lecture 5 - Advanced SQL

The document discusses various SQL constraints such as NOT NULL, DEFAULT, UNIQUE, PRIMARY KEY and how to add or drop them using ALTER TABLE. It also covers SQL joins like INNER JOIN, LEFT JOIN, SELF JOIN and UNION operators.

Uploaded by

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

Lecture 5 - Advanced SQL

The document discusses various SQL constraints such as NOT NULL, DEFAULT, UNIQUE, PRIMARY KEY and how to add or drop them using ALTER TABLE. It also covers SQL joins like INNER JOIN, LEFT JOIN, SELF JOIN and UNION operators.

Uploaded by

jubairahmed1678
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Advanced SQL

Constraints
• Constraints are the rules enforced on the data columns of a table.
These are used to limit the type of data that can go into a table. This
ensures the accuracy and reliability of the data in the database.
• Constraints could be either on a column level or a table level. The
column level constraints are applied only to one column, whereas the
table level constraints are applied to the whole table.
Commonly used Constraints available in SQL
• NOT NULL Constraint – Ensures that a column cannot have a null value
CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Commonly used Constraints available in
SQL
• If CUSTOMERS table has already been created, then to add a NOT
NULL constraint to the SALARY column in Oracle and MySQL, you
would write a query like the one that is shown in the following code
block.
ALTER TABLE CUSTOMERS
MODIFY SALARY DECIMAL (18, 2) NOT NULL;
Commonly used Constraints available in SQL
• DEFAULT Constraint - Provides a default value for a column when none is
specified.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2) DEFAULT 5000.00,
PRIMARY KEY (ID)
);
Commonly used Constraints available in SQL
• If the CUSTOMERS table has already been created, then to add a
DEFAULT constraint to the SALARY column, you would write a query
like the one which is shown in the code block below.
MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;

To drop a DEFAULT constraint, use the following SQL query.

ALTER TABLE CUSTOMERS


ALTER COLUMN SALARY DROP DEFAULT;
Commonly used Constraints available in SQL
• UNIQUE Constraint – to apply a unique constraint to age the syntax would be

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Commonly used constraints available in SQL
• If the CUSTOMERS table has already been created, then to add a UNIQUE
constraint to the AGE column. You would write a statement like the query that is
given in the code block below.
ALTER TABLE CUSTOMERS
MODIFY AGE INT NOT NULL UNIQUE;
You can also use the following syntax, which supports naming the constraint in
multiple columns as well.
ALTER TABLE CUSTOMERS
ADD CONSTRAINT myUniqueConstraint UNIQUE(AGE, SALARY);
To drop a UNIQUE constraint, use the following SQL query.
ALTER TABLE CUSTOMERS
DROP CONSTRAINT myUniqueConstraint;
Commonly used constraints available in SQL

• PRIMARY KEY - Uniquely identifies each row/record in a database table.


CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
Commonly used constraints available in SQL
• To create a PRIMARY KEY constraint on the "ID" column when the
CUSTOMERS table already exists, use the following SQL syntax −

ALTER TABLE CUSTOMER ADD PRIMARY KEY (ID);

NOTE − If you use the ALTER TABLE statement to add a primary key, the
primary key column(s) should have already been declared to not contain NULL
values (when the table was first created)
Delete Primary Key

ALTER TABLE CUSTOMERS DROP PRIMARY KEY ;


SQL - Joins
• The SQL Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each.
• There are different types of joins available in SQL −
• INNER JOIN − returns rows when there is a match in both tables.
• LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
table.
• RIGHT JOIN − returns all rows from the right table, even if there are no matches in the left
table.
• FULL JOIN − returns rows when there is a match in one of the tables.
• SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
• CARTESIAN JOIN − returns the Cartesian product of the sets of records from the two or
more joined tables.
Inner Join
• The most important and frequently used of the joins is the INNER JOIN.
• The INNER JOIN creates a new result table by combining column values of
two tables (table1 and table2) based upon the join-predicate. The query
compares each row of table1 with each row of table2 to find all pairs of rows
which satisfy the join-predicate. When the join-predicate is satisfied, column
values for each matched pair of rows of A and B are combined into a result
row.
SELECT table1.column1, table2.column2...
FROM table1
INNER JOIN table2
ON table1.common_field = table2.common_field;
Left Join
• The SQL LEFT JOIN returns all rows from the left table, even if there are
no matches in the right table. This means that if the ON clause matches 0
(zero) records in the right table; the join will still return a row in the result,
but with NULL in each column from the right table.
• This means that a left join returns all the values from the left table, plus
matched values from the right table or NULL in case of no matching join
predicate.
SELECT table1.column1, table2.column2...
FROM table1
LEFT JOIN table2
ON table1.common_field = table2.common_field;
Full Join
• The SQL FULL JOIN combines the results of both left and right outer joins.
• The joined table will contain all records from both the tables and fill in
NULLs for missing matches on either side.

SELECT table1.column1, table2.column2...


FROM table1
FULL JOIN table2
ON table1.common_field = table2.common_field;
Self Join
• The SQL SELF JOIN is used to join a table to itself as if the table were two
tables; temporarily renaming at least one table in the SQL statement.
SELECT a.column_name, b.column_name...
FROM table1 a
JOIN table1 b
WHERE CONDITION;

Here, the WHERE clause could be any given expression based on your
requirement.
Cartesian Join
• The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets
of records from two or more joined tables.
SELECT ColumnName_1,
ColumnName_2,
ColumnName_N
FROM [Table_1]
CROSS JOIN [Table_2]
or
SELECT ColumnName_1,
ColumnName_2,
ColumnName_N
FROM [Table_1],[Table_2]
Union Operator
The SQL UNION clause/operator is used to combine the results of two or more
SELECT statements without returning any duplicate rows.
To use this UNION clause, each SELECT statement must have
• The same number of columns selected
• The same number of column expressions
• The same data type and
• Have them in the same order
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
Union All Operator
• The UNION ALL operator is used to combine the results of two SELECT
statements including duplicate rows.
• The same rules that apply to the UNION clause will apply to the UNION
ALL operator.
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION ALL
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
Intersect Operator
• The SQL INTERSECT clause/operator is used to combine two SELECT
statements, but returns rows only from the first SELECT statement that are
identical to a row in the second SELECT statement. This means INTERSECT
returns only common rows returned by the two SELECT statements.
• Just as with the UNION operator, the same rules apply when using the
INTERSECT operator. MySQL does not support the INTERSECT operator.

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
Except Operator
• The SQL EXCEPT clause/operator is used to combine two SELECT statements
and returns rows from the first SELECT statement that are not returned by the
second SELECT statement. This means EXCEPT returns only rows, which are
not available in the second SELECT statement.
• Just as with the UNION operator, the same rules apply when using the EXCEPT
operator. MySQL does not support the EXCEPT operator.

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]
EXCEPT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
Alter Table
• The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table.
You should also use the ALTER TABLE command to add and drop various constraints on an existing
table.

ALTER TABLE table_name ADD column_name datatype; - to add column


ALTER TABLE table_name DROP COLUMN column_name; - drop column
ALTER TABLE table_name MODIFY COLUMN column_name datatype; - change datatype
ALTER TABLE table_name MODIFY column_name datatype NOT NULL; - add NOT NULL
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...); - add CONSTRAINT
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint – to drop constraint

Many other options are available with the ALTER COMMAND.


Index
• Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply
put, an index is a pointer to data in a table. An index in a database is very similar to an index in the back of a
book.
• For example, if you want to reference all pages in a book that discusses a certain topic, you first refer to the
index, which lists all the topics alphabetically and are then referred to one or more specific page numbers.
• An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input, with the
UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on the data.
• Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify
the table and which column or columns to index, and to indicate whether the index is in an ascending or
descending order.
• Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries in the
column or combination of columns on which there is an index.
Index
• Single-Column Indexes - A single-column index is created based on only one table column. The basic
syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);
• 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. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);
• A composite index - is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
• Implicit indexes are indexes that are automatically created by the database server when an object is created.
Indexes are automatically created for primary key constraints and unique constraints.
Index
• An index can be dropped using SQL DROP command. Care should be taken when dropping an index
because the performance may either slow down or improve.
DROP INDEX index_name;

When should indexes be avoided?

Although indexes are intended to enhance a database's performance, there are times when they should be
avoided. The following guidelines indicate when the use of an index should be reconsidered.
 Indexes should not be used on small tables.
 Tables that have frequent, large batch updates or insert operations.
 Indexes should not be used on columns that contain a high number of NULL values.
 Columns that are frequently manipulated should not be indexed.
Index
•Example - For example, the following SQL syntax creates a new table called CUSTOMERS and adds five
columns in it.
CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID));

•Now, you can create an index on a single or multiple columns using the syntax given below.
CREATE INDEX index_name
ON table_name ( column1, column2.....);

•To create an INDEX on the AGE column, to optimize the search on customers for a specific age, you can use
the follow SQL syntax which is given below −
CREATE INDEX idx_age
ON CUSTOMERS ( AGE );
Index
•DROP an INDEX Constraint - To drop an INDEX constraint, use the following SQL syntax.

ALTER TABLE CUSTOMERS


DROP INDEX idx_age;

Remember - The INDEX is used to create and retrieve data from the database very quickly. An Index can be
created by using a single or group of columns in a table. When the index is created, it is assigned a ROWID for
each row before it sorts out the data.

Proper indexes are good for performance in large databases, but you need to be careful while creating an index. A
Selection of fields depends on what you are using in your SQL queries.
Truncate
•The SQL TRUNCATE TABLE command is used to delete all the records from an existing table by reinitializing
the table's structure. This command instructs the database to deallocate the space for all records in a table and
change this table's structure by resetting the table size. This is the reason why it is deemed to be a Data Definition
Language (DDL) operation rather than Data Manipulation Language (DML), even though all the table data is
removed.

•Logically, the TRUNCATE TABLE statement performs similarly to the DELETE TABLE statement but without
the WHERE clause. However, TRUNCATE is much faster than DELETE and does not allow roll back once
committed.

•You can also use DROP TABLE command to delete a table but it will remove the complete table structure from
the database and you would need to re-create this table once again if you wish you store some data again.
The basic syntax of a TRUNCATE TABLE command is as follows.

TRUNCATE TABLE table_name;


Truncate Vs Delete
DELETE TRUNCATE
The DELETE command in SQL removes one or more SQL's TRUNCATE command is used to remove all of the
rows from a table based on the conditions specified in rows from a table, regardless of whether or not any
a WHERE Clause. conditions are met.

It is a DML(Data Manipulation Language) command. It is a DDL(Data Definition Language) command.

There is a need to make a manual COMMIT after When you use the TRUNCATE command, the
making changes to the DELETE command, for the modifications made to the table are committed
modifications to be committed. automatically.

It deletes rows one at a time and applies some criteria It removes all of the information in one go
to each deletion.

When it comes to large databases, it is much slower. It is faster.


Views
•Creating a view is simply creating a virtual table using a query. A view is an SQL statement that is stored in the
database with an associated name. It is actually a composition of a table in the form of a predefined SQL query.
•A view can contain rows from an existing table (all or selected). A view can be created from one or many tables
which depends on the written SQL query to create a view. Unless indexed, a view does not exist in a database.
•Views, which are a type of virtual tables allow users to do the following −
• Structure data in a way that users or classes of users find natural or intuitive.
• Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no
more.
• Summarize data from various tables which can be used to generate reports.

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];
Views
Example - Create view first_view AS SELECT * FROM customers;
•With Check Option.
•The WITH CHECK OPTION is a CREATE VIEW statement option. The purpose of the WITH CHECK
OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view definition.
•If they do not satisfy the condition(s), the UPDATE or INSERT returns an error. The following code block has
an example of creating same view CUSTOMERS_VIEW with the WITH CHECK
CREATE VIEW CUSTOMERS_VIEW
AS SELECT name, age FROM CUSTOMERS
WHERE age IS NOT NULL
WITH CHECK OPTION;
The WITH CHECK OPTION in this case should deny the entry of
any NULL values in the view's AGE column, because the view is
defined by data that does not have a NULL value in the AGE
column.
Update Views – Only for simple view (One Table
View)
• The SQL UPDATE Query is used to modify the existing records in a table or a
view. It is a Data Manipulation Language Command as it only modifies the
data of the database object.
• The UPDATE statement makes use of locks on each row while modifying them
in a table or view, and once the row is modified, the lock is released.
Therefore, it can either make changes to a single row or multiple rows with a
single query.
UPDATE view_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Update Views – Example
Create view CUSTOMERS_VIEW AS SELECT * FROM CUSTOMERS;
• Now, through the view you created, you can update the age of Ramesh to 35 in the
original CUSTOMERS table, using the following code block −
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.
Updating Multiple columns
UPDATE CUSTOMERS_VIEW
SET NAME = 'Kaushik', AGE = 24
WHERE ID = 3;

Multiple Rows UPDATE CUSTOMERS_VIEW


Drop View
The SQL DROP View statement is used to delete an existing view, along with its
definition and other information. Once the view is dropped, all the permissions
for it will also be removed.
Suppose a table is dropped using the DROP TABLE command and it has a view
associated to it, this view must also be dropped explicitly using the DROP VIEW
command.
While trying to perform queries, the database engine checks all the objects
referenced in that statement are valid and exist. So, if a view does not exist in
the database, the DROP VIEW statement will throw an error.
DROP VIEW view_name;
DROP VIEW [IF EXISTS] view_name;
(Does not throw error if view does not exist)
Stored Procedure
A stored procedure is a group of pre-compiled SQL
statements (prepared SQL code) that can be reused again
and again.

They can be used to perform a wide range of database


operations such as inserting, updating, or deleting data,
generating reports, and performing complex calculations.
Stored procedures are very useful because they allow you to
encapsulate (bundle) a set of SQL statements as a single unit
and execute them repeatedly with different parameters,
making it easy to manage and reuse code.
Stored Procedure - Syntax
CREATE PROCEDURE procedure_name
@parameter1 datatype,
@parameter2 datatype
AS
BEGIN
-- SQL statements to be executed
END
Where,

The CREATE PROCEDURE statement is used to create the procedure. After creating the
procedure, we can define any input parameters that the procedure may require. These
parameters are preceded by the '@' symbol and followed by their respective data types.
The AS keyword is used to begin the procedure definition. The SQL statements
that make up the procedure are placed between the BEGIN and END keywords.
Stored Procedure - Example
Customer Table CREATE PROCEDURE GetCustomerInfo
@CutomerAge INT
AS
BEGIN
SELECT * FROM CUSTOMERS
WHERE AGE = @CutomerAge
END

EXEC GetCustomerInfo @CutomerAge = 25


Procedure with IN Parameter
The IN parameter is the default parameter that will receive input value from the program.
We can pass the values as arguments when the stored procedure is being executed. These
values are read-only, which means they cannot be modified by the stored procedure.

CREATE PROCEDURE GetCustomerSalary


@CustomerID INT
AS
BEGIN
SELECT SALARY FROM CUSTOMERS WHERE ID = @CustomerID
END

EXEC GetCustomerSalary @CustomerID = 6


Procedure with OUT Parameter
The OUT parameter sends output value to the program. It allows us to return a value or set
of values to the calling program.
Note that when using an OUT parameter, we must specify the keyword "OUT" after the
parameter name when passing it to the stored procedure.
CREATE PROCEDURE GetCustomerSalary
@CustomerID INT,
@Salary DECIMAL(18,2) OUT
AS
BEGIN
SELECT @Salary = SALARY FROM CUSTOMERS WHERE ID = @CustomerID
END
DECLARE @CustSalary DECIMAL(18, 2)
EXEC GetCustomerSalary @CustomerID = 4, @Salary = @CustSalary OUT
SELECT @CustSalary AS 'Customer Salary'
Procedure – Other actions
Rename
sp_rename 'old_procedure_name', 'new_procedure_name';
Modify
ALTER PROCEDURE procedure_name
AS
BEGIN
-- New procedure code goes here
END
Drop
DROP PROCEDURE [IF EXISTS] procedure_name;
If the stored procedure is referenced by other objects such as views or other stored procedures,
we need to update those references manually to reflect the new name of the stored procedure.
Additionally, dropping a stored procedure may impact any scripts or applications that rely on the
stored procedure.
Advantages of Stored Procedures
• Improved Performance − Stored procedures are pre-compiled and stored on the server, so
they can be executed more quickly than SQL statements that are sent from client applications.
• Code Reuse − Stored procedures can be called from different client applications, which means
that the same code can be reused across different applications. This reduces development time
and maintenance costs.
• Reduced Network Traffic − Because stored procedures are executed on the server, only the
results are returned to the client, which reduces network traffic and improves application
performance.
• Better Security − Stored procedures can be used to enforce security rules and prevent
unauthorized access to sensitive data. They can also limit the actions that can be performed by
users, making it easier to maintain data integrity and consistency.
• Simplified Maintenance − By storing SQL code in a single location, it becomes easier to
maintain and update the code. This makes it easier to fix bugs, add new functionality, and
optimize performance.
Drawbacks of Stored Procedures
• Increased Overhead − Stored procedures can consume more server resources
than simple SQL statements, particularly when they are used frequently or for
complex operations.
• Limited Portability − Stored procedures are often specific to a particular database
management system (DBMS), which means they may not be easily portable to
other DBMSs.
• Debugging Challenges − Debugging stored procedures can be more challenging
than debugging simple SQL statements, particularly when there are multiple
layers of code involved.
• Security Risks − If stored procedures are not written correctly, they can pose a
security risk, particularly if they are used to access sensitive data or to perform
actions that could compromise the integrity of the database.
Transactions
• A transaction is a unit of work that is performed against a database. Transactions
are units or sequences of work accomplished in a logical order, whether in a
manual fashion by a user or automatically by some sort of a database program.

• A transaction is the propagation of one or more changes to the database. For


example, if you are creating a record or updating a record or deleting a record
from the table, then you are performing a transaction on that table. It is
important to control these transactions to ensure the data integrity and to handle
database errors.

• Practically, you will club many SQL queries into a group and you will execute all of
them together as a part of a transaction.
Properties of Transactions
Transactions have the following four standard properties, usually referred to by the
acronym ACID.
• Atomicity − ensures that all operations within the work unit are completed
successfully. Otherwise, the transaction is aborted at the point of failure and all
the previous operations are rolled back to their former state.
• Consistency − ensures that the database properly changes states upon a
successfully committed transaction.
• Isolation − enables transactions to operate independently of and transparent to
each other.

• Durability − ensures that the result or effect of a committed transaction persists


in case of a system failure.
Transaction Control
The following commands are commonly used to control transactions.
COMMIT − to save the changes.
ROLLBACK − to roll back the changes.
SAVEPOINT − creates points within the groups of transactions in
which to ROLLBACK.
Transactional control commands are only used with the DML
Commands such as - INSERT, UPDATE and DELETE only. They cannot be
used while creating tables or dropping them because these operations
are automatically committed in the database.
The COMMIT Command
The COMMIT command is the transactional command used to save
changes invoked by a transaction to the database.
The COMMIT command is the transactional command used to save
changes invoked by a transaction to the database. The COMMIT
command saves all the transactions to the database since the last
COMMIT or ROLLBACK command.

The syntax for the COMMIT command is as follows.


COMMIT;
The ROLLBACK Command
The ROLLBACK command is the transactional command used to undo
transactions that have not already been saved to the database. This
command can only be used to undo transactions since the last
COMMIT or ROLLBACK command was issued.

The syntax for a ROLLBACK command is as follows −

ROLLBACK;
The SAVEPOINT Command
A SAVEPOINT is a point in a transaction when you can roll the
transaction back to a certain point without rolling back the entire
transaction.
The syntax for a SAVEPOINT command is as shown below.−
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among all the
transactional statements. The ROLLBACK command is used to undo a group of
transactions.
The syntax for rolling back to a SAVEPOINT is as shown below.
ROLLBACK TO SAVEPOINT_NAME;
The SAVEPOINT Command - Example
SQL> SAVEPOINT SP1;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
SQL> SAVEPOINT SP2;
SQL> ROLLBACK TO SP2;
Savepoint created.
Rollback complete.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.
Sequences

The sequences in SQL is a database object that generates a


sequence of unique integer values. They are frequently 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.
A sequence is created using the CREATE SEQUENCE
statement in SQL. The statement specifies the name of the
sequence, the starting value, the increment, and other
properties of the sequence.
Sequences

Following is the syntax to create a sequence in SQL −


CREATE SEQUENCE Sequence_Name
START WITH Initial_Value
INCREMENT BY Increment_Value
MINVALUE Minimum_Value
MAXVALUE Maximum_Value
CACHE I NOCACHE ------ Optional
CYCLE|NOCYCLE;
Sequences
Sequence_Name − This specifies the name of the sequence.

Initial_Value − This specifies the starting value from where the sequence should start.

Increment_Value − This specifies the value by which the sequence will increment by itself. This can be valued positively or
negatively.

Minimum_Value − This specifies the minimum value of the sequence.

Maximum_Value − This specifies the maximum value of the sequence.

Cache - Specify how many values of the sequence the database preallocates and keeps in memory for faster access. The
maximum value allowed for CACHE must be less than the value determined by the following formula: (CEIL (MAXVALUE -
MINVALUE)) / ABS (INCREMENT)

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

Cycle − When the sequence reaches its Maximum_Value, it starts again from the beginning.

Nocycle − An exception will be thrown if the sequence exceeds the Maximum_Value.


Sequences - Example
Thank You

You might also like