Table of Contents
1. Sequence introduction
2. Create a sequence
3. Query sequence
4. Use the sequence
NEXTVAL and CURRVAL pseudo columns
5. Modify the sequence
6. Delete sequence
7. Create auto-increment sequence
Home Database Oracle Oracle sequence SEQUENCE analysis

Oracle sequence SEQUENCE analysis

Jul 28, 2022 pm 03:49 PM
oracle

This article brings you relevant knowledge about Oracle, and explains the sequence SEQUENCE in Oracle in detail. The article introduces it in detail through sample code. It has certain reference value for everyone's study or work, and I hope it will be helpful to everyone.

Oracle sequence SEQUENCE analysis

Recommended tutorial: "Oracle Video Tutorial"

1. Sequence introduction

Oracle's sequence is a A database object whose main function is to generate unique values. After the sequence is created, the sequence object can be found through the data dictionary, so the sequence can be shared by multiple objects.

2. Create a sequence

The sequence is created using the CREATE SEQUENCE syntax:

1

2

3

4

5

6

7

CREATE SEQUENCE sequence

[INCREMENT BY n]

 [START WITH n]

 [{MAXVALUE n | NOMAXVALUE}]

 [{MINVALUE n | NOMINVALUE}]

 [{CYCLE | NOCYCLE}]

 [{CACHE n | NOCACHE}];

Copy after login
  • NCREMENT BY: used to define the step size of the sequence, if omitted, it defaults Is 1. If it is a negative value, it means that the value of the sequence is decreasing.
  • START WITH: Defines the initial value of the sequence (that is, the first value generated), the default is 1.
  • MAXVALUE: Defines the maximum value that the sequence can generate. NOMAXVALUE is the default option, which means there is no maximum value. At this time, for an increasing sequence, the maximum value the system can generate is 10 to the 27th power; for a decreasing sequence, the maximum value is -1.
  • MINVALUE: Defines the minimum value that the sequence can generate. NOMINVALUE is the default option, which means there is no minimum value. At this time, for the descending sequence, the minimum value the system can generate is negative 10 to the 26th power; for the descending sequence, the minimum value is 1.
  • CYCLE and NOCYCLE: Indicate whether to loop when the value of the sequence generator reaches the limit. If looping, when the increasing sequence reaches the maximum value, it loops to the minimum value; for the descending sequence, when it reaches the minimum value, it loops to the maximum value. If you do not loop, after reaching the limit value, an error will occur if you continue to generate new values.
  • CACHE: Defines the size of the memory block to store the sequence, the default is 20. NOCACHE means no memory buffering of the sequence. Memory buffering of sequences can improve sequence performance.

For example:

1

2

3

4

5

CREATE SEQUENCE invoice_seq

INCREMENT BY 1

START WITH 1

MAXVALUE 9999999

NOCYCLE NOCACHE;

Copy after login

3. Query sequence

Once the sequence is created, the sequence creation code is textualized in the data dictionary and can be found in the user_objects data See it in the dictionary, such as:

1

SELECT object_name,object_id,object_type  FROM user_objects WHERE object_name = 'INVOICE_SEQ';

Copy after login

The sequence details are saved in the user_sequences table:

1

SELECT sequence_name, min_value, max_value, increment_by, last_number  FROM user_sequences;

Copy after login

4. Use the sequence

NEXTVAL and CURRVAL pseudo columns

  • NEXTVAL: Returns the next available sequence value. It returns a unique referenced value each time, and this is actually true for different users. When using sequence.NEXTVAL, a new sequence number is generated and the current sequence number is put into CURRVAL.
  • CURRVAL: Get the current sequence value. If you use CURRVAL before using NEXTVAL for the first time, an error will be reported.

is used as follows:

1

2

3

4

SELECT invoice_seq.CURRVAL,invoice_seq.NEXTVAL FROM DUAL;

 

INSERT INTO invoice  (invoice_id, vendor_id, invoice_number, invoice_total  )

      VALUES (invoice_seq.NEXTVAL, 10, 'INV' || invoice_seq.CURRVAL, 100  );

Copy after login

NEXTVAL and CURRVAL can be used in the following context:

  • is not part of a subquery The field list of the SELECT statement.
  • The SELECT list of the subquery in the INSERT statement.
  • VALUES clause in the INSERT statement.
  • SET clause in UPDATE statement.

NEXTVAL and CURRVAL cannot be used in the following context:

  • The SELECT list of a view.
  • SELECT statement with DISTINCT.
  • SELECT statement with GROUP BY, HAVING or ORDER BY clause.
  • Clauses in SELECT, DELETE or UPDATE statements.
  • DEFAULT expression in CREATE TABLE or ALTER TABLE statement.

Also note that ROLLBACK does not roll back the sequence value.

5. Modify the sequence

For example:

1

ALTER SEQUENCE invoice_seq     INCREMENT BY 2 MAXVALUE 10   NOCACHE  NOCYCLE;

Copy after login

