Keys and Sequences

Back

Loading concept...

🎰 The Magical Ticket Machine: Sequences & Auto-Increment

Imagine a bakery with a special ticket dispenser. Every customer pulls a ticket with a unique number—1, 2, 3, 4… The machine never gives the same number twice, and it always remembers the last number it gave out. This is exactly how sequences work in databases!


🎫 What is a Sequence?

A sequence is like that ticket machine at the bakery. It’s a special counter that:

  • Starts at a number you choose (usually 1)
  • Goes up by a fixed amount each time (usually +1)
  • Never forgets the last number it gave
  • Never repeats a number
graph TD A["🎰 Sequence Created"] --> B["Start Value: 1"] B --> C["Customer 1 asks → Gets 1"] C --> D["Customer 2 asks → Gets 2"] D --> E["Customer 3 asks → Gets 3"] E --> F["...and so on forever!"]

Real Example: Creating a Sequence

CREATE SEQUENCE order_number
START WITH 1
INCREMENT BY 1;

What this does:

  • Creates a ticket machine named order_number
  • First ticket will be 1
  • Each new ticket adds 1 to the previous

🔧 Managing Sequences: Your Control Panel

Just like a real ticket machine has buttons and settings, sequences have special commands to manage them!

Getting the Next Number

When you need a new unique number:

SELECT NEXTVAL('order_number');
-- First call: Returns 1
-- Second call: Returns 2
-- Third call: Returns 3

Think of NEXTVAL as pressing the button on the ticket machine. Each press gives you the next number!

Peeking at the Current Number

Want to see what number was given last WITHOUT getting a new one?

SELECT CURRVAL('order_number');
-- Shows the last number given

This is like looking at the display on the ticket machine without pressing the button.

Resetting the Sequence

Sometimes you need to start fresh (like January 1st for yearly order numbers):

ALTER SEQUENCE order_number
RESTART WITH 1;

This resets the machine back to 1!

Changing the Step Size

What if you want tickets to go 10, 20, 30 instead of 1, 2, 3?

ALTER SEQUENCE order_number
INCREMENT BY 10;

Now each button press adds 10 instead of 1!

Deleting a Sequence

Don’t need the ticket machine anymore?

DROP SEQUENCE order_number;

Goodbye, ticket machine! 👋


🚀 Auto-Increment: The Lazy Person’s Best Friend

Auto-increment is like having a robot assistant that automatically pulls a ticket for every new customer. You don’t even need to think about it!

The Magic Setup

CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100)
);

SERIAL is the magic word that says: “Hey database, please give each new row its own unique number automatically!”

Watch the Magic Happen

INSERT INTO customers (name)
VALUES ('Alice');
-- Alice gets id = 1 automatically!

INSERT INTO customers (name)
VALUES ('Bob');
-- Bob gets id = 2 automatically!

INSERT INTO customers (name)
VALUES ('Charlie');
-- Charlie gets id = 3 automatically!
graph TD A["INSERT Alice"] --> B["🤖 Auto-assigns id=1"] C["INSERT Bob"] --> D["🤖 Auto-assigns id=2"] E["INSERT Charlie"] --> F["🤖 Auto-assigns id=3"]

You never typed a number, but each customer got a unique ID!


🎯 Different Flavors of Auto-Increment

SMALLSERIAL (The Mini Counter)

  • Counts from 1 to 32,767
  • Perfect for small lists
CREATE TABLE colors (
    id SMALLSERIAL PRIMARY KEY,
    name VARCHAR(50)
);

SERIAL (The Regular Counter)

  • Counts from 1 to 2,147,483,647
  • Good for most things
CREATE TABLE products (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100)
);

BIGSERIAL (The Giant Counter)

  • Counts to 9 quintillion+
  • For apps with LOTS of data
CREATE TABLE clicks (
    id BIGSERIAL PRIMARY KEY,
    timestamp TIMESTAMP
);

🧩 Why Are Sequences So Important?

1. Every Row Gets a Unique Address

Like houses on a street need different numbers, every row in a table needs a unique identifier!

2. No More Guessing

Without auto-increment:

-- ❌ You'd have to figure out
-- what number comes next!
INSERT INTO users (id, name)
VALUES (???, 'Dan');

With auto-increment:

-- ✅ Just add the data!
INSERT INTO users (name)
VALUES ('Dan');
-- Database handles the number!

3. Safe Even When Busy

What if 100 people sign up at the exact same moment? The sequence guarantees each person gets a different number. No duplicates ever!


🎪 The Full Picture

graph TD A["🎰 SEQUENCE"] --> B["Manual Control"] A --> C["Flexible Settings"] D["🤖 AUTO-INCREMENT"] --> E["Automatic"] D --> F["Uses Sequence Behind Scenes"] B --> G["NEXTVAL - Get Next"] B --> H["CURRVAL - Check Current"] B --> I["RESTART - Reset"] E --> J["SERIAL"] E --> K["BIGSERIAL"] E --> L["SMALLSERIAL"]

💡 Quick Tips to Remember

Task Command
Create sequence CREATE SEQUENCE name
Get next number NEXTVAL('name')
See current CURRVAL('name')
Reset ALTER ... RESTART
Delete DROP SEQUENCE name
Auto-ID column Use SERIAL type

🎉 You Did It!

You now understand:

Sequences = Programmable ticket machines ✅ NEXTVAL = Press the button for next number ✅ CURRVAL = Peek at the display ✅ Auto-increment = Robot that pulls tickets for you ✅ SERIAL = The magic word for auto-numbering

Next time you see id SERIAL PRIMARY KEY, you’ll know there’s a tiny ticket machine working hard behind the scenes! 🎰✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.