Search code examples
mysqlsqlcsvsql-insertload-data-infile

MySQL: Importing csv into table with quotation marks


I have a csv where each row starts with quotation marks and ends with them too. How do I ignore the quotations at the start and end of the row when loading the csv into a table?

LOAD DATA LOCAL INFILE '/path/data.csv' 
INTO TABLE test1 
FIELDS TERMINATED BY ';' 
LINES TERMINATED BY '\"\n'
IGNORE 1 ROWS;

I have tried

OPTIONALLY ENCLOSED BY '"'

but this refers to each specific field and not the entire row.


Solution

  • As commented by Shadow and Barmar, the answer lies in the documentation :

    If all the input lines have a common prefix that you want to ignore, you can use LINES STARTING BY 'prefix_string' to skip the prefix and anything before it. If a line does not include the prefix, the entire line is skipped. [...] The FIELDS TERMINATED BY, LINES STARTING BY, and LINES TERMINATED BY values can be more than one character.

    Hence, use :

    LOAD DATA LOCAL INFILE '/path/data.csv' 
    INTO TABLE test1 
        FIELDS TERMINATED BY ';' 
        LINES STARTING BY '"'
        LINES TERMINATED BY '"\n'
        IGNORE 1 ROWS;