How to Import Data From a CSV File in MySQL?
Last Updated :
23 Jul, 2025
Importing data from a CSV (Comma-Separated Values) file into a MySQL database is a common task for data migration and loading purposes. CSV files are widely used for storing and exchanging tabular data. However, we cannot run SQL queries on such CSV data so we must convert it to structured tables.
In this article, we will learn about many methods to import a CSV file in MySQL with the help of implementation and so on.
How to Import CSV Files in MySQL?
We will use the below three methods to import any CSV file into MySQL.
- Import CSV into MySQL Using Command Line
- Import CSV into MySQL Using PhpMyAdmin
- Import CSV into MySQL using Workbench
Using these methods, you can efficiently import all the data from a CSV file into a MySQL table, allowing you to use MySQL queries to manipulate and analyze the data.
Importing data significantly saves time and effort by eliminating the need for manual data entry, ensuring accuracy, and streamlining your workflow.
1. Import CSV into MySQL Using the Command Line
Follow the given steps, to import data from a CSV file into MySQL tables using the MySQL command line.
Step 1: Open the terminal window and log in to the MySQL Client using the password. Refer to the following command:
mysql -u root -p
Step 2: Create a database and then create a table inside that database. The .CSV file data will be the input data for this table:
#To create a database
CREATE DATABASE database_name;
#To use that database
use database_name;
#To create a table
CREATE TABLE table_name(
id INTEGER,
col_1 VARCHAR(100),
col_2 INTEGER,
col_3 DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
We create a database and a table called table_name inside it. The table contains various attributes such as id, col_1, col_2, and col_3. The col_3 attribute is of the DATETIME type, and it contains both data and time in the format YYYY-MM-DD hh:mm:ss. In addition to the integer and varchar attributes, we'll look at how to import a DateTime type attribute from a CSV file into a MySQL table.
Step 3: Now we must examine the MySQL variable "secure_file_priv". By default, the MySQL server starts with the -secure-file-priv option. When using LOAD DATA INFILE, it specifies the directory from which data files can be loaded into a given database instance. To view the configured directory, use the following command:
SHOW VARIABLES LIKE 'secure_file_priv';
Output:
Output For Steps 1, 2 and 3The variable "secure_file_priv" will be set to a file directory configured by the MySQL server. We now have two options for making the LOAD DATA INFILE command work properly:
- Move the input .csv file into the specified folder structure.
- To change the configured folder structure to our needs.
We'll go over both of these approaches.
Approach 1:
In this approach, we will need to put the input CSV file into the specified folder structure, and then only we will be able to access the file to be loaded into the database. Once we do this, now we are ready to run the command to import the CSV files to the database. Refer to the following command:
LOAD DATA INFILE '{folder_structure}/{csv_file_name}'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
- LOAD DATA INFILE - It specifies the location of the input CSV file.
- INTO TABLE - It specifies the table into which data is to be populated.
- FIELDS TERMINATED BY - It specifies the delimiter through which the individual values in the file are separated.
- ENCLOSED BY - It specifies the symbol which specifies the values in the CSV file.
- LINES TERMINATED BY - It specifies the code for a line break.
- IGNORE 1 ROWS - It specifies the number of lines to be ignored from an input CSV file which might contain column labels, etc.
Output:
Output For LOAD DATA INFILE CommandApproach 2:
In this approach, we will change the configured folder structure to our needs.
For Windows:
Step 1: The existing folder structure in my.ini must be changed. Go to This PC -> C Drive -> ProgramData -> MySQL -> MySQL Server * -> my.ini [The ProgramData folder is hidden. To see the folder, go to View in the top menubar and enable Hidden items.]
Step 2: Open the file and search for “secure-file-priv”. It will look something like this.
# Secure File Priv.
secure-file-priv=”C:/ProgramData/MySQL
/MySQL Server 5.7/Uploads”
Step 3: Change the folder structure as per your choice and save the file in a different location, as the file cannot be saved at the same location. Now, copy and paste the file into its actual location. To do so, we need administrator access.
Step 4: Now, press “Ctrl + R” -> Type “services.msc” -> Press “Enter”. This will open the Services tab.
Step 5: Search for MySQL57 [The number 57 may vary on your PC]. Right-click on it and then click on the restart button.
Step 6: Log in to the MySQL Command Line client and run the following command:
LOAD DATA LOCAL INFILE '{file_location}'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Following the steps outlined above, we can import a CSV file to a MySQL table in Windows OS without encountering any errors.
For Linux:
Step 1: We need to add the new folder structure of our choice in my.cnf file. The file is located in /etc/mysql/ folder. Open my.cnf file using the editor of your choice and add the following lines to the file:
[mysqld]
secure-file-priv={new_folder_structure}
Step 2: Save the file after making the changes and restart the MySQL service. Refer to the following command for that:
sudo systemctl restart mysql
Step 3: Log in to the MySQL client again using the following command:
mysql -u root -p --local-infile
Step 4: Once you log in, run the following command:
set global local_infile = 1;
SHOW VARIABLES LIKE 'local_infile';
Output:
Step 5: Now, we are set to import the CSV file data to the MySQL table. Refer to the following command:
LOAD DATA LOCAL INFILE '{file_location}'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;
Output:
Following the steps outlined above, we can import a CSV file to a MySQL table in Linux OS without encountering any errors.
The following command can be used to determine whether or not the dob attribute with timestamp type has been properly imported. In this way, we can ensure that the attribute in the table corresponds to the actual DateTime datatype of MySQL:
SELECT * FROM table_name WHERE col_3
= TIMESTAMP('{YYYY-MM-DD HH:MM:SS}');
Validation Of DATETIME AttributeOptional Step: Transforming Data while Importing
When you want to load data from a file into a MySQL table, you might notice that the incoming datatime format does not exactly match the target table. As an example, consider the col_3 timestamp format in the items.
If the target table format is "yyyy/mm/dd %H:%i:%s.%f" and the csv file format is "dd/mm/yyyy %H:%i:%s.%f". The SET clause in the LOAD DATA INFILE statement can be used to convert the CSV file datetime format to the one used by the destination table in MySQL. While performing the operation to load data from file to table in MySQL, you can use the SET clause in the end along with the str to date() function. Refer to the following command:
LOAD DATA INFILE '{file_location}'
INTO TABLE table_name
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(id, col_1, col_2, @col_3)
SET col_3 = timestamp(str_to_date(@col_3,'%d-%m-%Y %H:%i:%s.%f'));
Transforming Data while Importing2. Import CSV into MySQL Using phpMyAdmin
phpMyAdmin is a free PHP-based software tool designed to handle MySQL administration over the Internet.
Let's look at how we can use PhpMyAdmin to import a CSV file into a MySQL database.
Step 1: When you launch PhpMyAdmin, you will see various databases and tables on the left side of the interface. Create a table into which you want to import the CSV file data. The columns and datatypes must match the corresponding data in the CSV file.
Step 2: Select the table and then click on the import button from the top side menu bar.
Import Button To Input CSV FileStep 3: Click the "choose file" button and navigate to your local storage to find the input CSV file. On the same page, you can also specify the number of lines to skip in the file.
Select Input CSV FileStep 4: Scroll down the page to choose the file format, which is csv in our case. Similarly to the command line approach, we have several Format-specific options here. When we're finished, click the "Go" button.
Format And Format-specific Options For Input CSV FileStep 5:The CSV file gets imported into the MySQL table. When the import is successful, we see the following messages.
Successful Import of CSV File Into MySQL TableStep 6: We can now return to the table and examine the data imported from the CSV file.
MySQL Table Imported With Input CSV Data3. Import CSV into MySQL Using MySQL Workbench
MySQL Workbench is a visual database design tool that combines SQL development, administration, database design, creation, and maintenance for the MySQL database system into a single integrated development environment.
Let's look at how we can use MySQL Workbench to import a CSV file into a MySQL database.
Step 1: When you launch MySQL Workbench, you will see various databases and tables on the left side of the interface. Create a table into which you want to import the CSV file data. The columns and datatypes must match the corresponding data in the CSV file.
Create a TableStep 2: Right-click on the table and select the option of “Table Data Import Wizard”. Browse your local storage to select the input CSV file.
Table Data Import WizardStep 3: Select the file encoding and match the source and destination columns to configure the import settings. When you're finished, click the next button.
Select the file encodingStep 4: The input CSV file data will then be imported into the MySQL table. We can then check the imported data on the MySQL workbench interface.
CSV Data ImportedConclusion
Overall, this article provided three methods to import CSV files into MySQL such as using the Command Line, phpMyAdmin, and MySQL Workbench. By leveraging these tools, you can efficiently import data from CSV files into MySQL, saving time and ensuring accuracy.
Similar Reads
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Mainly used to manage data. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. Widely supported across various database syst
8 min read
Basics
What is SQL?Structured Query Language (SQL) is the standard language used to interact with relational databases. Allows users to store, retrieve, update, and manage data efficiently through simple commands. Known for its user-friendly syntax and powerful capabilities, SQL is widely used across industries.How Do
6 min read
SQL Data TypesSQL data types define the kind of data a column can store, dictating how the database manages and interacts with the data. Each data type in SQL specifies a set of allowed values, as well as the operations that can be performed on the values.SQL data types are broadly categorized into several groups
4 min read
SQL OperatorsSQL operators are symbols or keywords used to perform operations on data in SQL queries. These operations can include mathematical calculations, data comparisons, logical manipulations, other data-processing tasks. Operators help in filtering, calculating, and updating data in databases, making them
5 min read
SQL Commands | DDL, DQL, DML, DCL and TCL CommandsSQL commands are the fundamental building blocks for communicating with a database management system (DBMS). It is used to interact with the database with some operations. It is also used to perform specific tasks, functions, and queries of data. SQL can perform various tasks like creating a table,
7 min read
SQL Database OperationsSQL databases or relational databases are widely used for storing, managing and organizing structured data in a tabular format. These databases store data in tables consisting of rows and columns. SQL is the standard programming language used to interact with these databases. It enables users to cre
3 min read
SQL CREATE TABLEIn SQL, creating a table is one of the most essential tasks for structuring your database. The CREATE TABLE statement defines the structure of the database table, specifying column names, data types, and constraints such as PRIMARY KEY, NOT NULL, and CHECK. Mastering this statement is fundamental to
5 min read
Queries & Operations
SQL SELECT QueryThe SQL SELECT query is one of the most frequently used commands to retrieve data from a database. It allows users to access and extract specific records based on defined conditions, making it an essential tool for data management and analysis. In this article, we will learn about SQL SELECT stateme
4 min read
SQL INSERT INTO StatementThe SQL INSERT INTO statement is one of the most essential commands for adding new data into a database table. Whether you are working with customer records, product details or user information, understanding and mastering this command is important for effective database management. How SQL INSERT I
6 min read
SQL UPDATE StatementIn SQL, the UPDATE statement is used to modify existing records in a table. Whether you are updating a single record or multiple records at once, SQL provides the necessary functionality to make these changes. Whether you are working with a small dataset or handling large-scale databases, the UPDATE
6 min read
SQL DELETE StatementThe SQL DELETE statement is an essential command in SQL used to remove one or more rows from a database table. Unlike the DROP statement, which removes the entire table, the DELETE statement removes data (rows) from the table retaining only the table structure, constraints, and schema. Whether you n
4 min read
SQL | WHERE ClauseThe SQL WHERE clause allows filtering of records in queries. Whether you are retrieving data, updating records, or deleting entries from a database, the WHERE clause plays an important role in defining which rows will be affected by the query. Without WHERE clause, SQL queries would return all rows
4 min read
SQL | AliasesIn SQL, aliases are temporary names assigned to columns or tables for the duration of a query. They make the query more readable, especially when dealing with complex queries or large datasets. Aliases help simplify long column names, improve query clarity, and are particularly useful in queries inv
4 min read
SQL Joins & Functions
SQL Joins (Inner, Left, Right and Full Join)SQL joins are fundamental tools for combining data from multiple tables in relational databases. For example, consider two tables where one table (say Student) has student information with id as a key and other table (say Marks) has information about marks of every student id. Now to display the mar
4 min read
SQL CROSS JOINIn SQL, the CROSS JOIN is a unique join operation that returns the Cartesian product of two or more tables. This means it matches each row from the left table with every row from the right table, resulting in a combination of all possible pairs of records. In this article, we will learn the CROSS JO
3 min read
SQL | Date Functions (Set-1)SQL Date Functions are essential for managing and manipulating date and time values in SQL databases. They provide tools to perform operations such as calculating date differences, retrieving current dates and times and formatting dates. From tracking sales trends to calculating project deadlines, w
5 min read
SQL | String functionsSQL String Functions are powerful tools that allow us to manipulate, format, and extract specific parts of text data in our database. These functions are essential for tasks like cleaning up data, comparing strings, and combining text fields. Whether we're working with names, addresses, or any form
7 min read
Data Constraints & Aggregate Functions
SQL NOT NULL ConstraintIn SQL, constraints are used to enforce rules on data, ensuring the accuracy, consistency, and integrity of the data stored in a database. One of the most commonly used constraints is the NOT NULL constraint, which ensures that a column cannot have NULL values. This is important for maintaining data
3 min read
SQL PRIMARY KEY ConstraintThe PRIMARY KEY constraint in SQL is one of the most important constraints used to ensure data integrity in a database table. A primary key uniquely identifies each record in a table, preventing duplicate or NULL values in the specified column(s). Understanding how to properly implement and use the
5 min read
SQL Count() FunctionIn the world of SQL, data analysis often requires us to get counts of rows or unique values. The COUNT() function is a powerful tool that helps us perform this task. Whether we are counting all rows in a table, counting rows based on a specific condition, or even counting unique values, the COUNT()
7 min read
SQL SUM() FunctionThe SUM() function in SQL is one of the most commonly used aggregate functions. It allows us to calculate the total sum of a numeric column, making it essential for reporting and data analysis tasks. Whether we're working with sales data, financial figures, or any other numeric information, the SUM(
5 min read
SQL MAX() FunctionThe MAX() function in SQL is a powerful aggregate function used to retrieve the maximum (highest) value from a specified column in a table. It is commonly employed for analyzing data to identify the largest numeric value, the latest date, or other maximum values in various datasets. The MAX() functi
4 min read
AVG() Function in SQLSQL is an RDBMS system in which SQL functions become very essential to provide us with primary data insights. One of the most important functions is called AVG() and is particularly useful for the calculation of averages within datasets. In this, we will learn about the AVG() function, and its synta
4 min read
Advanced SQL Topics
SQL SubqueryA subquery in SQL is a query nested within another SQL query. It allows you to perform complex filtering, aggregation, and data manipulation by using the result of one query inside another. Subqueries are often found in the WHERE, HAVING, or FROM clauses and are supported in SELECT, INSERT, UPDATE,
5 min read
Window Functions in SQLSQL window functions are essential for advanced data analysis and database management. It is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data and they are particularly useful
6 min read
SQL Stored ProceduresStored procedures are precompiled SQL statements that are stored in the database and can be executed as a single unit. SQL Stored Procedures are a powerful feature in database management systems (DBMS) that allow developers to encapsulate SQL code and business logic. When executed, they can accept i
7 min read
SQL TriggersA trigger is a stored procedure in adatabase that automatically invokes whenever a special event in the database occurs. By using SQL triggers, developers can automate tasks, ensure data consistency, and keep accurate records of database activities. For example, a trigger can be invoked when a row i
7 min read
SQL Performance TuningSQL performance tuning is an essential aspect of database management that helps improve the efficiency of SQL queries and ensures that database systems run smoothly. Properly tuned queries execute faster, reducing response times and minimizing the load on the serverIn this article, we'll discuss var
8 min read
SQL TRANSACTIONSSQL transactions are essential for ensuring data integrity and consistency in relational databases. Transactions allow for a group of SQL operations to be executed as a single unit, ensuring that either all the operations succeed or none of them do. Transactions allow us to group SQL operations into
8 min read
Database Design & Security
Introduction of ER ModelThe Entity-Relationship Model (ER Model) is a conceptual model for designing a databases. This model represents the logical structure of a database, including entities, their attributes and relationships between them. Entity: An objects that is stored as data such as Student, Course or Company.Attri
10 min read
Introduction to Database NormalizationNormalization is an important process in database design that helps improve the database's efficiency, consistency, and accuracy. It makes it easier to manage and maintain the data and ensures that the database is adaptable to changing business needs.Database normalization is the process of organizi
6 min read
SQL InjectionSQL Injection is a security flaw in web applications where attackers insert harmful SQL code through user inputs. This can allow them to access sensitive data, change database contents or even take control of the system. It's important to know about SQL Injection to keep web applications secure.In t
7 min read
SQL Data EncryptionIn todayâs digital era, data security is more critical than ever, especially for organizations storing the personal details of their customers in their database. SQL Data Encryption aims to safeguard unauthorized access to data, ensuring that even if a breach occurs, the information remains unreadab
5 min read
SQL BackupIn SQL Server, a backup, or data backup is a copy of computer data that is created and stored in a different location so that it can be used to recover the original in the event of a data loss. To create a full database backup, the below methods could be used : 1. Using the SQL Server Management Stu
4 min read
What is Object-Relational Mapping (ORM) in DBMS?Object-relational mapping (ORM) is a key concept in the field of Database Management Systems (DBMS), addressing the bridge between the object-oriented programming approach and relational databases. ORM is critical in data interaction simplification, code optimization, and smooth blending of applicat
7 min read