Load CSV/Excel into SQL (LOAD DATA, COPY)

Imagine This

You have a notebook filled with names, phone numbers, and salaries. That’s your CSV or Excel file — it has all the information written down in rows and columns.

Now you want to put all that data into a smart system — your SQL database — so you can search it, sort it, and use it for reports or applications.

But your database doesn’t understand Excel or paper. It understands commands. So you give it a special instruction to load that file into a table.

Think of a Table as a Shelf

Your database has a shelf called employees. It has spots labeled:

  • ID
  • Name
  • Email
  • Salary

Now, you receive a file called employees.csv that looks like this:

id,name,email,salary
1,John Doe,john@example.com,50000
2,Jane Smith,jane@example.com,60000

You want to put all of this on the shelf in one go — not by typing each row manually.

MySQL: Load the File

LOAD DATA INFILE '/path/to/employees.csv'
INTO TABLE employees
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

This command tells SQL: “Here is a file. Each piece of data is separated by a comma. The first line is just labels. Please fill in the employees table using this.”

PostgreSQL: Use COPY

COPY employees FROM '/path/to/employees.csv'
DELIMITER ','
CSV HEADER;

This tells PostgreSQL: “Copy the data from this CSV file into the employees table. The first row has column names.”

What Happens Behind the Scenes

  1. The database opens your file
  2. It reads each line, splits it by commas
  3. Each row is added to the table

What If the File Is in Excel?

SQL doesn’t read Excel files directly, so you just:

  1. Open the Excel file
  2. Click “Save As”
  3. Choose CSV (Comma Delimited) format
  4. Then use the same SQL commands above

Make Sure the Table Is Ready

Before importing, make sure your table already exists. For example:

CREATE TABLE employees (
  id INT,
  name VARCHAR(100),
  email VARCHAR(100),
  salary DECIMAL(10,2)
);

Summary

You’re taking data from a file — like a list in a notebook — and telling the database exactly where to put it. Once it’s loaded, you can search, sort, filter, or analyze that data easily.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top