2

I need to run this MySql code on some databases and I suspect that some of them to have already this column. Is there anything similar to if not exists for the below code?

ALTER TABLE 
    `comments` 
ADD COLUMN 
    `active` int(1) NOT NULL DEFAULT '0' AFTER `sid`

I'm considering this to prevent getting the duplicated column error.

2
  • you have more than one table with the same table name (in a single DB) ? Commented Oct 17, 2010 at 15:24
  • no just i want to know if there is any option to exclude those sites that has an active column actually to prevent getting duplicated column error ! Commented Oct 17, 2010 at 15:27

3 Answers 3

2
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tbl_name'
AND table_schema = 'db_name'
AND column_name = 'column_name'

should give you what you are looking for!!

Sign up to request clarification or add additional context in comments.

Comments

1

It's not built-in, but it can be accomplished using the information_schema database:

http://www.cryer.co.uk/brian/mysql/howto_add_column_unless_exists.htm

Comments

1

Or: SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'tbl_name' AND table_schema = 'db_name' AND column_name = 'column_name'

This gives you a 1 or 0 result based on existence or not.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.