Home > Database > Mysql Tutorial > How to Insert Data with Selective Column Selection in SQL's INSERT INTO ... SELECT Statement?

How to Insert Data with Selective Column Selection in SQL's INSERT INTO ... SELECT Statement?

DDD
Release: 2025-01-18 20:15:10
Original
998 people have browsed it

How to Insert Data with Selective Column Selection in SQL's INSERT INTO ... SELECT Statement?

SQL's INSERT INTO ... SELECT: Targeted Data Insertion

SQL's powerful INSERT INTO ... SELECT statement lets you populate a table with data from a query's results. This is ideal for efficiently copying or transferring data between tables.

Let's examine a typical query:

<code class="language-sql">INSERT INTO courses (name, location, gid) 
SELECT name, location, gid 
FROM courses 
WHERE cid = $cid</code>
Copy after login

This copies entire rows. However, you often need to insert only specific columns, or assign custom values to certain fields.

Selective Column Insertion and Constant Values

To insert chosen columns and set a column like 'gid' to a fixed value, adjust the query like this:

<code class="language-sql">INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = $cid</code>
Copy after login

Here, 'gid' is assigned the constant '1'. Remember to use a constant compatible with the 'gid' column's data type.

Important: The number of columns in the SELECT statement must match the number of columns listed in the INSERT statement.

The above is the detailed content of How to Insert Data with Selective Column Selection in SQL's INSERT INTO ... SELECT Statement?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template