Skip to main content

Getting Started with MySQL: Basic CRUD Operations

In this tutorial, we'll cover the essential CRUD operations (Create, Read, Update, and Delete) in MySQL. These operations form the backbone of any data-driven application, enabling you to manage your database records with ease.

1. Creating a Database and Table

Before performing any operations, you need to create a database and a table. In this example, we'll create a database called sample_db and a table named users to store user information.

-- Create a new database
CREATE DATABASE sample_db;
USE sample_db;

-- Create a table named 'users'
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);

2. Inserting Data (Create)

To add new records to your table, use the INSERT statement. Here’s how you can insert a couple of records into the users table:

INSERT INTO users (name, email)
VALUES ('Alice', 'alice@example.com'),
       ('Bob', 'bob@example.com');

3. Retrieving Data (Read)

To read data from the database, use the SELECT statement. The example below retrieves all records from the users table:

SELECT * FROM users;

4. Updating Data (Update)

If you need to modify existing data, the UPDATE statement comes into play. For instance, to update Alice's email address:

UPDATE users
SET email = 'alice_new@example.com'
WHERE name = 'Alice';

5. Deleting Data (Delete)

Finally, to remove records, use the DELETE statement. The following command removes Bob's record from the table:

DELETE FROM users
WHERE name = 'Bob';

Conclusion

You now have a quick overview of how to perform basic CRUD operations using MySQL. Mastering these commands is crucial for building, managing, and scaling any database-backed application. With these fundamentals in hand, you're ready to explore more advanced SQL queries and database optimization techniques.

Happy coding!

Comments