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:
id | name | type |
---|---|---|
1 | Red Car | Vehicle |
2 | Blue Car | Vehicle |
3 | Doll | Figure |
SQL Query to Get Cars
SELECT * FROM toys WHERE type = 'Vehicle';
Output of This Query:
id | name | type |
---|---|---|
1 | Red Car | Vehicle |
2 | Blue Car | Vehicle |
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:
- Runs the same query to find cars
- Saves the results to a file named
vehicles.csv
- 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