Locionic
Blog
Projects
Dev ToolsCheatsheetsSeries & Guides
About MeFree Production KitContact
Send email to LocionicLocionic GitHub profileLocionic YouTube channel
© 2026Locionic• All rights reserved.
Dev Kits & Data•Tools•Tags•RSS•Privacy Policy•Terms
  1. Home
  2. Blog
  3. The MySQL Cheat Sheet: Queries You'll Actually Use
Friday, April 12, 2024•6 min read

The MySQL Cheat Sheet: Queries You'll Actually Use

Locionic
Locionic(@Locionic)
mysql database
The MySQL Cheat Sheet: Queries You'll Actually Use
MySQL

CREATE DATABASE

Click to reveal
MySQL
Creates a new database: CREATE DATABASE zoo_db; Must be followed by USE zoo_db; to select it for subsequent operations.

CREATE DATABASE

MySQL

FOREIGN KEY

Click to reveal
MySQL
Enforces referential integrity between tables: FOREIGN KEY (habitat_id) REFERENCES habitat(id). Prevents orphaned records.

FOREIGN KEY

MySQL

GROUP BY

Click to reveal
MySQL
Groups rows by a column and allows aggregate functions (COUNT, SUM, AVG) per group. Often paired with HAVING to filter groups.

GROUP BY

MySQL

INNER JOIN

Click to reveal
MySQL
Returns only rows with matching values in both tables: INNER JOIN habitat ON animal.habitat_id = habitat.id. Most common join type.

INNER JOIN

MySQL

LEFT JOIN

Click to reveal
MySQL
Returns all rows from left table + matching rows from right. Non-matching right columns are NULL. Use for optional relationships.

LEFT JOIN

When you start working with databases, MySQL is usually the first system you'll encounter. It's battle-tested and powers everything from small side projects to massive enterprise applications.

Instead of reading a massive textbook, this guide covers the 20% of commands you'll use 80% of the time!

Audio Briefing• Voice: Google Cloud Journey-F
0:00 / --:--
Interactive Dev Tool
100% Client-Side & Private

SQL Query Optimizer & Index Advisor

Analyze queries for sargability, missing composite indexes & offsets

Analyze SQL queries for performance anti-patterns, wildcards, and slow offsets. Generates optimized queries and DDL composite indexes for PostgreSQL, MySQL, and SQLite.

Sargable QueriesComposite IndexesPostgres / MySQL / SQLiteQuery Planner
Launch Full ToolBrowse all 22 Dev Tools
Quick Start

Don't have MySQL installed? Spin it up instantly using Docker: docker run --name mysql-dev -e MYSQL_ROOT_PASSWORD=secret -d mysql


1. Databases & Tables

Manage Databases

Connect via terminal with mysql -u root -p. Create and select a database:

sql
CREATE DATABASE zoo_db;
USE zoo_db;

Create Tables with Relationships

Use Foreign Keys to ensure data integrity!

sql
CREATE TABLE habitat (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(64));
CREATE TABLE animal (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(64),
  habitat_id INT,
  FOREIGN KEY (habitat_id) REFERENCES habitat(id)
);
Interactive Quiz

What is the purpose of a FOREIGN KEY constraint?


2. Data Manipulation (CRUD)

OperationSyntaxKey Point
INSERT
INSERT INTO table (col) VALUES (val)
Auto-increment ID handled automatically
UPDATE
UPDATE table SET col=val WHERE condition
ALWAYS use WHERE clause!
DELETE
DELETE FROM table WHERE condition
Without WHERE = delete all rows!
SELECT
SELECT col1, col2 FROM table WHERE condition
* = all columns (avoid in production)
sql
INSERT INTO habitat (name) VALUES ('River'), ('Forest');

UPDATE animal SET name = 'Quack' WHERE id = 2;

DELETE FROM animal WHERE id = 1;
Always use WHERE!

If you run an UPDATE or DELETE command without a WHERE clause, you will modify or delete every single row in the table. Always double-check your queries!

