Search code examples
mysqlif-statementpopsql

MySQL IF (SELECT) in order to change a Column value


I am first creating a table in which I have 6 headers/columns, then I add a column in there and set a default value for that new column. The part I'm trying to modify is that new column which I set. I have some places where the default value would change - based on a different column that is purely form that data I imported.

My code is as follows:

SET GLOBAL local_infile=1;
CREATE TABLE audio(
    File_Name CHAR(4) PRIMARY KEY,
    File_Subdirectory CHAR(50),
    ....,
    ....,
    ....,
    ....,
);

-- Created table with the headers described above (left out 4 column names)

LOAD DATA LOCAL INFILE 'audio.csv'
     INTO TABLE audio
     FIELDS TERMINATED BY ',';

-- Loaded data into the right columns, even when I check with SELECT * FROM audio looks good

ALTER TABLE audio ADD COLUMN Microphone VARCHAR(15) DEFAULT 'Forward' AFTER File_Directory

-- Successful added a column after File_Directory with header Microphone and default was Forward for all entries/rows. 

IF (SELECT File_Directory FROM audio WHERE File_Driectory = 'Home')
    SET Microphone = 'Not Forward'
END IF;

-- Here I want to change the Microphone column (3rd column now - previously added and set default to be 'forward') to be 'Not Forward' if the File_Directory column has variable/entry to be home.

Also, if I do the following I get the entries which I am looking for and which I would like to change that third column. It prints out the column with multiple rows that have 'Home' written as the entry. These rows are the ones I'd like to change that new column I added, I want to change it from default 'forward' to 'not forward'.

SELECT File_Directory FROM audio WHERE File_Driectory = 'Home'

My problem is with the last statement since I am not able to SET or change the entry to that third column... it's not that I can't, I am not sure what I am doing wrong with the IF statement. I hope the code I provided is enough to give me a quick solution. I left out the other 4 column names since they are not relevant nor do I do anything in them. Again I load data from a csv, successfully add a column with a header/and default field (which is the majority), I just need to change the few places that new column needs to have a different name/entry.

Any suggestions would be helpful! Thank you!


Solution

  • I was able to solve this easily without even using an IF statement. I used the UPDATE command.

    UPDATE audio SET Microphone = 'Not forward' WHERE File_Directory = 'Home'