Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 5: Inserting, Updating, and Deleting Data

Inserting data into a table

To add data to a table, use the INSERT INTO statement:

INSERT INTO users (id, username, email)
VALUES (1, 'john_doe', '[email protected]');

This inserts a new row into the users table, with 1 in the id column, 'john_doe' in the username column, and '[email protected]' in the email column.

You can also insert several rows at once:

INSERT INTO users (id, username, email)
VALUES (2, 'jane_doe', '[email protected]'),
       (3, 'bob_smith', '[email protected]');

This inserts two new rows into the users table.

Updating data in a table

To change data that’s already in a table, use the UPDATE statement:

UPDATE users
SET email = '[email protected]'
WHERE id = 1;

This updates the email column in the row where id equals 1. The new value of email is '[email protected]'.

You can update several columns at once:

UPDATE users
SET email = '[email protected]',
    username = 'new_username'
WHERE id = 1;

This updates both the email and username columns in the row where id equals 1.

Deleting data from a table

To remove data from a table, use the DELETE FROM statement:

DELETE FROM users
WHERE id = 1;

This deletes the row where id equals 1 from the users table.

You can also delete every row in a table:

DELETE FROM users;

This deletes all rows from the users table. The data is deleted permanently, so be careful with this statement and make sure you have a backup of your data before you use DELETE FROM.