简体   繁体   中英

PostgreSQL Custom Sequencing

Is there a built-in method in PostgreSQL or a custom method I can use to create a custom sequence column?

Example: AAA-2022-0001 
         AAA-2022-0002
         BAC-2022-0001
         ABC-2022-0001
         BAC-2022-0002
         AAA-2022-0003

Sequencing on PostgreSQL is performed by creating a Sequence. If when we use serial by creating a table then DB automatically created one sequence for this table. After then sets to default value of the id field this: nextval('table_id_seq'::regclass) . nextval is a PostgreSQL function that are increase sequence values and update. Because for sequencing we must create sequence using this table. But, we need a primary key in a custom format. And for this, we can create our own function that returns a formatted primary key value and we can set this function to default value of the id field. Please see to examples of our SQL queries:

-- creating our sequence 
CREATE SEQUENCE tbl_status_idx_seq
    INCREMENT BY 1
    MINVALUE 1
    MAXVALUE 2147483647
    START 1
    CACHE 1
    NO CYCLE;


-- create function that will be returned unique id value in custom format 
CREATE OR REPLACE FUNCTION get_nextval()
 RETURNS text
 LANGUAGE plpgsql
 IMMUTABLE
AS $function$
declare 
    p_val int4; 
    v_ret text;
begin
    
    p_val = nextval('tbl_status_idx_seq'::regclass); 
    v_ret = 'AAA-' || extract(year from now())::text || '-' || lpad(p_val::text, 6, '0');
    
    return v_ret;  
  
end;
$function$;


-- creating our table for testing and use our function on the default value of id field. 
CREATE TABLE tbl_status (
    "id" text NOT NULL DEFAULT get_nextval(),
    "timestamp" timestamp NULL,
    state text NULL,
    CONSTRAINT tbl_status_pk PRIMARY KEY (id)
);



-- inserting sample data for testing and viewing our id value 
INSERT INTO tbl_status ("timestamp", "state") 
VALUES('2022-01-15 00:00:00.000', 'online');

INSERT INTO tbl_status ("timestamp", "state") 
VALUES('2022-02-03 00:00:00.000', 'deactivated');

INSERT INTO tbl_status ("timestamp", "state") 
VALUES('2022-03-20 00:00:00.000', 'disconnected');


-- and selecting table 
select * from tbl_status;


-- Result: 

id                      timestamp                       state
-----------------------------------------------------------------------
 AAA-2022-000003         2022-01-15 00:00:00.000         online
 AAA-2022-000004         2022-02-03 00:00:00.000         deactivated
 AAA-2022-000005         2022-03-20 00:00:00.000         disconnected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM