How to Insert Data Into Table Using Select Query
In this article
Inserting data into a table using a SELECT query copies existing data from one or more tables and adds it to another table in a single operation. This is useful for backing up records, migrating data between environments, or enriching a target table with related information from source tables. You must have write permissions on the target table and read permissions on the source table(s). The target table must already exist and have a compatible structure with the SELECT result set.
What You'll Need
- Access to a SQL database (such as PostgreSQL, MySQL, SQL Server, or SQLite)
- Permissions to INSERT into the target table and SELECT from the source table(s)
- A working SQL client or command-line interface (like psql, mysql, SQL Server Management Studio, or DBeaver)
- Knowledge of the column names, data types, and structure of both source and target tables
Step-by-Step
- Connect to your database using your preferred SQL client or terminal. Ensure you are connected to the correct database instance and schema (if applicable).
- Verify the structure of the source table by running a simple SELECT query like:
SELECT * FROM source_table LIMIT 1;This confirms the column names and data types you’ll be copying. - Check the structure of the target table using:
DESCRIBE target_table;(MySQL) or(PostgreSQL). Ensure that the target table has columns matching the SELECT result in number, order, and compatible data types. If columns are in different order, you must explicitly name them in the INSERT statement. - Write your INSERT INTO ... SELECT statement. The basic syntax is:
INSERT INTO target_table (col1, col2, col3) SELECT col1, col2, col3 FROM source_table WHERE condition;Always list the target columns explicitly to avoid mismatches due to schema changes. - Test your SELECT portion first. Run just the SELECT part of your query (without INSERT) to confirm it returns the expected rows and data. Check for nulls, unexpected types, or duplicates.
- Once the SELECT returns correct results, prepend it with INSERT INTO ... and execute the full statement.
- After execution, verify the data was inserted by running:
SELECT COUNT(*) FROM target_table;Compare this count to the number of rows returned by your SELECT query to ensure all rows were copied. - If you're copying from multiple tables, use JOINs in your SELECT clause. For example:
INSERT INTO target_table (name, email, department) SELECT s.name, s.email, d.name FROM students s JOIN departments d ON s.dept_id = d.id; - Use transactions for safety. Wrap your INSERT INTO ... SELECT in a BEGIN; ... COMMIT; block (PostgreSQL/SQL Server) or START TRANSACTION; ... COMMIT; (MySQL). This allows you to roll back if something goes wrong.
Common Mistakes
- Assuming column order matches between source and target tables — always list columns explicitly to avoid insertion errors.
- Trying to insert into a table that doesn’t exist — ensure the target table is created before running the INSERT statement.
- Ignoring data type mismatches — for example, inserting a string into an INTEGER column or a DATE into a TIMESTAMP without conversion.
- Forgetting WHERE conditions — unintentionally copying all rows instead of a filtered subset, which can bloat the target table.
- Using INSERT INTO table SELECT without parentheses around the column list — syntax errors occur in some databases if you omit the column specification.
- Not accounting for auto-increment or identity columns — if the target table has an auto-increment primary key, exclude it from the column list so the database generates it automatically.
Tips
- Always use a transaction when inserting large datasets — it allows you to rollback if there’s an error without partial data corruption.
- Use LIMIT in your SELECT during testing to preview a small subset before running the full insert.
- Include explicit column aliases in your SELECT if you’re performing calculations or using functions (e.g.,
SELECT UPPER(name) AS name) to ensure the target column names match. - For very large data sets, consider batching inserts using LIMIT and OFFSET, or using a temporary staging table to reduce lock duration.
- Use database-specific tools like pg_dump and pg_restore (PostgreSQL) or mysqldump (MySQL) for full table exports instead of SELECT inserts if you’re migrating entire tables.
- Log the number of affected rows if your client supports it — some tools show this after execution, helping you validate success.
Troubleshooting
- If you get a "column count doesn't match value count" error, check that the number of columns in your INSERT list matches the number of fields returned by your SELECT. Use column names explicitly.
- If you see "cannot insert NULL into column X", verify the source data for that column is not NULL, or add a COALESCE or IFNULL clause (e.g.,
COALESCE(email, 'n/a')) to provide defaults. - If the query runs but no rows are inserted, check your WHERE clause — it may be filtering out all results. Test the SELECT alone with the same condition.
- If you receive a permission denied error, confirm your user account has INSERT privileges on the target table and SELECT on the source. Contact your DBA if needed.
- If the database hangs or times out during a large insert, break the operation into smaller chunks using LIMIT and OFFSET, or use a temporary table and then copy in batches.
- If the target table has triggers, constraints, or foreign keys, these may block insertion. Disable them temporarily if you’re certain the data is valid — but re-enable them immediately after.
Frequently Asked Questions
Can I insert data into a table using SELECT from another database?
Yes, if your database system supports cross-database queries (like SQL Server with linked servers or PostgreSQL with dblink). Otherwise, export the data first, then import it into the target database.
Do I need to drop and recreate the target table before inserting?
No. INSERT INTO ... SELECT appends data to existing rows. If you want to replace all data, use TRUNCATE target_table; first, then run your INSERT.
Can I use INSERT INTO ... SELECT to copy data between different database systems?
No. This only works within the same database instance. To transfer between different systems (e.g., MySQL to PostgreSQL), use export/import tools like CSV, JSON, or database migration utilities.
What happens if the SELECT returns duplicate rows?
The duplicates are inserted as-is. Use DISTINCT in your SELECT to remove duplicates before insertion: INSERT INTO target SELECT DISTINCT col1, col2 FROM source;
Can I insert data using SELECT and static values together?
Yes. You can mix static values with SELECT columns. Example: INSERT INTO users (name, email, created_by) SELECT name, email, 'system' FROM temp_users;
Is INSERT INTO ... SELECT faster than using multiple INSERT statements?
Yes — it is significantly faster because the database processes all rows in a single operation, reducing overhead from individual transaction logs and network round-trips.