Sub topic 2
Changing a column's type
This chapter assumes you know basic SELECT, INSERT, UPDATE and DELETE statements, CREATE TABLE with common data types, and primary and foreign keys. Examples use PostgreSQL unless noted. Run them on a test database first.
Changing a column's type
Use ALTER TABLE with a column clause to change a column's data type. The syntax differs by database:
-- PostgreSQL
ALTER TABLE customers ALTER COLUMN name TYPE VARCHAR(200);
-- MySQL
ALTER TABLE customers MODIFY COLUMN name VARCHAR(200) NOT NULL;
-- SQL Server
ALTER TABLE customers ALTER COLUMN name VARCHAR(200) NOT NULL;Renaming columns and tables
PostgreSQL, MySQL 8, Oracle and SQLite 3.25 or later rename a column like this:
ALTER TABLE customers RENAME COLUMN name TO full_name;
ALTER TABLE customers RENAME TO clients;SQL Server uses the sprename procedure instead: `EXEC sprename 'customers.name', 'full_name', 'COLUMN';`. Renaming does not update application code or views that use the old name.
Adding and dropping constraints
This example assumes an orders table with a customer_id column:
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id);
ALTER TABLE orders DROP CONSTRAINT fk_orders_customer;MySQL versions before 8.0.19 use DROP FOREIGN KEY fk_orders_customer. Name every constraint when you create it. An unnamed constraint gets a generated name that you must look up before you can drop it.
Removing a table with DROP TABLE
DROP TABLE deletes the table, its rows and its structure. A foreign key from another table blocks the drop:
DROP TABLE customers; -- fails while orders references customers
DROP TABLE customers CASCADE; -- in PostgreSQL, drops the foreign key in orders, but not the orders tableMaking scripts re-runnable with IF EXISTS
DROP TABLE IF EXISTS orders;Without IF EXISTS, running the script a second time fails because the table is already gone. IF EXISTS suppresses that error. It does not prevent data loss, so confirm which database you are connected to before you run it.
Exercise
Why must MySQL's MODIFY COLUMN restate NOT NULL when you only want to change the type?
Show answer
MODIFY COLUMN replaces the whole column definition. Any clause you leave out, including NOT NULL, is removed, so the column becomes nullable.