So far, we have focused on retrieving data from existing tables using the SELECT statement. Now, we will begin exploring Data Manipulation Language (DML), starting with how to add new data to your tables using the INSERT INTO statement.
There are two primary ways to use the INSERT INTO statement.
This is the safest and most common method. You explicitly list the columns you want to fill, followed by the values for those columns.
INSERT INTO table_name (column1, column2, column3)
VALUES (value1, value2, value3);
If you are providing values for all columns in the table in the exact order they were defined, you can omit the column names. However, this is less flexible and can lead to errors if the table structure changes.
INSERT INTO table_name
VALUES (value1, value2, value3, ...);
WHERE clause, string (text) and date values must be enclosed in single quotes (').NULL and you don't provide a value for it, it will be filled with NULL (or a default value if one is defined).Let's add a new actor to the actor table in the Sakila database.
INSERT INTO actor (first_name, last_name)
VALUES ('JOHNNY', 'DEPP');
Note: We didn't specify the actor_id because it is usually auto-generated by the database.
If we have a table with many columns but only want to fill a few:
INSERT INTO customer (first_name, last_name, email, store_id, address_id)
VALUES ('ALICE', 'JOHNSON', 'alice.j@example.com', 1, 5);
Most modern databases allow you to insert multiple rows in a single statement by separating the sets of values with commas.
INSERT INTO actor (first_name, last_name)
VALUES
('TOM', 'HANKS'),
('MERYL', 'STREEP'),
('LEONARDO', 'DICAPRIO');
Key Takeaways from this Lesson:
INSERT INTO statement is used to add new rows to a table.In the next lesson, we will learn how to Create Tables from scratch and define their structure.