Posts Tagged ‘alter’

Foreign keys in MySQL

Tuesday, April 8th, 2008

The default engine in MySQL, MyISAM, does not support foreign keys. You need foreign keys to use the SQLAlchemy Python package effectively.

In order to use foreign keys, you need to convert your tables to the InnoDB engine:

ALTER TABLE mytable ENGINE = INNODB;

To add a foreign key to mytable where the unique keys are coming from othertable, use this:

ALTER TABLE mytable ADD FOREIGN KEY (otherID) REFERENCES othertable (otherID);

If you run that same line several times, several identical foreign keys will be created, which will confuse SQLAlchemy. In that case you need to delete the keys. To do so, you need their name. To see the name, use

SHOW CREATE TABLE mytable;

The foreign key’s label will be something that ends in something similar to fk_1 or fk_2. Using that label, you can then delete the foreign key:

ALTER TABLE mytable DROP FOREIGN KEY mytable_dbfk_2;

Add or delete columns in a table in MySQL

Monday, March 17th, 2008

Add a column to a table in the database:


ALTER TABLE table_name
ADD column_name datatype

Delete a column from a table in the database:


ALTER TABLE table_name
DROP COLUMN column_name