Creating Databases and Tables and Safely Modifying Data

Create a user table and safely insert, query, update, and delete records

🎯 Introduction

By the end of this article, you will be able to create a user table and safely insert, query, update, and delete records.


🗃 Create a database for your application

Create the practice database in the MySQL client:

CREATE DATABASE blog_demo CHARACTER SET utf8mb4;

blog_demo is the database name. utf8mb4 is a character encoding that supports Chinese text and common emoji.

Select it as the database to work with:

USE blog_demo;

Select it again after reconnecting: USE only affects the current connection. Run the examples in this article once. Later articles specify which tables they use; you do not need to keep deleting and recreating them.


🧱 Create a user table

CREATE TABLE user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(50) NOT NULL,
    age INT,
    city VARCHAR(50),
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

id is an integer primary key that identifies a record; AUTO_INCREMENT assigns an ID automatically on insertion. username allows up to 50 characters, and NOT NULL requires a value. age and city can be unknown and stored as NULL.

created_at stores the creation time and defaults to the current time when omitted. Updating the city later does not automatically change it.

Inspect the table definition:

SHOW CREATE TABLE user;

The result has one row and two columns. The second column is abbreviated below; its actual value is a complete CREATE TABLE statement:

TableCreate Table (abbreviated)
userCREATE TABLE user (id int NOT NULL AUTO_INCREMENT, …) ENGINE=InnoDB …

The ellipses represent omitted columns and table options; they are not part of the actual SQL.

The result includes the actual columns, primary key, and storage engine configuration. This lets you verify the structure the database accepted, beyond simply checking that the command ran without errors.


➕ Insert a record

INSERT INTO user (username, age, city) VALUES ('Xiao Ming', 25, 'Beijing');

The client reports one row inserted. The omitted id is generated automatically, and created_at uses its default timestamp.

Query the record you just inserted:

SELECT id, username, age, city FROM user ORDER BY id;

Following the steps in this article produces:

idusernameagecity
1Xiao Ming25Beijing

In the newly created empty table, this produces a record with id 1 and username Xiao Ming. Listing columns explicitly prevents accidentally returning sensitive columns, such as a password, if they are added later.


📥 Insert multiple records at once

To import a small batch of users, provide multiple sets of values in one INSERT statement:

INSERT INTO user (username, age, city) VALUES
    ('Xiao Hong', 30, 'Shanghai'),
    ('Xiao Gang', 22, 'Beijing');

A successful insertion adds two rows, with IDs 2 and 3 in an empty database following this article's sequence. Each set follows the username, age, city column order listed above. Submit large datasets in batches to avoid building an excessively large SQL statement.


✏️ Confirm the target before updating

First, check the user with id 1:

SELECT id, username, city FROM user WHERE id = 1;

Following the steps in this article produces:

idusernamecity
1Xiao MingBeijing

After confirming that the record belongs to Xiao Ming, update the city:

UPDATE user SET city = 'Hangzhou' WHERE id = 1;

Run the same query again:

idusernamecity
1Xiao MingHangzhou

WHERE limits which rows are updated; SET specifies the new value.

The client may report matched rows and changed rows separately. If the city is already Hangzhou, a matched record may remain unchanged. A report of zero changed rows does not always mean the user does not exist.


🗑 Query before deleting

Insert a record specifically for the deletion exercise:

INSERT INTO user (id, username) VALUES (100, 'User to delete');

Check the record with ID 100:

SELECT id, username FROM user WHERE id = 100;

Following the steps in this article produces:

idusername
100User to delete

Once you have confirmed the record, delete it:

DELETE FROM user WHERE id = 100;

Query ID 100 again. The result set has no data rows, leaving only the column names:

idusername

The client typically displays Empty set. Other users are unaffected, and auto-increment IDs are not rearranged to fill gaps.

An UPDATE or DELETE without WHERE affects the entire table. With the default autocommit behavior, a successful deletion cannot subsequently be undone with ROLLBACK.

❓ Questions and Answers

Q1: What if the database already exists?

Confirm that it is your practice database, then run USE blog_demo. Do not delete the existing database merely to eliminate the error.

Q2: Can the primary key tell me the total number of users?

No. Deletions, failed insertions, and manually assigned IDs can leave gaps. Use COUNT to count records.

Q3: Is NULL an empty string?

No. NULL represents a missing value; an empty string is a supplied text value with a length of zero.


🧪 Exercise

Insert a practice user, update only that record's city, and query it by ID to verify the change. Keep the record with ID 1: later articles use it.

-- Write your SQL or record your verification results here