How to Export Query Results to CSV in SQL Server

In this short guide, I’ll show you 2 methods to export query results to CSV in SQL Server Management Studio:

  1. The quick method for smaller number of records
  2. The complete method for larger datasets

I’ll also demonstrate how to include the column headers when exporting your results.

Method 1: The quick method to export query results to CSV in SQL Server

To start, run your query in order to get the query results.

For example, I ran a simple query, and got the following table with a small number of records:

Table

To quickly export the query results, select all the records in your table (e.g., by picking any cell on the grid, and then using the keyboard combination of Ctrl + A):

Select all records in a table

After selecting all your records, right-click on any cell on the grid, and then select ‘Copy with Headers‘ (or simply select ‘Copy’ if you don’t want to include the headers):

How to Export Query Results to CSV in SQL Server

Open a blank CSV file, and then paste the results:

Records in CSV file

The above method can be useful for smaller number of records. However, if you’re dealing with much larger datasets, you may consider to use the second method below.

Method 2: Export query results for larger datasets

Using the same example, you can export the query results to a CSV file by right-clicking on any cell on the grid, and then selecting ‘Save Results As…

How to Export Query Results to CSV in SQL Server

Next, type a name for your CSV file (for example, ‘query_results’), and then click on Save:

Save Grid Results

Your CSV file will be saved at the location that you specified:

Export Query Results to CSV in SQL Server

And if you open the CSV file, you’ll see the exported results (without the column headers):

CSV FIle

You may follow the steps below in case you need to include the column headers when exporting your CSV file in SQL Server.

How to include the column headers when exporting query results to CSV in SQL Server

In order to include your column headers, go to Tools, and then select Options…

Options menu

Then, click on Query Results >> SQL Server >> Results to Grid:

How to Export Query Results to CSV in SQL Server

Check the option to ‘Include column headers when copying or saving the results‘ and then click on OK:

Export Query Results to CSV in SQL Server

You’ll now need to restart SQL Server in order for the changes to be applied.

Then, rerun your query to get the query results:

Example of a table

Right-click on any cell on the grid itself, and then select ‘Save Results As…

How to Export Query Results to CSV in SQL Server Management Studio

Type a name for your CSV file, and then press on Save:

Query results

Your new CSV would now contain the column headers going forward:

Column headers