T-SQL Tutorial

SQL insert into table where


To insert rows into a SQL Server database as a result of a SQL query with a WHERE condition, you can use the INSERT INTO SELECT statement. This statement allows you to select data from one or more tables and insert it into a new or existing table.


Example

Here is an example of how to use INSERT INTO SELECT to insert rows into a table based on a WHERE condition:

INSERT INTO new_table (column1, column2, column3)
SELECT old_table.column1, old_table.column2, old_table.column3
FROM old_table
WHERE old_table.column4 = 'condition_value';


In this example, the new_table is the table where you want to insert the rows. The columns you want to insert data into are specified in parentheses after the table name. In this case, column1, column2, and column3 are the columns you want to insert data into.

The SELECT statement specifies the data you want to insert. In this example, you are selecting data from the old_table. The columns you want to select data from are specified after the SELECT keyword. In this case, column1, column2, and column3 are the columns you want to select data from.

The WHERE condition specifies the criteria that must be met for a row to be selected. In this example, the WHERE condition is checking the value of column4 to ensure that it matches the specified condition_value.

When you run this SQL query, SQL Server will select the rows from the old_table that match the WHERE condition, and then insert them into the new_table.

Note that the column names and table names used in this example are just placeholders, and you should replace them with the appropriate column and table names for your own database.