1

I'm trying to execute this query:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.columns 
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion')
THEN ALTER TABLE MyTableName DROP COLUMN ColumnInQuestion;

And I get the following error message:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF EXISTS(SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'articles'' at line 1

I'm using MySQL 5.1.something, so I don't think information_schema not being defined is the issue. Any ideas?

Thank you for your help!

2
  • How are you trying to run the query? Commented Nov 30, 2010 at 2:02
  • @OMG Ponies: it doesn't matter how he runs it. In this query mysql tries to use DML IF in the context of DDL (at least I think so). According to the documentation - it is not possible to write such conditional DDLs. Commented Nov 30, 2010 at 2:06

2 Answers 2

2

You cannot do this. IF EXISTS is meaningful only for creating tables/databases

If you need to drop column if it exists - you could use

ALTER IGNORE TABLE DROP COLUMN ...

Note on IGNORE.

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

Comments

0

You have a couple of options.

One option is to just run the ALTER TABLE command and ignore the error if the column doesn't exist.

Another option closer in spirit to your original attempt is to conditionally dump the DDL to a SQL script on disk if the column exists, then source that SQL script to run the DDL (if any).

Here's an example:

-- delete the SQL script if it exists
\! rm /tmp/drop_column.sql

-- Conditionally dump the DDL to a SQL script if the column exists
SELECT concat('ALTER TABLE ',table_schema,'.',table_name,
' DROP COLUMN ',column_name,';') as sql_stmt
into outfile '/tmp/drop_column.sql'
FROM INFORMATION_SCHEMA.columns 
WHERE table_name = 'MyTableName' AND column_name = 'ColumnInQuestion';

-- execute the SQL script
\. /tmp/drop_column.sql

-- delete the SQL script from disk
\! rm /tmp/drop_column.sql

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.