When modifying the sequence, there are the following restrictions:

  • The table sequence cannot be started initial value.
  • The minimum value cannot be greater than the current value.
  • The maximum value cannot be less than the current value.
  • The modified sequence rules will not affect previous sequence values, only future sequence values ​​will be affected.
  • Users must have ALTER SEQUENCE permissions.

6. Delete sequence

1

DROP SEQUENCE invoice_seq;

Copy after login

7. Create auto-increment sequence

1. Create a sequence

1

2

create sequence sq_recid

minvalue 1 maxvalue 999999  increment by 1   start with 1 noCYCLE;

Copy after login

2. Create a trigger

1

2

3

4

5

6

7

create or replace trigger  trg_test

  before  insert on test for each row

begin

  select sq_recid.nextval into :new.ID from dual;

end;

 

alter  trigger trg_test  enable;

Copy after login

3. In C#, you can also manually insert sequences into the table

1

2

string sql="insert into test(ID,otherCol)value (Sql_recid.nextval,***)

    retuing ID into :ID"

Copy after login

Recommended tutorial: "Oracle Video Tutorial"

The above is the detailed content of Oracle sequence SEQUENCE analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check tablespace size of oracle How to check tablespace size of oracle Apr 11, 2025 pm 08:15 PM

To query the Oracle tablespace size, follow the following steps: Determine the tablespace name by running the query: SELECT tablespace_name FROM dba_tablespaces; Query the tablespace size by running the query: SELECT sum(bytes) AS total_size, sum(bytes_free) AS available_space, sum(bytes) - sum(bytes_free) AS used_space FROM dba_data_files WHERE tablespace_

How to import oracle database How to import oracle database Apr 11, 2025 pm 08:06 PM

Data import method: 1. Use the SQLLoader utility: prepare data files, create control files, and run SQLLoader; 2. Use the IMP/EXP tool: export data, import data. Tip: 1. Recommended SQL*Loader for big data sets; 2. The target table should exist and the column definition matches; 3. After importing, data integrity needs to be verified.

How to uninstall Oracle installation failed How to uninstall Oracle installation failed Apr 11, 2025 pm 08:24 PM

Uninstall method for Oracle installation failure: Close Oracle service, delete Oracle program files and registry keys, uninstall Oracle environment variables, and restart the computer. If the uninstall fails, you can uninstall manually using the Oracle Universal Uninstall Tool.

How to create a table in oracle How to create a table in oracle Apr 11, 2025 pm 08:00 PM

Creating an Oracle table involves the following steps: Use the CREATE TABLE syntax to specify table names, column names, data types, constraints, and default values. The table name should be concise and descriptive, and should not exceed 30 characters. The column name should be descriptive, and the data type specifies the data type stored in the column. The NOT NULL constraint ensures that null values ​​are not allowed in the column, and the DEFAULT clause specifies the default values ​​for the column. PRIMARY KEY Constraints to identify the unique record of the table. FOREIGN KEY constraint specifies that the column in the table refers to the primary key in another table. See the creation of the sample table students, which contains primary keys, unique constraints, and default values.

How to view instance name of oracle How to view instance name of oracle Apr 11, 2025 pm 08:18 PM

There are three ways to view instance names in Oracle: use the "sqlplus" and "select instance_name from v$instance;" commands on the command line. Use the "show instance_name;" command in SQL*Plus. Check environment variables (ORACLE_SID on Linux) through the operating system's Task Manager, Oracle Enterprise Manager, or through the operating system.

How to re-query oracle How to re-query oracle Apr 11, 2025 pm 07:33 PM

Oracle provides multiple deduplication query methods: The DISTINCT keyword returns a unique value for each column. The GROUP BY clause groups the results and returns a non-repetitive value for each group. The UNIQUE keyword is used to create an index containing only unique rows, and querying the index will automatically deduplicate. The ROW_NUMBER() function assigns unique numbers and filters out results that contain only line 1. The MIN() or MAX() function returns non-repetitive values ​​of a numeric column. The INTERSECT operator returns the common values ​​of the two result sets (no duplicates).

How to encrypt oracle view How to encrypt oracle view Apr 11, 2025 pm 08:30 PM

Oracle View Encryption allows you to encrypt data in the view, thereby enhancing the security of sensitive information. The steps include: 1) creating the master encryption key (MEk); 2) creating an encrypted view, specifying the view and MEk to be encrypted; 3) authorizing users to access the encrypted view. How encrypted views work: When a user querys for an encrypted view, Oracle uses MEk to decrypt data, ensuring that only authorized users can access readable data.

How to read the oracle awr report How to read the oracle awr report Apr 11, 2025 pm 09:45 PM

An AWR report is a report that displays database performance and activity snapshots. The interpretation steps include: identifying the date and time of the activity snapshot. View an overview of activities and resource consumption. Analyze session activities to find session types, resource consumption, and waiting events. Find potential performance bottlenecks such as slow SQL statements, resource contention, and I/O issues. View waiting events, identify and resolve them for performance. Analyze latch and memory usage patterns to identify memory issues that are causing performance issues.

See all articles