Exporting query results to CSV

Imagine This

You just finished sorting your toy collection — all your favorite cars in a line.

Now, you want to write them down on a piece of paper so you can:

  • Show it to a friend
  • Print it later
  • Save it to remember your collection

In the world of databases, this “paper list” is called a CSV file.

What Is a CSV?

CSV means Comma-Separated Values — it’s like a table where each row is a line, and each value is split by commas.

id,name,type
1,Red Car,Vehicle
2,Blue Car,Vehicle

Let’s Say You Have a Table

Your table is called toys, and it looks like this:

idnametype
1Red CarVehicle
2Blue CarVehicle
3DollFigure

SQL Query to Get Cars

SELECT * FROM toys WHERE type = 'Vehicle';

Output of This Query:

idnametype
1Red CarVehicle
2Blue CarVehicle

Export This to a CSV (MySQL)

SELECT * FROM toys 
WHERE type = 'Vehicle'
INTO OUTFILE '/var/lib/mysql-files/vehicles.csv'
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\n';

What This Does:

  1. Runs the same query to find cars
  2. Saves the results to a file named vehicles.csv
  3. Formats each row like this:
"1","Red Car","Vehicle"
"2","Blue Car","Vehicle"

Output in the File (vehicles.csv)

"1","Red Car","Vehicle"
"2","Blue Car","Vehicle"

You can now:

  • Open it in Excel or Google Sheets
  • Email it
  • Store it for later

What to Remember

  • A query finds the data you want
  • INTO OUTFILE tells SQL: “Save this to a file”
  • The file is a simple table made of text
  • It’s easy to read, open, and share

Leave a Comment

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

Scroll to Top