The basic misunderstanding is that youYou seem to assume variable substitution for an SQL utility command like ALTER TABLE
, which isbut that's not implemented.
EquallyAlso not possible to pass valuespass values for utility commands to EXECUTE
with the USING
clause in plpgsql.
Detailed
Detailed explanation for both in this related answer on SO:
- Error when setting n_distinct using a plpgsql variableError when setting n_distinct using a plpgsql variable
Hence, you have to concatenateConcatenate the statement before you, then execute it - like @Abelisto already hinted. But you don't strictly needneed a variable, you can concatenate the lookup value directly:
DO $$
BEGIN
EXECUTE format('ALTER TABLE beta ALTER COLUMN aref SET DEFAULT %L'
, (SELECT a.id::text FROM alpha a));
END $$;
The SELECT
must return a single value.
I cast to text
explicitly, which is also not strictly necessary. And since it's a default value for a uuid
column, castingCasting the string literal back to the target type uuid
isn't required, either. Postgres will derive that from the column type automatically.
Related: