How do i change the datatype of a column in mysql?

Using SQL Query:

To change the data type of a column, use MODIFY:

ALTER TABLE table_name MODIFY col_name new_type;

To rename a column, use RENAME COLUMN:

ALTER TABLE table_name RENAME COLUMN old_col_name TO new_col_name;

MODIFY can only be used to change a column definition and RENAME COLUMN can change a column’s name but not its definition. If you want to rename and change the data type of the table at the same time, use CHANGE:

ALTER TABLE table_name CHANGE old_col_name new_col_name new_type;

Using TablePlus GUI Tool:

When viewing a table, you can switch to the structure tab at the bottom of the windows, or you can use shortcut keys Cmd + Ctrl + ]

From there, you can be able to rename or change the data type of any columns simply by double-clicking on the cell.

After that, remember to hit Cmd + S to commit change to the server.

Need a good GUI Tool for MySQL? TablePlus is a modern, native tool with an elegant UI that allows you to simultaneously manage multiple databases such as MySQL, PostgreSQL, SQLite, Microsoft SQL Server and more.

Download TablePlus for Mac.

Not on Mac? Download TablePlus for Windows.

On Linux? Download TablePlus for Linux

Need a quick edit on the go? Download TablePlus for iOS.

  1. Change Column Datatype or Property in MySQL
  2. Use the ALTER TABLE CHANGE Keyword to Modify the Datatype, Constraints, or Property of a Single Column in a MySQL Database Table
  3. Use the ALTER TABLE MODIFY Keyword to Modify the Datatype, Constraints, or Property of a Single Column in a MySQL Database Table
  4. Use the ALTER TABLE Keyword to Modify the Datatype, Constraints, or Property of Multiple Columns in a MySQL Database Table

Database design is often iterative, with requirements changing and initial design re-adjusted. MySQL is a robust RDBMS that allows the modification of existing/declared table columns with the ALTER TABLE keyword.

This tutorial illustrates using the ALTER TABLE keyword for modifying the datatype, constraints, or properties of existing columns in a MySQL database.

Change Column Datatype or Property in MySQL

The ALTER TABLE keyword can combine with other keywords for achieving the necessary modification. In MySQL, the CHANGE keyword is the main extension to the standard SQL.

However, the MODIFY keyword is an available extension for the sake of compatibility with Oracle.

The CHANGE or MODIFY keywords achieve the same result, with slight trade-offs in terms of convenience of syntax and robustness. To illustrate these concepts, let us create a programming_languages database with a table named Details.

/* Here goes the definition of the database */
CREATE DATABASE programming_languages;
USE programming_languages;

-- Creating a details table
CREATE TABLE Details[
	id INT NOT NULL AUTO_INCREMENT,
    name VARCHAR[25] UNIQUE,
    year_released VARCHAR [5],
    PRIMARY KEY[id]
    ];
-- Populating Details with information
INSERT INTO Details [name, year_released] VALUES ['python', 1991],['c++', 1985],['Java', 1995];
SELECT * FROM Details ORDER BY id;

DESCRIBE Details year_released;  -- Checking the column information

Output:

id	name	year_released
1	python	1991
2	c++		1985
3	Java	1995
-----------------------------------------------------------------------------------------
Field			Type		Null	Key	Default	Extra
year_released	varchar[5]	YES			NULL

Let us modify the year_released column to implement a YEAR data type instead of a VARCHAR.

Use the ALTER TABLE CHANGE Keyword to Modify the Datatype, Constraints, or Property of a Single Column in a MySQL Database Table

The CHANGE keyword can implement three types of modifications on a column at a time.

  1. It can redefine the datatype and constraints of a column.
  2. It can rename a column.
  3. It can re-order the columns in a table with the FIRST or AFTER keywords.

Note

When using the ALTER statement, include initial column definitions and constraints to ensure they reflect in the modified column. For example, if a column had a NOT NULL constraint, it must be re-specified in the ALTER statement.

 -- changing the datatype of year_released from VARCHAR to YEAR
 ALTER TABLE Details
 CHANGE year_released year_released YEAR;

 DESCRIBE Details year_released;  -- Running again, to confirm changes

Output:

Field			Type	Null	Key	Default	Extra
year_released	year	YES			NULL

Notice how the name of the target column was included twice. This is the syntax inconvenience of using CHANGE, as it expects the name of the modified column to be specified.

We re-specify the name as year_released to keep the original column name. However, this supposed inconvenience becomes efficient when there is a requirement to modify both the property and the name of a column.

