'Is using Alter here wrong as opposed to Cast?
So I created a table with all varchar (255) then decided to use CAST to change to UNSIGNED (since all +ve values). When I checked, it has been changed to unsigned. However, I noticed when I check the whole table again the columns are still considered as varchar.
Is my understanding correct that CAST only works for the specific code and will not permanently change and if I wish to change the column type permanently, will require me to use ALTER as shown below?
If so why do people use cast instead of Alter?
CREATE table project.worldcup_players (
MatchID varchar (255),
Team_Initials varchar (255),
Coach_Name varchar (255),
Player_Name varchar (255)
);
SELECT * FROM project.worldcup_players;
SELECT CAST(MatchID AS UNSIGNED) AS MatchID FROM project.worldcup_players;
ALTER TABLE project.worldcup_players
CHANGE COLUMN `MatchID` `MatchID` INT NULL DEFAULT NULL ;
Solution 1:[1]
CAST only changes the result of an expression in the query. You could use CAST if you only want to change to an unsigned integer sometimes, without changing the way the data are stored.
ALTER TABLE is required if you want to change the way the data are stored.
Suppose your MatchID was represented by a number only for some matches. In other matches, the match is identified by an alpha string. In that case, the column must be a varchar, because the column must be stored as the same data type on all rows in a given table. Don't alter the table, because it would cause all the non-numeric strings to be changed to their numeric equivalent, 0.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Bill Karwin |
