I am trying to alter column named names
type from text to VARCHAR with length L. Where L is the maximum length of the names
. I am trying with inner/sub-query as follows:
Is this even possible? Any alternative to do this in a single query?
ALTER TABLE friends
ALTER COLUMN names TYPE VARCHAR(
SELECT MAX(LENGTH(names))
FROM friends
)
I get the following error in PgAdmin4 SQL console:
ERROR: syntax error at or near "SELECT"
LINE 3: SELECT MAX(LENGTH(card_number))
2
Answers
You can use the equivalent of
VARCHAR(MAX)
on Postgres, which can be achieved by simply usingVARCHAR
alone with no size:Note that with
VARCHAR
any given string will only use storage for that string alone, with no padding (unlikeCHAR
).Or, we could use the
TEXT
type:You’ll probably be better off using
text
.Answering the question: you can’t use anything but integer constants in that context, so to achieve that "in a single query", you’ll need dynamic SQL.
fiddle