A sequence in a database is a database object that generates a sequential list of unique numbers, which can be particularly useful for creating primary keys, unique identifiers, or timestamps for rows in a table. Using sequences helps ensure data integrity by preventing duplicate keys and can simplify the process of inserting new rows into a table.
Proposed Use Case:
Imagine a scenario where you have a table for customer orders. Each order needs a unique order ID, which could be efficiently managed using a sequence.
Steps to Create and Use a Sequence:
- Create a Sequence: First, you will create a sequence that generates values for the order ID.
- Use the Sequence: When inserting a new order into the orders table, you can utilize the sequence to assign a unique ID to the order.
Example Code:
Below is an example SQL code to create a sequence and use it in an INSERT statement. Assume we are using a PostgreSQL database.
-- Step 1: Create the sequence
CREATE SEQUENCE order_id_seq
START WITH 1 -- Initial value of the sequence
INCREMENT BY 1 -- Increment by 1 for each new value
NO MINVALUE -- No minimum value
NO MAXVALUE -- No maximum value
CACHE 1; -- Cache size
-- (Optional) Check the current value of the sequence
SELECT nextval('order_id_seq');
-- Step 2: Create an orders table
CREATE TABLE orders (
order_id INT PRIMARY KEY, -- Will use the sequence to populate this
customer_name VARCHAR(255),
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Step 3: Insert a new order using the sequence
INSERT INTO orders (order_id, customer_name)
VALUES (nextval('order_id_seq'), 'John Doe');
-- Step 4 (Optional): Verify the inserted order
SELECT * FROM orders;
Relevant Output:
After executing the above code, you might have an output similar to:
order_id | customer_name | order_date
----------+---------------+-------------------------
1 | John Doe | 2023-10-10 12:00:00
Explanation:
- Create Sequence: The
CREATE SEQUENCE
statement initializes a sequence namedorder_id_seq
. - Insert Statement: The
INSERT INTO orders
statement usesnextval()
to get the next available value from the sequence for theorder_id
column. - Output Verification: The final SELECT statement retrieves the data from the orders table, showing that we successfully used the sequence to generate a unique order ID.
Conclusion:
Using a sequence simplifies the assignment of unique identifiers, ensures data integrity, and allows for easier management of primary keys in a relational database. This method is efficient and reduces the likelihood of key collisions during concurrent database operations.
Total: 5 Marks.