Example Codes for Adding a Column if Not Exists in PostgreSQL (pre-9.4)
- Using Information Schema:
This approach involves checking if the column already exists in the table and then adding it only if it's missing. Here's how it works:
- Use
INFORMATION_SCHEMA.COLUMNS
to query for existing columns in the table. - Check if the desired column name exists in the results.
- If the column doesn't exist, use
ALTER TABLE
with theADD COLUMN
clause to add it with the desired data type.
- Using exception handling (for PostgreSQL 9.3 and above):
This method leverages exception handling within PostgreSQL to attempt adding the column and catch the error if it already exists. Here's a breakdown:
- Wrap the
ALTER TABLE
statement withDO $$
andBEGIN
andEND
blocks. - Inside the block, try adding the column using
ALTER TABLE
. - Use
EXCEPTION
to handle the error that occurs if the column already exists. - Within the
EXCEPTION
block, you can optionally raise a notice informing you that the column already exists.
Both methods achieve the same result: adding a column only if it's not present in the table. The first approach is more explicit, while the second approach with exception handling (available in Postgres 9.3 and later) can be more concise.
Here are some additional points to consider:
- PostgreSQL versions 9.4 and later directly support
IF NOT EXISTS
with theALTER TABLE
statement, making it simpler to add a column conditionally. - Remember to adjust the data type and column name in the examples to match your specific requirements.
Example Codes for Adding a Column if Not Exists in PostgreSQL (pre-9.4)
-- Check if the column 'email' already exists in 'users' table
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'users'
AND column_name = 'email';
-- If the query returns no rows, the column doesn't exist, so add it
IF (SELECT count(*) FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'email') = 0
THEN
ALTER TABLE users ADD COLUMN email VARCHAR(255);
END IF;
DO $$
BEGIN
ALTER TABLE users ADD COLUMN phone_number INTEGER;
EXCEPTION WHEN duplicate_column THEN
-- Handle the error if the column already exists (optional)
RAISE NOTICE 'Column phone_number already exists.';
END;
$$;
Note:
- Replace
users
with your actual table name. - Adjust
email
(example 1) andphone_number
(example 2) with your desired column names and data types.
These examples demonstrate how to conditionally add columns in PostgreSQL versions before 9.4. For versions 9.4 and later, you can use a simpler approach:
ALTER TABLE users ADD COLUMN IF NOT EXISTS new_column_name data_type;
This method involves creating a temporary table with the desired structure including the new column. Then, you can copy data from the original table to the temporary table and finally drop the original table and rename the temporary table.
Here's a basic example:
-- Define the new column structure
CREATE TEMP TABLE tmp_users AS
SELECT *, new_column_name data_type -- Adjust data type
FROM users;
-- Drop the original table
DROP TABLE users;
-- Rename the temporary table to the original name
ALTER TABLE tmp_users RENAME TO users;
Note: This method can be less efficient for large tables due to the data copying involved.
Using a User-Defined Function (UDF):
This approach involves writing a UDF that checks for the column's existence and then adds it if necessary. However, this method is generally considered more complex and less common compared to the other methods.
Here's a very simplified example (caution, implementing a robust UDF requires more code):
CREATE OR REPLACE FUNCTION add_column_if_not_exists(table_name TEXT, column_name TEXT, data_type TEXT) RETURNS VOID AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = $1 AND column_name = $2) THEN
ALTER TABLE $1 ADD COLUMN $2 $3;
END IF;
END;
$$ LANGUAGE plpgsql;
-- Usage example
SELECT add_column_if_not_exists('users', 'new_column_name', 'INTEGER');
Remember:
- These alternative methods might be less straightforward compared to the information schema or exception handling approaches.
- Choose the method that best suits your specific needs and skill level.
postgresql postgresql-9.1