Then, such an operation can be executed in the same line.

For example, let us change the column name to year_of_release and include a NOT NULL and DEFAULT constraint.

-- Altering YET AGAIN
ALTER TABLE Details
CHANGE year_released year_of_release YEAR NOT NULL DEFAULT '1990';

DESCRIBE Details year_of_release;

Output:

Field			Type	Null	Key	Default	Extra
year_of_release	year	NO			1990

While this works, the recommended approach for changing a column name is with the RENAME COLUMN keyword. RENAME only requires the current/old name of the column and the new name.

ALTER TABLE Details
RENAME COLUMN year_of_release TO year_released;

DESCRIBE Details year_released;  -- Viewing changes

Output:

Field			Type	Null	Key	Default	Extra
year_released	year	NO			1990

For extra details on the usage of the CHANGE keyword, have a look at this official documentation.

Use the ALTER TABLE MODIFY Keyword to Modify the Datatype, Constraints, or Property of a Single Column in a MySQL Database Table

The alternative MODIFY keyword offers the same functionality as the CHANGE keyword, but it does not support the rename of a column in its expression. To rename a column, combine the MODIFY keyword with the RENAME COLUMN keyword as previously described.

This time, let us redefine the name column to accept a VARCHAR of thirty [30] characters with a NOT NULL constraint.

-- Altering with MODIFY
ALTER TABLE Details
MODIFY name VARCHAR[30] NOT NULL DEFAULT 'None';

DESCRIBE Details name;

Output:

Field	Type		Null	Key	Default	Extra
name	varchar[30]	NO		UNI	None

Notice how the UNIQUE constraint carries over to the altered column. Constraints like PRIMARY KEY or UNIQUE do not need a re-specification.

Now, let us rename the column to prog_language_name and allow NULL values by combining the MODIFY keyword with RENAME COLUMN.

ALTER TABLE Details
-- Allowing Null values by not specifying NOT NULL
MODIFY name VARCHAR[30] DEFAULT 'None';

-- Renaming the column
ALTER TABLE Details
RENAME COLUMN name TO prog_language_name;

-- Viewing the changes
DESCRIBE Details prog_language_name;

Output:

Field				Type		Null	Key	Default	Extra
prog_language_name	varchar[30]	YES		UNI	None

Use the ALTER TABLE Keyword to Modify the Datatype, Constraints, or Property of Multiple Columns in a MySQL Database Table

The methods previously illustrated are similarly applicable to multiple columns. However, the MODIFY or CHANGE statements are repeated based on the number of columns to be changed.

Further details on this are available via this reference.

Let us set a NOT NULL constraint and a default value for the year_of_release and prog_language_name columns.

ALTER TABLE Details
MODIFY prog_language_name VARCHAR[30] NOT NULL DEFAULT 'No Data',
MODIFY year_released year NOT NULL DEFAULT '1950';

DESCRIBE Details

Output:

Field				Type		Null	Key		Default		Extra
id					int			NO		PRI		NULL		auto_increment
prog_language_name	varchar[30]	NO		UNI		No Data
year_released		year		NO				1950

Related Article - MySQL Column

  • Convert Rows to Columns in MySQL
  • Find Tables in MySQL With Specific Column Names in Them
  • Calculate Average of a Table Column in MySQL
  • MySQL Check if Column Is Null or Empty
  • How do you change the datatype of a column?

    Change data types in Datasheet view.
    In the Navigation Pane, locate and double-click the table that you want to change. ... .
    Select the field [the column] that you want to change..
    On the Fields tab, in the Properties group, click the arrow in the drop-down list next to Data Type, and then select a data type..

    How do I change the existing datatype in MySQL?

    If you want to change all columns of a certain type to another type, you can generate queries using a query like this: select distinct concat['alter table ', table_name, ' modify ', column_name, ' ', if[is_nullable = 'NO', ' NOT ', ''], ' NULL;'] from information_schema.

    Can we change the datatype of a column which has data?

    We can use ALTER TABLE MODIFY COLUMN statement to change the datatype of the column. The syntax to change the datatype of the column is following. In the syntax, Tbl_name: Specify the table name that contains the column that you want to change.

    How do you change the datatype of a column in SQL without losing data?

    So to do that go to SQL Server and within Tools select Options. Now in the option window expand Designers and under that "Table and Database Designers" and uncheck the check box "Prevent saving changes that require table re-creation" then click OK.

    Bài mới nhất

    Chủ Đề