Home >Database >Mysql Tutorial >How to Insert Rows into a Specific Column in a MySQL Table?

How to Insert Rows into a Specific Column in a MySQL Table?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-04 14:51:011032browse

How to Insert Rows into a Specific Column in a MySQL Table?

Inserting Rows in a Specific Column

Consider this scenario: you have a MySQL table named table1 with columns key_col, col_a, and col_b. You want to add rows to the table, but only in the col_a column, leaving col_b unchanged.

However, simply attempting an INSERT statement like this is incorrect:

INSERT INTO table1 AS t1 (key_col, col_a) VALUES ("k1", "foo"), ("k2", "bar");

Using UPDATE for Targeted Insertions

To achieve your desired result, you must use the UPDATE statement instead of INSERT.

UPDATE Syntax:

UPDATE <table_name> SET <column_name> = <value> WHERE <condition>;

Example:

To insert "k1" and "foo" into the table while leaving col_b unchanged, use these statements:

UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';

This approach ensures that existing data in col_b remains intact while updating col_a with the desired values.

The above is the detailed content of How to Insert Rows into a Specific Column in a MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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