So I created a table with all varchar(255) and then decided to use CAST to change it to UNSIGNED (since all values are positive). When I checked, it had been changed to unsigned. However, I noticed that when I checked the entire table again, the columns were still treated as varchar.
My understanding is that CAST only works on specific code and will not change permanently. If I want to permanently change the column type, do I need to use ALTER as shown below?
If that's the case, 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 ;
CAST only changes the result of the expression in the query. If you just want to change it to an unsigned integer sometimes, without changing how the data is stored, you can use CAST.
If you want to change the way data is stored, you need to use ALTER TABLE.
Assume your MatchID is represented as a number only for certain matches. In other competitions, competitions are identified by alphabetical strings. In this case, the columns must be varchar because columns must be stored with the same data type on all rows in a given table. Do not modify the table as this will cause all non-numeric strings to be changed to their numeric equivalent of 0.