Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop column if it exists in PostgreSQL 9+?

Tags:

sql

postgresql

I am trying to drop a column from a table. How can I check if the column exists or not?

I went through the documentation at https://www.postgresql.org/docs/9.2/static/sql-altertable.html, but didn't find any example how to do it.

Even found How to check if a column exists in a SQL Server table?, but it does not seem relevant.

like image 402
user3521432 Avatar asked Nov 07 '16 19:11

user3521432


People also ask

How do I drop a column if exists?

The syntax goes like this: ALTER TABLE table_name DROP COLUMN column_name; Some RDBMSs accept an optional IF EXISTS argument which means that it won't return an error if the column doesn't exist.

How do I delete a specific column in PostgreSQL?

The syntax to drop a column in a table in PostgreSQL (using the ALTER TABLE statement) is: ALTER TABLE table_name DROP COLUMN column_name; table_name. The name of the table to modify.

How do I drop a specific column in a table?

Right-click the column you want to delete and choose Delete Column from the shortcut menu. If the column participates in a relationship (FOREIGN KEY or PRIMARY KEY), a message prompts you to confirm the deletion of the selected columns and their relationships. Choose Yes.

How do I select a specific column in PostgreSQL?

PostgreSQL SELECT statement syntax If you specify a list of columns, you need to place a comma ( , ) between two columns to separate them. If you want to select data from all the columns of the table, you can use an asterisk ( * ) shorthand instead of specifying all the column names.


1 Answers

You just need to add IF EXIST to your DROP COLUMN statement:

ALTER TABLE tableName DROP COLUMN IF EXISTS columnName; 
like image 102
user3521432 Avatar answered Sep 23 '22 03:09

user3521432