w3resource

How to Modify a Column's Data Type in SQL


Modify a Column's Data Type

Write a SQL query to change the data type of an existing column in a table.

Solution:

-- Change the data type of the "Salary" column to INTEGER.
ALTER TABLE Employees -- Specify the table to modify.
MODIFY Salary INT; -- Modify the data type of the "Salary" column to INTEGER.

Explanation:

    1. Purpose of the Query :

    1. The goal is to alter the Salary column in the Employees table by changing its data type from DECIMAL(10, 2) to INTEGER.
    2. This demonstrates how to use the ALTER TABLE statement to modify the structure of an existing table.

    2. Key Components :

    1. ALTER TABLE Employees : Specifies the table where the modification will occur.
    2. MODIFY Salary INT : Changes the data type of the Salary column to INTEGER.

    3. Why use MODIFY? :

    1. The MODIFY clause allows you to change the definition of an existing column without dropping or recreating the table.
    2. This is useful when you need to adapt the table to new requirements, such as simplifying calculations or optimizing storage.

    4. Real-World Application :

    1. For example, if salaries are no longer required to include fractional values (e.g., cents), you can switch the Salary column from DECIMAL to INTEGER to store whole numbers only.

Additional Notes:

  • Modifying column data types is part of maintaining and adapting database schemas over time.
  • Potential risks when modifying data types, such as:
    • Data Loss : Converting DECIMAL to INTEGER truncates fractional parts, which may lead to unintended data loss.
    • Application Errors : Queries or application logic that depend on the original data type may fail or behave incorrectly after the change.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: How to add a new Column to an Existing SQL Table.
Next SQL Exercise: How to Drop a Column from an SQL Table.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.