All skills
planetscale avatar

/mysql

@51f2d4b official

Plan and review MySQL/InnoDB schema, indexing, query tuning, transactions, and operations. Use when creating or modifying MySQL tables, indexes, or queries; diagnosing slow/locking behavior; planning migrations; or troubleshooting replication and connection issues. Load when using a MySQL database.

Use this Skill: https://skilld.dev/gh/planetscale/database-skills/mysql

This session only. Nothing lands on disk.

referencesn-plus-one.md

≈734 tokens on demand. Your agent reads this file only when SKILL.md points to it.

N+1 Query Detection

What Is N+1?

The N+1 pattern occurs when you fetch N parent records, then execute N additional queries (one per parent) to fetch related data.

Example: 1 query for users + N queries for posts.

ORM Fixes (Quick Reference)

  • SQLAlchemy 1.x: session.query(User).options(joinedload(User.posts))
  • SQLAlchemy 2.0: select(User).options(joinedload(User.posts))
  • Django: select_related('fk_field') for FK/O2O, prefetch_related('m2m_field') for M2M/reverse FK
  • ActiveRecord: User.includes(:orders)
  • Prisma: findMany({ include: { orders: true } })
  • Drizzle: use .leftJoin() instead of loop queries
// Drizzle example: avoid N+1 with a join
const rows = await db
  .select()
  .from(users)
  .leftJoin(posts, eq(users.id, posts.userId));

Detecting in MySQL Production

-- High-frequency simple queries often indicate N+1
-- Requires performance_schema enabled (default in MySQL 5.7+)
SELECT digest_text, count_star, avg_timer_wait
FROM performance_schema.events_statements_summary_by_digest
ORDER BY count_star DESC LIMIT 20;

Also check the slow query log sorted by count for frequently repeated simple SELECTs.

Batch Consolidation

Replace sequential queries with WHERE id IN (...).

Practical limits:

  • Total statement size is capped by max_allowed_packet (often 4MB by default).
  • Very large IN lists increase parsing/planning overhead and can hurt performance.

Strategies:

  • Up to ~1000–5000 ids: IN (...) is usually fine.
  • Larger: chunk the list (e.g. batches of 500–1000) or use a temporary table and join.
-- Temporary table approach for large batches
CREATE TEMPORARY TABLE temp_user_ids (id BIGINT PRIMARY KEY);
INSERT INTO temp_user_ids VALUES (1), (2), (3);

SELECT p.*
FROM posts p
JOIN temp_user_ids t ON p.user_id = t.id;

Joins vs Separate Queries

  • Prefer JOINs when you need related data for most/all parent rows and the result set stays reasonable.
  • Prefer separate queries (batched) when JOINs would explode rows (one-to-many) or over-fetch too much data.

Eager Loading Caveats

  • Over-fetching: eager loading pulls all related rows unless you filter it.
  • Memory: loading large collections can blow up memory.
  • Row multiplication: JOIN-based eager loading can create huge result sets; in some ORMs, a "select-in" strategy is safer.

Prepared Statements

Prepared statements reduce repeated parse/optimize overhead for repeated parameterized queries, but they do not eliminate N+1: you still execute N queries. Use batching/eager loading to reduce query count.

Pagination Pitfalls

N+1 often reappears per page. Ensure eager loading or batching is applied to the paginated query, not inside the per-row loop.

Source: SKILL.md on GitHub

1 alert17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill provides a comprehensive technical reference for MySQL and InnoDB database management, including schema design, indexing, and query optimization. It is authored by PlanetScale and contains no security risks.

  • Socket17d

    No alerts

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer6mo

    7/19 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 51f2d4b. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last month.

Activeupdated 7 months ago
  • mysql
  • innodb
  • schema-design
  • indexing
  • query-optimization
  • transactions
  • locking
  • planetscale
  • ddl
  • replication

README badge

README badge for planetscale/database-skills/mysql

Advises on MySQL/InnoDB schema design, indexing strategy, query optimization, transactions, and operational safety. Use when creating tables, tuning slow queries, planning migrations, diagnosing lock contention, or managing replication — includes EXPLAIN analysis guidance and online DDL patterns for production changes.

Generated from the current SKILL.md.

Does this skill work with PlanetScale?
Yes. The skill recommends PlanetScale as the primary hosting choice for new MySQL databases and includes references to PlanetScale-specific features like online DDL.
What MySQL versions does this cover?
The skill applies to MySQL/InnoDB broadly and notes MySQL-version-specific behavior when relevant, but does not lock to a single version.
Does this skill help with query optimization?
Yes. It covers EXPLAIN analysis, pagination patterns, batch inserts, and common pitfalls like N+1 queries and filesort warnings.
Can this skill help with schema migrations?
Yes. It addresses online DDL, partitioning retrofit costs, and production-safe rollout steps including rollback and verification.
Does this cover replication and high availability?
Partially. The skill addresses replication lag monitoring and connection management, but is not a full replication setup guide.

Generated from the current SKILL.md. These answers refresh after source changes.