Pins this version in aipm.package.json and aipm-lock.json.
aipm add @affaan-m/mysql-patterns@1.0.0
Without project tracking
Writes the skill files only. Add --no-init to skip aipm.package.json and the lockfile.
aipm add @affaan-m/mysql-patterns@1.0.0 --no-init
How to use
Install the skill above, then run this in your AI tool:
/mysql-patterns <your description>
About
Use this skill when working on MySQL or MariaDB schema design, migrations,
slow-query investigation, queue-style transactions, connection pools, or
production database configuration. Prefer exact version checks before applying a
feature-specific pattern because MySQL and MariaDB have diverged in several SQL
details.
Source
What gets added to your project
Preview every file this package writes on install before you run the command above.
Summary
MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends. Use when designing MySQL or MariaDB schemas and indexes, or when a query, transaction, or replica lags.
Skill instructions
MySQL Patterns
Use this skill when working on MySQL or MariaDB schema design, migrations,
slow-query investigation, queue-style transactions, connection pools, or
production database configuration. Prefer exact version checks before applying a
feature-specific pattern because MySQL and MariaDB have diverged in several SQL
details.
Activation
Designing MySQL or MariaDB tables, indexes, and constraints
Reviewing migrations before they run on large production tables
Debugging slow queries, lock waits, deadlocks, or connection exhaustion
Adding keyset pagination, upserts, full-text search, JSON columns, or queues
Configuring application connection pools, read replicas, TLS, or slow logs
Version Check
Start by identifying the engine and version:
sql
SELECT VERSION();
SHOW VARIABLES LIKE'version_comment';
Keep MySQL and MariaDB guidance separate when syntax differs:
MySQL documents row aliases as the replacement for VALUES(col) in
ON DUPLICATE KEY UPDATE; VALUES(col) is deprecated there.
MariaDB documents VALUES(col) as the supported way to reference inserted
values in ON DUPLICATE KEY UPDATE; use it for cross-engine compatibility.
SKIP LOCKED is appropriate for queue-like work only. It skips locked rows
and can return an inconsistent view, so do not use it for general accounting
or integrity-sensitive reads.
Schema Defaults
sql
CREATE TABLE orders (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
account_id BIGINT UNSIGNED NOT NULL,
status VARCHAR(32) NOT NULL,
total DECIMAL(15, 2) NOT NULL,
created_at DATETIME NOT NULLDEFAULTCURRENT_TIMESTAMP,
updated_at DATETIME NOT NULLDEFAULTCURRENT_TIMESTAMPONUPDATECURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_orders_account_status_created (account_id, status, created_at),
KEY idx_orders_active (account_id, deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Default choices:
Use Case
Prefer
Avoid
Surrogate primary keys
BIGINT UNSIGNED AUTO_INCREMENT
INT for tables that can grow beyond 2B rows
UUID lookup keys
BINARY(16) with conversion helpers
VARCHAR(36) primary keys on hot tables
Money and exact quantities
DECIMAL(p, s)
FLOAT or DOUBLE
User-facing text
utf8mb4 tables and indexes
MySQL utf8 / utf8mb3 defaults
Application timestamps
DATETIME with UTC managed by the app
Assuming DATETIME stores time zone metadata
Soft deletes
deleted_at DATETIME NULL plus scoped indexes
Filtering soft-deleted rows without an index
Extensible status values
lookup table or constrained VARCHAR
ENUM when values change often
Indexing
Composite index order usually follows equality predicates first, then range or
sort columns:
sql
CREATE INDEX idx_orders_account_status_created
ON orders (account_id, status, created_at);
SELECT id, total
FROM orders
WHERE account_id = ?
AND status ='pending'AND created_at >= ?
ORDERBY created_at DESC
LIMIT 50;
Use EXPLAIN before adding or changing an index:
sql
EXPLAIN
SELECT id, total
FROM orders
WHERE account_id =123AND status ='pending'ORDERBY created_at DESC
LIMIT 50;
Signals to investigate:
Field
Risk Signal
type
ALL on a large table
key
NULL when a selective predicate exists
rows
Very high row estimate for an interactive path
Extra
Using temporary, Using filesort, or broad Using where
Avoid adding indexes blindly. Each index increases write cost, migration time,
backup size, and buffer-pool pressure.
Query Patterns
Upsert
Cross-engine-compatible form:
sql
INSERT INTO user_settings (user_id, setting_key, setting_value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
setting_value =VALUES(setting_value),
updated_at =CURRENT_TIMESTAMP;
Use the row-alias form only after confirming the target is MySQL. Use
VALUES(col) for MariaDB or mixed MySQL/MariaDB fleets.
Keyset Pagination
sql
SELECT id, name, created_at
FROM products
WHERE (created_at, id) < (?, ?)
ORDERBY created_at DESC, id DESC
LIMIT 50;
Back it with an index that matches the cursor:
sql
CREATE INDEX idx_products_created_id ON products (created_at, id);
Do not use deep OFFSET pagination on large tables; it makes the server scan
and discard rows before returning the page.
JSON Fields
Use JSON columns for extension data, not for fields that need heavy relational
filtering or constraints.
sql
CREATE TABLE events (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
payload JSON NOT NULL,
event_type VARCHAR(64)
GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(payload, '$.type'))) STORED,
KEY idx_events_type (event_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
For frequently queried JSON paths, expose a generated column and index that
column. Keep foreign keys, ownership, tenancy, and lifecycle fields relational.
Full-Text Search
sql
ALTER TABLE articles ADD FULLTEXT KEY ft_articles_title_body (title, body);
SELECT id, title, MATCH(title, body) AGAINST (? INNATURALLANGUAGE MODE) AS score
FROM articles
WHEREMATCH(title, body) AGAINST (? INNATURALLANGUAGE MODE)
ORDERBY score DESC
LIMIT 20;
Use external search when you need typo tolerance, complex ranking, cross-table
facets, or language-specific analysis beyond built-in full-text behavior.
Transactions
Keep transactions short and lock rows in a consistent order:
sql
START TRANSACTION;
SELECT id, balance
FROM accounts
WHERE id IN (?, ?)
ORDERBY id
FORUPDATE;
UPDATE accounts SET balance = balance - ? WHERE id = ?;
UPDATE accounts SET balance = balance + ? WHERE id = ?;
COMMIT;
Deadlock and lock-wait checklist:
Lock rows in a deterministic order across code paths.
Do external API calls before opening the transaction, not inside it.
Add indexes for predicates used in UPDATE, DELETE, and locking reads.
On deadlock, roll back and retry the whole transaction with a bounded retry
budget.
Capture SHOW ENGINE INNODB STATUS\G soon after a deadlock; it is overwritten
by later events.
Queue-style worker claim:
sql
START TRANSACTION;
SELECT id
FROM jobs
WHERE status ='pending'ORDERBY created_at
LIMIT 1FORUPDATESKIP LOCKED;
UPDATE jobs
SET status ='processing', started_at =CURRENT_TIMESTAMPWHERE id = ?;
COMMIT;
Use SKIP LOCKED only for queue-like workloads where skipping a locked row is
acceptable. It is not a replacement for normal transactional consistency.
import mysql from'mysql2/promise';
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 30000,
});
const [rows] = await pool.execute(
'SELECT id, total FROM orders WHERE account_id = ? LIMIT 50',
[accountId],
);
Keep application pool recycling below the server wait_timeout. If the server
uses wait_timeout = 300, a pool_recycle around 240 seconds is coherent;
pool_pre_ping still helps recover from network and failover events.
Diagnostics
Useful first-pass commands:
sql
SHOWFULL PROCESSLIST;
SHOW ENGINE INNODB STATUS\G;
SHOW VARIABLES LIKE'slow_query_log';
SHOW VARIABLES LIKE'long_query_time';
Use EXPLAIN ANALYZE only when it is safe to execute the query. It runs the
statement and can be expensive on production-sized data.
Replication
Read replicas can lag. Do not route read-your-own-write paths, checkout flows,
permission checks, or idempotency-key reads to a replica immediately after a
write.
sql
-- MySQL legacy terminology, still common in existing fleetsSHOW SLAVE STATUS\G;
-- Newer terminology where supportedSHOW REPLICA STATUS\G;
Check the engine/version before standardizing on one command. Monitor replica
SQL thread health, IO thread health, and lag, not just whether the TCP
connection is alive.
Security
sql
CREATEUSER'app'@'%' IDENTIFIED BY'use-a-secret-manager';
GRANTSELECT, INSERT, UPDATE, DELETEON appdb.*TO'app'@'%';
ALTERUSER'app'@'%' REQUIRE SSL;
SELECTuser, host
FROM mysql.user
WHEREuser='';
DROPUSER IF EXISTS''@'localhost';
DROPUSER IF EXISTS''@'%';
Security review points:
Do not grant ALL PRIVILEGES or *.* to application users.
Require TLS for application users when traffic crosses hosts or networks.
Store credentials in the platform secret manager, not in examples, scripts, or
repository files.
Separate migration/admin users from runtime application users.
Audit public network exposure and bind addresses before tuning performance.
Configuration
Example starting point for a dedicated database host:
Treat configuration values as a prompt for review, not a universal preset. Size
memory, connections, log retention, and durability settings from workload,
hardware, backup policy, and recovery objectives.
Anti-Patterns
Anti-Pattern
Risk
Better Pattern
SELECT * in hot paths
Over-fetching and brittle clients
Select explicit columns
Deep OFFSET pagination
Linear scans and slow pages
Keyset pagination
No index on foreign-key joins
Slow joins and lock-heavy deletes
Index FK columns intentionally
Long transactions
Lock waits and large undo history
Commit small units of work
Direct DML against mysql.user
Grant-table corruption risk
Use CREATE USER, ALTER USER, DROP USER
Application user with admin grants
High blast radius
Least-privilege runtime user
Pool recycle above wait_timeout
Stale pooled connections
Recycle below timeout and pre-ping
Replica reads after writes
Stale user-facing state
Pin read-after-write flows to primary
Output Expectations
When this skill is used for review, return:
Engine/version assumptions.
Highest-risk correctness, lock, security, and migration issues.
Add this badge to a GitHub README so readers can open the package page and install the same version.
[](https://www.aipm-registry.com/skills/affaan-m/mysql-patterns/1.0.0?utm_source=github&utm_medium=readme&utm_campaign=package_badge)
This imported publisher has not claimed its AIPM account. A connected account confirms account control, but it does not guarantee that a package is safe.
AI assistant context
What this skill is for
@affaan-m/mysql-patterns@1.0.0 is an AIPM skill package for All tools. Use it when a project needs the reusable AI behavior described as: MySQL and MariaDB schema, query, indexing, transaction, replication, and connection-pool patterns for production backends. Use when designing MySQL or MariaDB schemas and indexes, or when a query, transaction, or replica lags.
Run aipm add @affaan-m/mysql-patterns@1.0.0 in a project that has AIPM initialized.
Supported tools
@affaan-m/mysql-patterns@1.0.0 supports All tools.
Before installing
AIPM skills can add files to your project. Review the package name, target, description, license, and publisher before installing. Use a clean branch when trying a new skill.