Mastering CRUD Operations

Mastering CRUD Operations in MySQL: CRUD represents the four fundamental operations performed on persistent data: Create, Read, Update, and Delete.

CRUD represents the four fundamental operations performed on persistent data: Create, Read, Update, and Delete. In SQL, these map directly to the Data Manipulation Language (DML) commands: INSERT, SELECT, UPDATE, and DELETE.

Every web application, REST API, mobile app backend, and microservice is ultimately a software wrapper around these four core database operations.


1. CREATE: The INSERT Statement

The INSERT statement adds new rows into an existing table.

Single-Row Insert

Explicitly specify the destination columns for safety, followed by the matching VALUES:

INSERT INTO users (username, email, age) 
VALUES ('sarah_connor', 'sarah@cyberdyne.com', 29);

Bulk Multi-Row Insert (High Performance)

In production applications, never run 1,000 individual insert queries in a loop. A single bulk insert query with multiple value tuples is up to 100x faster because it amortizes transaction log flushes and network round-trips into one batch:

INSERT INTO users (username, email, age) VALUES 
('john_matrix', 'john@commando.mil', 38),
('ellen_ripley', 'ripley@weyland.com', 32),
('tony_stark', 'tony@starkindustries.com', 45);

The "Upsert" Pattern (ON DUPLICATE KEY UPDATE)

When you want to insert a record if it's new, but update it if it already exists (matching a Primary Key or Unique Index):

INSERT INTO users (id, username, email, age)
VALUES (1, 'johndoe', 'new_john_email@example.com', 26)
ON DUPLICATE KEY UPDATE 
  email = VALUES(email),
  age = VALUES(age);

2. READ: The Power of SELECT

SELECT is the most expressive command in SQL. It allows you to project columns, filter conditions, sort results, calculate aggregates, and paginate records.

Column Projection & Aliasing (AS)

Never use SELECT * in production application code—only retrieve the exact columns needed to save network bandwidth and memory:

SELECT 
  username AS 'Customer Name',
  email AS 'Contact Email',
  age * 365 AS 'Estimated Days Old'
FROM users;

Precision Filtering with the WHERE Clause

The WHERE clause evaluates a boolean expression on every row:

-- Comparison operators: =, !=, <>, >, <, >=, <=
SELECT * FROM users WHERE age > 25;

-- Range filtering: BETWEEN ... AND ... (inclusive)
SELECT * FROM users WHERE age BETWEEN 20 AND 30;

-- Set membership: IN (...)
SELECT * FROM users WHERE username IN ('johndoe', 'janedoe');

-- Pattern matching: LIKE with wildcards (% = any characters, _ = one character)
SELECT * FROM users WHERE email LIKE '%@example.com';
SELECT * FROM users WHERE username LIKE 'john%';

-- Handling NULL: Always use IS NULL or IS NOT NULL (col = NULL never matches!)
SELECT * FROM users WHERE created_at IS NOT NULL;

-- Compound logic: AND, OR, NOT
SELECT * FROM users 
WHERE (age >= 21 AND age <= 35) 
   OR email LIKE '%.mil';

Sorting Results (ORDER BY)

By default, relational databases do not guarantee any specific order for returned rows. Always specify ORDER BY when order matters:

-- Sort descending by age, secondary sort ascending by username
SELECT username, age 
FROM users 
ORDER BY age DESC, username ASC;

Pagination Boundaries (LIMIT & OFFSET)

Essential for building paginated tables and infinite-scroll feeds:

-- Page 1: 10 items starting from index 0
SELECT id, username FROM users ORDER BY id ASC LIMIT 10 OFFSET 0;

-- Page 2: Next 10 items
SELECT id, username FROM users ORDER BY id ASC LIMIT 10 OFFSET 10;

3. UPDATE: Modifying Existing Records Safely

The UPDATE statement modifies existing data values in one or more columns.

⚠️ THE GOLDEN RULE OF UPDATES: Always verify your WHERE clause with a SELECT before running UPDATE. An UPDATE query without a WHERE clause will overwrite every single row in the entire table!

-- Safe, targeted update
UPDATE users 
SET age = age + 1, email = 'updated_jane@example.com'
WHERE username = 'janedoe';

-- Update multiple rows matching a condition
UPDATE orders
SET amount = amount * 0.90
WHERE order_date >= '2024-01-01';

4. DELETE: Removing Records & The Soft-Delete Pattern

The DELETE statement removes rows that match a condition.

-- Hard delete a specific user
DELETE FROM users 
WHERE username = 'alexsmith';

Hard Delete vs. Soft Delete in Modern Architectures

In modern production applications (banking, healthcare, e-commerce, SaaS), engineers rarely use raw DELETE statements because:

  1. Deleting a customer destroys audit trails and accounting records.
  2. Accidental deletions cannot be undone easily.

Instead, production schemas use the Soft Delete Pattern:

-- Add a nullable timestamp column to the table
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP NULL;

-- To "delete" a user, simply record the timestamp
UPDATE users 
SET deleted_at = CURRENT_TIMESTAMP 
WHERE id = 3;

-- Normal application queries filter out deleted rows
SELECT * FROM users 
WHERE deleted_at IS NULL;

5. Interactive Practice Challenges

Put your CRUD skills to the test right now in the Query Input editor:

Challenge 1: Insert a new user into the sandbox

INSERT INTO users (username, email, age) 
VALUES ('dev_ninja', 'ninja@codeacademix.com', 27);

SELECT * FROM users WHERE username = 'dev_ninja';

Challenge 2: Insert a matching order for this user

INSERT INTO orders (user_id, product, amount, order_date) 
VALUES (4, 'Mechanical Keyboard', 129.99, '2024-03-01');

SELECT * FROM orders WHERE user_id = 4;

Challenge 3: Update and calculate

UPDATE orders 
SET amount = amount - 20.00 
WHERE product = 'Mechanical Keyboard';

SELECT product, amount FROM orders WHERE product = 'Mechanical Keyboard';