Adding New Data with INSERT

Putting new rows into a table

7 min read

Everything so far has only read data with SELECT. At some point though, your website needs to add something brand new: a new user signing up, a new blog post being published, a new order being placed. That is the job of INSERT.

INSERT INTO users (username, email) VALUES ('ana', 'ana@example.com');

Read this as: "into the users table, in the username and email columns, insert these values: ana, and ana@example.com." The column list and the value list must line up in the same order, the first value fills the first column you listed, the second value fills the second column, and so on.

Text needs quotes, numbers do not

Just like in a WHERE clause, text values are wrapped in quotes, while numbers are written plainly:

INSERT INTO products (name, price) VALUES ('coffee mug', 12.99);

What about the id column?

You may notice that many tables have an id column, yet the examples above never mention it. That is because databases can automatically generate a new id for every row you insert, so you do not have to think it up yourself. You will learn exactly how that works in the upcoming lesson on primary keys.

Inserting more than one row at once

You can also insert several rows in a single statement, which saves you from repeating INSERT INTO over and over:

INSERT INTO users (username, email) VALUES
  ('ana', 'ana@example.com'),
  ('ben', 'ben@example.com');

A real world moment

Picture someone filling out a sign up form on your Gwecode website and pressing submit. Behind the scenes, your website takes what they typed and runs an INSERT statement exactly like the ones above, which is how their account actually comes into existence inside your database.

Double check that your column names are spelled exactly right and that you have exactly one value for every column you listed. A mismatched column list is one of the most common beginner mistakes with INSERT.

Quick check

Q1 Which statement correctly inserts a new product named 'coffee mug' priced at 12.99?

Q2 In INSERT INTO users (username, email) VALUES ('ana', 'ana@example.com');, why is 'ana' wrapped in quotes but a price like 12.99 would not be?

Want to save your progress? It's free.

Create a free account