Here’s a comprehensive set of MySQL queries demonstrating how to create a database and perform all CRUD (Create, Read, Update, Delete) operations.
-- Create a new database
CREATE DATABASE my_database;
-- Use the created database
USE my_database;
-- Create a table named 'users'
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY, -- Auto-increment ID
name VARCHAR(100) NOT NULL, -- Name cannot be null
email VARCHAR(100) UNIQUE NOT NULL, -- Unique email
age INT, -- Optional age field
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Auto-filled timestamp
);
-- Insert a single record into the 'users' table
INSERT INTO users (name, email, age)
VALUES ('Alice', 'alice@example.com', 25);
-- Insert multiple records
INSERT INTO users (name, email, age)
VALUES
('Bob', 'bob@example.com', 30),
('Charlie', 'charlie@example.com', 22);
-- Select all records from the 'users' table
SELECT * FROM users;
-- Select only the 'name' and 'email' columns
SELECT name, email FROM users;
-- Select users older than 25
SELECT * FROM users WHERE age > 25;
-- Count total users
SELECT COUNT(*) AS total_users FROM users;
-- Find the average age
SELECT AVG(age) AS average_age FROM users;
-- Update a user's age where the name is 'Alice'
UPDATE users
SET age = 26
WHERE name = 'Alice';
-- Update multiple fields
UPDATE users
SET age = 35, email = 'updatedbob@example.com'
WHERE name = 'Bob';
-- Delete a user where the name is 'Charlie'
DELETE FROM users
WHERE name = 'Charlie';
-- Delete all records (use cautiously)
DELETE FROM users;
-- Select users whose email ends with '@example.com'
SELECT * FROM users WHERE email LIKE '%@example.com';
-- Select all users and sort by age in ascending order
SELECT * FROM users ORDER BY age ASC;
-- Sort by age in descending order
SELECT * FROM users ORDER BY age DESC;
-- Select only the first 2 records
SELECT * FROM users LIMIT 2;
-- Delete the 'users' table
DROP TABLE users;
-- Delete the 'my_database' database
DROP DATABASE my_database;
-
Create Database:
CREATE DATABASE my_database; USE my_database;
-
Create Table:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
-
Insert Data:
INSERT INTO users (name, email, age) VALUES ('Alice', 'alice@example.com', 25), ('Bob', 'bob@example.com', 30);
-
Read Data:
SELECT * FROM users;
-
Update Data:
UPDATE users SET age = 28 WHERE name = 'Alice';
-
Delete Data:
DELETE FROM users WHERE name = 'Bob';
- Always use the
WHERE
clause inUPDATE
andDELETE
statements to avoid unintentional changes to all rows. - Use
SHOW DATABASES;
andSHOW TABLES;
to list all databases and tables. - Use
DESCRIBE table_name;
to view the structure of a table.
This workflow covers the essentials of CRUD operations in MySQL.