Changing the data type of a column
Thankfully, changing column data types is not an everyday task, but when we need to do it, we must know all the details so that we can perform the conversion on a production system without any errors.
Getting ready
Let's start with a simple example of a table, as follows:
postgres=# select * from birthday;
This gives the following output:
name | dob -------+-------- simon | 690926 (1 row)
The preceding table was created using this command:
CREATE TABLE birthday ( name TEXT , dob INTEGER);
How to do it…
Let's say we want to change the dob
column to another data type. Let's try with a simple example first, as follows:
postgres=# ALTER TABLE birthday postgres-# ALTER COLUMN dob SET DATA TYPE text; ALTER TABLE
This works fine. Let's just change that back to the integer
type so that we can try something more complex, such as a date
data type:
postgres=# ALTER TABLE birthday postgres-# ALTER COLUMN dob SET DATA TYPE integer; ERROR: column ...