I need a way to create table and nextval sequence name dynamically in PostgreSQL, can this be done without brain meltdown?
My thinking goes along the lines of:
DECLARE
$tablename varchar(50) = "name_of_table";
-- Sequence and defined type
CREATE SEQUENCE IF NOT EXISTS $tablename_id_seq; <-- PROBABLY NEED SOME SORT OF CONCATENATION HERE
-- Table Definition
CREATE TABLE $tablename (
"id" int4 NOT NULL DEFAULT nextval($tablename || '_id_seq'::regclass),
... (the rest omitted)
What I'm trying to achieve: I'm building an interface where a user can type in the name of the table they'd like to create, and based on the input of that field a table of that name with matching sequence is created ...
Yes, and it's built-in. There are
smallserial
,serial
andbigserial
types that do exactly that:And there's (better) identity column syntax mentioned by @Frank Heikens above
Then, if you want the sequence, you can use
pg_get_serial_sequence()
.If you decide to keep creating these by hand, make sure to later link them to the column they are responsible for:
If you're asking about dynamic SQL syntax in general, not just sequence name dynamically generated based on table name, there are examples in the doc:
fiddle