TExcelTAD
Home › PostgreSQL › PostgreSQL ADD, ALTER & DROP COLUMN

PostgreSQL ADD, ALTER & DROP COLUMN

Tables evolve. A shop that started without phone numbers suddenly needs them; a column called price must allow bigger values. ALTER TABLE changes the structure of an existing table without losing its data. This lesson covers the three column operations you need most.

ADD COLUMN

Add a phone column to customers. Existing rows get NULL, because there is nothing else to put there:

pgsql · try it yourself
ALTER TABLE customers ADD COLUMN phone text;

SELECT id, first_name, phone FROM customers WHERE id <= 3;
ALTER TABLE
 id | first_name | phone
----+------------+-------
  1 | Anna       |
  2 | Ben        |
  3 | Chloé      |
(3 rows)

If you give the new column a DEFAULT, existing rows get that value instead. This is also how you add a NOT NULL column to a table that already has rows:

pgsql · try it yourself
ALTER TABLE books ADD COLUMN on_sale boolean NOT NULL DEFAULT false;
UPDATE books SET on_sale = true WHERE stock > 20;

SELECT title, stock, on_sale FROM books WHERE stock > 12 ORDER BY stock DESC;
ALTER TABLE
UPDATE 2
       title        | stock | on_sale
--------------------+-------+---------
 Ten Tiny Dragons   |    30 | t
 Moon Socks         |    25 | t
 Murder at Low Tide |    20 | f
 Clockwork Garden   |    15 | f
 The Map Thief      |    14 | f
(5 rows)

ALTER COLUMN

ALTER COLUMN changes a column's type, default or nullability. Each change is its own sub-command:

Command Effect
ALTER COLUMN c TYPE new_type convert the stored values to a new type
ALTER COLUMN c SET DEFAULT value / DROP DEFAULT change the default
ALTER COLUMN c SET NOT NULL / DROP NOT NULL require a value, or allow NULL again
RENAME COLUMN old TO new rename a column

Changing a type works when every stored value can be converted. When the automatic conversion isn't enough, a USING expression says how to compute the new value:

pgsql · try it yourself
CREATE TABLE stock_counts (book_id integer, counted text);
INSERT INTO stock_counts VALUES (1, '12'), (2, '0'), (3, '7');

ALTER TABLE stock_counts ALTER COLUMN counted TYPE integer;
ALTER TABLE stock_counts ALTER COLUMN counted TYPE integer USING counted::integer;

SELECT book_id, counted + 1 AS next FROM stock_counts;
CREATE TABLE
INSERT 0 3
ERROR:  column "counted" cannot be cast automatically to type integer
HINT:  You might need to specify "USING counted::integer".
ALTER TABLE
 book_id | next
---------+------
       1 |   13
       2 |    1
       3 |    8
(3 rows)

The first attempt fails with a helpful HINT; the second succeeds. Making a column NOT NULL fails while any row still has a NULL in it:

pgsql · try it yourself
ALTER TABLE customers ALTER COLUMN email SET NOT NULL;

UPDATE customers SET email = lower(first_name) || '@example.org' WHERE email IS NULL;
ALTER TABLE customers ALTER COLUMN email SET NOT NULL;
ALTER TABLE customers RENAME COLUMN email TO email_address;

SELECT first_name, email_address FROM customers WHERE id IN (3, 7, 13);
ERROR:  column "email" of relation "customers" contains null values
UPDATE 3
ALTER TABLE
ALTER TABLE
 first_name |   email_address
------------+-------------------
 Chloé      | chloé@example.org
 Gina       | gina@example.org
 Mia        | mia@example.org
(3 rows)

DROP COLUMN

DROP COLUMN removes a column and all its data. Use IF EXISTS to avoid an error when the column might already be gone:

pgsql · try it yourself
ALTER TABLE authors DROP COLUMN birth_year;
ALTER TABLE authors DROP COLUMN IF EXISTS birth_year;

SELECT * FROM authors WHERE id <= 3;
ALTER TABLE
NOTICE:  column "birth_year" of relation "authors" does not exist, skipping
ALTER TABLE
 id |      name      | country
----+----------------+---------
  1 | Maria Okafor   | Nigeria
  2 | Lars Henriksen | Norway
  3 | Aiko Tanaka    | Japan
(3 rows)

Note: If other objects depend on a column, such as a view or a foreign key, PostgreSQL refuses to drop it. DROP COLUMN … CASCADE drops those dependent objects too, so use it carefully.

Several changes at once

One ALTER TABLE can contain several comma-separated actions; they are applied together:

pgsql · try it yourself
CREATE TABLE gift_cards (code text);
ALTER TABLE gift_cards
    ADD COLUMN amount numeric(6,2) NOT NULL DEFAULT 25,
    ADD COLUMN issued date,
    ALTER COLUMN code SET NOT NULL;

SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_name = 'gift_cards'
ORDER BY ordinal_position;
CREATE TABLE
ALTER TABLE
 column_name | data_type | is_nullable | column_default
-------------+-----------+-------------+----------------
 code        | text      | NO          |
 amount      | numeric   | NO          | 25
 issued      | date      | YES         |
(3 rows)

Test yourself

You add a column phone text to a table with 15 rows. What do the existing rows contain?

  1. An empty string
  2. NULL
  3. The text 'phone'
  4. The statement fails

Which clause tells ALTER COLUMN … TYPE how to convert each old value?

  1. WITH
  2. CAST
  3. USING
  4. AS

Why might ALTER COLUMN email SET NOT NULL fail?

  1. Email columns can't be NOT NULL
  2. Some rows still contain NULL in that column
  3. You must drop the column first
  4. It needs a DEFAULT