SQL Insert Into Table From Excel: Step-by-Step Guide
In this article
To insert data from Excel into a SQL table, the most efficient method is to save the Excel file as a CSV (Comma Separated Values) file and use the database's native import wizard or a BULK INSERT command. This process converts a visual spreadsheet into a structured text format that SQL engines can parse and map directly to table columns.
What You'll Need
- A Microsoft Excel file (.xlsx) containing the data you wish to upload.
- Access to a SQL database management tool (such as SQL Server Management Studio (SSMS), MySQL Workbench, or pgAdmin).
- Administrative permissions to create tables or insert data into the target database.
- A target table that already exists with a schema (column names and data types) that matches your Excel data.
Step-by-Step
- Prepare the Excel Data: Open your Excel workbook. Ensure the first row contains clear, descriptive headers that correspond to your SQL table columns. Remove any empty rows, merged cells, or complex formatting (like bolding or cell colors), as these can cause import errors. Ensure that date formats are consistent (e.g., YYYY-MM-DD) and that there are no trailing spaces in your text fields.
- Export to CSV: Go to File > Save As. In the file type dropdown menu, select CSV (Comma delimited) (*.csv). Save the file to a local directory that the SQL server can access. This step is critical because SQL servers cannot read the proprietary binary format of an .xlsx file directly; they require a plain-text representation.
-
Verify the Target Table: Open your SQL editor and ensure your destination table is ready. For example, if your Excel sheet has columns for "CustomerID", "OrderDate", and "TotalAmount", your SQL table should be defined as:
CREATE TABLE Orders (CustomerID INT, OrderDate DATE, TotalAmount DECIMAL(10,2));
Ensure the data types match. If you try to insert a text string from Excel into an INT column in SQL, the process will fail. -
Use the Import Wizard (GUI Method):
- In SSMS, right-click the database name, select Tasks > Import Data.
- In the "Choose a Data Source" window, select Flat File Source and browse to your CSV file.
- In the "Choose a Destination" window, select SQL Server Native Client and provide your server credentials.
- Map the source columns to the destination columns. The wizard usually attempts to match them by name, but you can manually adjust the mapping if the names differ.
- Click Finish to execute the import.
-
Use SQL Commands (Script Method): If you prefer coding or are automating the process, use the BULK INSERT command. Run the following script in your query window:
BULK INSERT Orders FROM 'C:\path\to\your\file.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2);
TheFIRSTROW = 2instruction tells SQL to skip the header row of your CSV file and start inserting data from the second row. -
Validate the Data: Once the process completes, run a SELECT query to verify the data was imported correctly:
SELECT TOP 100 * FROM Orders;
Check for null values in mandatory columns and ensure that dates and decimals were not truncated or shifted into the wrong columns.
Common Mistakes
One of the most frequent errors is a mismatch between the Excel data type and the SQL column data type. For instance, if a column in Excel contains a single non-numeric character (like a "N/A" or a currency symbol "$") in a column intended for a SQL DECIMAL or INT type, the entire import will fail. Always clean your data in Excel using the "Find and Replace" tool to remove symbols before exporting.
Another common mistake is failing to account for the header row. If you use a script-based import without specifying that the first row is a header, SQL will attempt to insert the words "CustomerID" or "OrderDate" into the table. This will result in a "Conversion failed when converting varchar value to int" error.
Users often forget to check for hidden characters or trailing spaces. A cell that looks like "New York" but actually contains "New York " (with a trailing space) may cause issues when you later try to join that table with another table using a WHERE clause, as the strings will not match exactly.
Finally, file permission issues are common. If you are using BULK INSERT, the SQL Server service account—not your personal Windows user account—must have read access to the folder where the CSV is stored. Placing the file in a restricted user folder often leads to an "Access Denied" error.
Tips
For very large datasets (hundreds of thousands of rows), avoid using the GUI wizard, as it can be slow and memory-intensive. The BULK INSERT command or the bcp (Bulk Copy Program) utility is significantly faster because it bypasses much of the logging overhead associated with standard INSERT statements.
If you are importing data into a table that already contains records, consider importing the Excel data into a "staging table" first. A staging table is a temporary table with no constraints or primary keys. Once the data is in the staging table, you can run a SQL script to clean the data, remove duplicates, and then move it into the production table using an INSERT INTO ... SELECT FROM statement.
To handle dates more reliably, format your Excel date columns as "YYYY-MM-DD" before exporting to CSV. This is the ISO standard and is recognized by almost every SQL dialect (SQL Server, MySQL, PostgreSQL), reducing the risk of the database misinterpreting the month and day (e.g., confusing 01/05 as January 5th vs May 1st).
If your data contains commas within the text (e.g., a column for "Address" that says "123 Main St, Apt 4"), a standard CSV will break because the comma is the delimiter. In this case, save your Excel file as a "CSV (UTF-8)" and ensure that text qualifiers (double quotes) are enabled, or use a Tab-Separated Values (.txt) file instead, changing your FIELDTERMINATOR to \t.
Troubleshooting
If the import fails, the first step is to check the error log. SQL usually provides a specific row number where the failure occurred. Navigate to that row in your CSV file to see if there is a formatting anomaly, such as a stray comma or an unexpectedly long string that exceeds the defined VARCHAR limit of the column.
If you encounter a "Data truncation" error, it means the data in your Excel cell is longer than the character limit defined in your SQL table. For example, if your column is VARCHAR(50) but your Excel cell contains 60 characters, the import will stop. To fix this, either shorten the data in Excel or increase the column size in SQL using ALTER TABLE TableName ALTER COLUMN ColumnName VARCHAR(100);
If the data imports but appears shifted (e.g., the phone number is in the email column), check your delimiter. This usually happens when the data itself contains the delimiter character. Switch from a comma-delimited CSV to a tab-delimited file to resolve this.
If you receive a "Permission Denied" error during a BULK INSERT, move the CSV file to a public folder (like C:\Temp) and grant "Everyone" read permissions to that folder. This ensures the SQL Server service account can reach the file regardless of the user currently logged into the machine.
Frequently Asked Questions
Can I import directly from .xlsx without converting to CSV?
Yes, but it requires specific drivers. In SQL Server, you can use the "SQL Server Import and Export Wizard" and select "Microsoft Excel" as the data source. This uses OLEDB providers to read the file directly, though it is often more prone to driver-version conflicts than the CSV method.
How do I handle duplicate rows during the import?
The best approach is to import the data into a temporary staging table. Once there, you can use a DISTINCT query or a ROW_NUMBER() function to identify and delete duplicates before moving the clean data into your final production table.
What happens if my Excel file has more columns than my SQL table?
If you use a GUI wizard, you can simply uncheck the columns you don't want to import. If you use BULK INSERT, the process will likely fail or misalign the data. You must either update the SQL table to match the file or delete the unnecessary columns in Excel before exporting.
Is there a way to automate this process daily?
Yes. You can write a SQL Agent Job that runs a BULK INSERT script on a schedule. Alternatively, you can use a Python script with the pandas library to read the Excel file and the sqlalchemy library to push the data to SQL.
Why are my numbers showing up as scientific notation in SQL?
This happens when Excel formats large numbers (like credit card numbers or long IDs) as scientific notation (e.g., 1.23E+10). To fix this, highlight the column in Excel, change the format to "Number" with 0 decimal places, and then re-save the CSV.