Tutorial by Examples

For example, if t1 is currently not an InnoDB table, this statement changes its storage engine to InnoDB: ALTER TABLE t1 ENGINE = InnoDB; If the table is already InnoDB, this will rebuild the table and its indexes and have an effect similar to OPTIMIZE TABLE. You may gain some disk space improv...
CREATE DATABASE stackoverflow; USE stackoverflow; Create table stack( id_user int NOT NULL, username varchar(30) NOT NULL, password varchar(30) NOT NULL ); ALTER TABLE stack ADD COLUMN submit date NOT NULL; -- add new column ALTER TABLE stack DROP COLUMN submit; -- drop col...
To improve performance one might want to add indexes to columns ALTER TABLE TABLE_NAME ADD INDEX `index_name` (`column_name`) altering to add composite (multiple column) indexes ALTER TABLE TABLE_NAME ADD INDEX `index_name` (`col1`,`col2`)
Changing an auto-increment value is useful when you don't want a gap in an AUTO_INCREMENT column after a massive deletion. For example, you got a lot of unwanted (advertisement) rows posted in your table, you deleted them, and you want to fix the gap in auto-increment values. Assume the MAX value o...
ALTER TABLE fish_data.fish DROP PRIMARY KEY; ALTER TABLE fish_data.fish MODIFY COLUMN fish_id DECIMAL(20,0) NOT NULL PRIMARY KEY; An attempt to modify the type of this column without first dropping the primary key would result in an error.
The change the definition of a db column, the query below can be used for example, if we have this db schema users ( firstname varchar(20), lastname varchar(20), age char(2) ) To change the type of age column from char to int, we use the query below: ALTER TABLE users CHANGE age...
There is no single command to rename a MySQL database but a simple workaround can be used to achieve this by backing up and restoring: mysqladmin -uroot -p<password> create <new name> mysqldump -uroot -p<password> --routines <old name> | mysql -uroot -pmypassword <new na...
The following commands can be used to swap the names of two MySQL databases (<db1> and <db2>): mysqladmin -uroot -p<password> create swaptemp mysqldump -uroot -p<password> --routines <db1> | mysql -uroot -p<password> swaptemp mysqladmin -uroot -p<password&gt...
Renaming a table can be done in a single command: RENAME TABLE `<old name>` TO `<new name>`; The following syntax does exactly the same: ALTER TABLE `<old name>` RENAME TO `<new name>`; If renaming a temporary table, the ALTER TABLE version of the syntax must be used....
Renaming a column can be done in a single statement but as well as the new name, the "column definition" (i.e. its data type and other optional properties such as nullability, auto incrementing etc.) must also be specified. ALTER TABLE `<table name>` CHANGE `<old name>` `<n...

Page 1 of 1