PostgreSQL: How to create an alphanumeric sequence

Updated: January 5, 2024 By: Guest Contributor Post a comment

Introduction

Creating sequences in PostgreSQL usually involves numeric values, but sometimes applications require unique alphanumeric identifiers. This tutorial demonstrates methods to generate such sequences.

Understanding Sequences in PostgreSQL

Before diving into alphanumeric sequences, it’s important to grasp the concept of sequences in PostgreSQL. A sequence in PostgreSQL is a special kind of database object that generates a series of unique numbers. They are often used for creating unique identifiers for table rows.

CREATE SEQUENCE my_numeric_sequence START 1 INCREMENT BY 1;

However, when it comes to alphanumeric sequences, PostgreSQL doesn’t provide built-in support as it does for numeric sequences. So we have to employ various strategies to achieve this.

Using Function and Triggers

One way to generate an alphanumeric sequence is by combining a numeric sequence with a function that converts numbers to a base-36 numbering system (0-9 and A-Z). Here’s how it can be done:

-- Create numeric sequence
CREATE SEQUENCE my_numeric_seq START WITH 1;

-- Function to convert to base36
CREATE OR REPLACE FUNCTION to_base36(INTEGER) RETURNS TEXT AS $
DECLARE
    digits TEXT[] = ARRAY['0','1',...,'Z'];
BEGIN
    result TEXT = '';
    WHILE $1 > 0 LOOP
        result := digits[($1 % 36) + 1] || result;
        $1 := $1 / 36;
    END LOOP;
    RETURN result;
END;
$ LANGUAGE plpgsql;

You can then use this function to get a new alphanumeric string:

-- Get the next alphanumeric sequence
SELECT 'prefix-' || to_base36(nextval('my_numeric_seq'));

If this sequence generating logic is needed frequently, it’s often beneficial to use a database trigger that automatically generates and assigns the alphanumeric identifier whenever a new row is inserted.

Storing and Incrementing Alphanumeric Sequences Directly

In scenarios where you need more control or complexity in the sequence, storing the last used identifier and incrementing it via a custom function can be a good option. This is a more advanced and flexible method but requires manual handling of the sequence.

-- Store last sequence value in a table
CREATE TABLE my_sequence_values (
    last_value VARCHAR(10) NOT NULL
);

-- Function to get the next alphanumeric sequence
CREATE OR REPLACE FUNCTION get_next_alphanumeric() RETURNS TEXT AS $
DECLARE ...
BEGIN ...
    -- Perform the increment and base-36 conversion logic
    RETURN new_alphanumeric_value;
END;
$ LANGUAGE plpgsql;

Using this function, you can retrieve and increment your alphanumeric sequence inside your application or database logic.

Importance of Indexing

No matter which method you choose, it’s crucial to index your alphanumeric identifiers properly, especially if you intend to use them as keys. The performance of your database could degrade significantly otherwise. Always ensure proper indexing strategies according to your unique sequence pattern and data access patterns.

Final Words

In this tutorial, we’ve explored several techniques for generating alphanumeric sequences in PostgreSQL—from simple adaptations of numeric sequences to more advanced storage and incrementing methods. Depending on your application’s requirements, choose the method that offers the right balance between simplicity and flexibility. Happy coding and sequence generation!