Inserting rows with INSERT #
Every command we have written so far only reads data. The INSERT statement is how we add a brand new row to a table:
INSERT INTO table_name (column_1, column_2, column_3)
VALUES
(value_1, value_2, value_3);
table_name: The table to add a row to.(column_1, column_2, column_3): The columns you are providing values for.VALUES (value_1, value_2, value_3): The values to insert, in the same order as the column list. Text values need quotes, numbers do not.
You can insert more than one row at a time by separating each group of values with a comma:
INSERT INTO table_name (column_1, column_2)
VALUES
(value_1, value_2),
(value_3, value_4);
If you leave a column out of the column list, it is set to NULL (or a default value, if the table was set up with one). You will learn how to set up default values later in this course.
Exercise #
We have already created a table products with the columns id, name, category, and price. Write a command that inserts a new product into products:
id:9name:Desk Chaircategory:Officeprice:85.00
Tests #
- The
productstable has exactly one more row than before. - A row exists with
nameDesk Chair,categoryOffice, andprice85.00.
Solution
INSERT INTO products (id, name, category, price)
VALUES
(9, 'Desk Chair', 'Office', 85.00);
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity