Tag Archives: add column

Adding, modifying or dropping a column in a table, the Magento way

This will be really simple. Just create a new install / upgrade script and write the following code into it:

$this->startSetup();
$this->getConnection()->addColumn($this->getTable('your_table_definition'), 'your column name', "column definition");
//example: $this->getConnection()->addColumn($this->getTable('catalog/product'), 'something', "INT(11) COMMENT 'this will create a column named something in catalog_product_entity table'");

$this->endSetup();

So, as you have already seen it, no more ALTER TABLEs.

The same is the situation with changing columns. Here are a couple of useful function declarations (for addColumn, changeColumn, modifyColumn, dropColumn):

    public function addColumn($tableName, $columnName, $definition, $schemaName = null)
    public function changeColumn($tableName, $oldColumnName, $newColumnName, $definition, $flushData = false, $schemaName = null)
    public function modifyColumn($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
    public function dropColumn($tableName, $columnName, $schemaName = null)

The difference between the changeColumn and modifyColumn is that changeColumn modifies also the name of the column and of course the definition also (it uses ALTER TABLE %s CHANGE COLUMN %s %s %s), while modifyColumn changes only the definition (it uses ALTER TABLE %s MODIFY COLUMN %s %s).