Interactive Quiz

What happens if you run `UPDATE animal SET name='Test';` without a WHERE clause?


3. Querying and Aggregation

The Power of GROUP BY

ClausePurposeExample
SELECT
Columns to return
species, AVG(age)
WHERE
Filter rows BEFORE grouping
WHERE id != 3
GROUP BY
Group rows by column
GROUP BY species
HAVING
Filter groups AFTER aggregation
HAVING AVG(age) > 3
ORDER BY
Sort final result
ORDER BY AVG(age) DESC

Want to find the average age of each animal species?

sql
SELECT species, AVG(age) as average_age
FROM animal
WHERE id != 3
GROUP BY species
HAVING AVG(age) > 3
ORDER BY AVG(age) DESC;

This powerful query filters, groups, aggregates, filters the groups, and sorts the final result!

Joining Tables

Join TypeResultUse When
INNER JOIN
Only matching rows from both
Required relationships
LEFT JOIN
All left + matched right (NULL if no match)
Optional relationships
RIGHT JOIN
All right + matched left (NULL if no match)
Rarely used (flip tables instead)
CROSS JOIN
Cartesian product (all combinations)
Generating test data

To combine data from our two tables and view the animal's name alongside its habitat's name:

sql
SELECT animal.name AS animal_name, habitat.name AS habitat_name
FROM animal
INNER JOIN habitat ON animal.habitat_id = habitat.id;
Interactive Quiz

Which JOIN returns all rows from the left table and NULLs for non-matching right table columns?

Practice Makes Perfect

Mastering MySQL requires muscle memory. Open up your terminal and practice creating tables and joining data until it becomes second nature!

Related Posts
  • REST API vs GraphQL - When to use which for your data layer
  • Modern Python Development Environment - Python database tooling
MySQL Database SQL

You Might Also Like

  • Database Seeding Strategies with Prisma and TypeScript
  • Turso & libSQL: Distributed SQLite with Embedded Replicas for Low-Latency Backends
  • Distributed Locking in Distributed Systems: Redlock, PostgreSQL Advisory Locks & etcd Leases
  • Redis Memory Optimization: Internals, Data Structure Encoding, and Memory Profiling
Advertisement
Share this article:

Stay Updated

Get the latest posts delivered straight to your inbox.

Free Developer Utilities

Free In-Browser Developer Tools

Clean AI CLI logs, build cron expressions, decode JWTs, and calculate chmod permissions offline.

Explore Tools

Related Articles

Modern Database Sharding Strategies for Hyper-Growth
databaseSeptember 28, 2026

Modern Database Sharding Strategies for Hyper-Growth

Master modern database sharding architectures: horizontal partitioning, range vs consistent hash keys, cross-shard joins, distributed transactions (2PC vs Saga), Vitess, and Citus.

Read more
ClickHouse vs Snowflake in 2026: Real-Time Analytics, Query Latency & 80% Cost Reduction
clickhouseOctober 3, 2026

ClickHouse vs Snowflake in 2026: Real-Time Analytics, Query Latency & 80% Cost Reduction

Real-time analytics benchmark comparing ClickHouse vs Snowflake: P95 query latencies, compression ratios, compute costs, and when to migrate from cloud warehouses.

Read more
ClickHouse Materialized Views & ReplacingMergeTree: Sub-Second Real-Time Analytics
clickhouseOctober 2, 2026

ClickHouse Materialized Views & ReplacingMergeTree: Sub-Second Real-Time Analytics

Building real-time event analytics with ClickHouse Materialized Views and ReplacingMergeTree: deduplication patterns and sub-second aggregation queries.

Read more
On this page
0%
  • 1. Databases & Tables
  • 2. Data Manipulation (CRUD)
  • 3. Querying and Aggregation
  • The Power of GROUP BY
  • Joining Tables
Read NextUsing less memory to look up IP addresses in Mess With DNS