SQL ALTER COLUMN Keyword
ALTER COLUMN
The ALTER COLUMN
command is used to change the data type of a column in a table.
Note: SQLite (used in our playground) does not support the
ALTER COLUMN
syntax directly. To change a column’s data type, you must recreate the table.
SQL ALTER COLUMN Syntax (Not supported in SQLite)
SQL
x
1
ALTER TABLE table_name
2
ALTER COLUMN column_name datatype;
SQL ALTER Example (Not supported in our playground)
The following SQL changes the data type of the column named BirthDate
in the Employees
table to type YEAR
:
SQL
1
1
ALTER TABLE Employees
2
ALTER COLUMN BirthDate YEAR;
Alternative Method
To change a column’s data type in SQLite, use the following approach:
SQL
1
20
1
-- Step 1: Create new table with modified column type
2
CREATE TABLE Patients_new (
3
patient_id INTEGER PRIMARY KEY,
4
first_name VARCHAR(50),
5
last_name VARCHAR(50),
6
dob TEXT, -- Changed data type from DATE to TEXT (example)
7
gender CHAR(1),
8
contact_number VARCHAR(15)
9
);
10
11
-- Step 2: Copy data from old table
12
INSERT INTO Patients_new
13
SELECT * FROM Patients;
14
15
-- Step 3: Drop old table
16
DROP TABLE Patients;
17
18
-- Step 4: Rename new table
19
ALTER TABLE Patients_new RENAME TO Patients;
20
This method allows you to effectively alter a column’s data type in our playground environment using SQLite-compatible SQL.