mysql-patterns
MySQL database patterns for query optimization, schema design, indexing, and security. Quick reference for common patterns.
What this skill does
# MySQL Patterns
Quick reference for MySQL best practices. For detailed guidance, use the `mysql-database-reviewer` agent.
## When to Activate
- Writing SQL queries or migrations
- Designing database schemas
- Troubleshooting slow queries
- Setting up connection pooling
- Implementing multi-tenant isolation
## Quick Reference
### Index Cheat Sheet
| Query Pattern | Index Type | Example |
| ------------------------- | ---------------- | ------------------------------------- |
| `WHERE col = value` | B-tree (default) | `CREATE INDEX idx ON t (col)` |
| `WHERE col > value` | B-tree | `CREATE INDEX idx ON t (col)` |
| `WHERE a = x AND b > y` | Composite | `CREATE INDEX idx ON t (a, b)` |
| `MATCH(...) AGAINST(...)` | FULLTEXT | `CREATE FULLTEXT INDEX ft ON t (col)` |
| Long string prefix | Prefix | `CREATE INDEX idx ON t (col(50))` |
| Geographic data | SPATIAL | `CREATE SPATIAL INDEX idx ON t (col)` |
### Data Type Quick Reference
| Use Case | Correct Type | Avoid |
| ------------- | ----------------- | ---------------------------- |
| IDs | `bigint unsigned` | `int`, random UUID as PK |
| Business code | `varchar(64)` | `char`, `text` |
| Strings | `varchar(n)` | `text` for short strings |
| Timestamps | `datetime` | `timestamp` (2038 problem) |
| Money | `decimal(10,2)` | `float`, `double` |
| Flags | `tinyint` | `varchar`, `boolean` literal |
| Status | `tinyint` | `enum` (hard to modify) |
| JSON data | `json` | `text` for structured data |
### Common Patterns
**Composite Index Order:**
```sql
-- Equality columns first, then range columns
CREATE INDEX idx_status_created ON t_order (status, created_at);
-- Works for: WHERE status = 'pending' AND created_at > '2024-01-01'
-- Does NOT work for: WHERE created_at > '2024-01-01' alone
```
**Prefix Index (Long Strings):**
```sql
CREATE INDEX idx_url ON t_page (url(100));
-- Index only first 100 characters
```
**Generated Column + Index (JSON):**
```sql
ALTER TABLE t_product
ADD COLUMN brand varchar(100) GENERATED ALWAYS AS (attributes->>'$.brand') STORED;
CREATE INDEX idx_brand ON t_product (brand);
```
**UPSERT (ON DUPLICATE KEY):**
```sql
INSERT INTO t_setting (user_code, `key`, `value`)
VALUES ('u123', 'theme', 'dark')
ON DUPLICATE KEY UPDATE
`value` = VALUES(`value`),
updated_at = NOW();
```
**Cursor Pagination:**
```sql
SELECT * FROM t_product WHERE id > ? ORDER BY id LIMIT 20;
-- O(1) vs OFFSET which is O(n)
```
**Queue Processing (MySQL 8.0+):**
```sql
START TRANSACTION;
SELECT * FROM t_job
WHERE status = 'pending'
ORDER BY created_at LIMIT 1
FOR UPDATE SKIP LOCKED;
-- Process job...
UPDATE t_job SET status = 'processing' WHERE id = ?;
COMMIT;
```
**Batch Insert:**
```sql
INSERT INTO t_event (user_code, action) VALUES
('u1', 'click'),
('u2', 'view'),
('u3', 'click');
-- 1 round trip instead of 3
```
### Anti-Pattern Detection
```sql
-- Find tables without primary key
SELECT t.table_name
FROM information_schema.tables t
LEFT JOIN information_schema.key_column_usage k
ON t.table_schema = k.table_schema
AND t.table_name = k.table_name
AND k.constraint_name = 'PRIMARY'
WHERE t.table_schema = DATABASE()
AND k.constraint_name IS NULL
AND t.table_type = 'BASE TABLE';
-- Find slow queries (performance_schema)
SELECT DIGEST_TEXT, COUNT_STAR,
ROUND(AVG_TIMER_WAIT/1000000000, 2) as avg_ms
FROM performance_schema.events_statements_summary_by_digest
WHERE AVG_TIMER_WAIT > 100000000 -- > 100ms
ORDER BY AVG_TIMER_WAIT DESC LIMIT 10;
-- Find unused indexes (sys schema)
SELECT * FROM sys.schema_unused_indexes
WHERE object_schema = DATABASE();
-- Find redundant indexes
SELECT * FROM sys.schema_redundant_indexes
WHERE table_schema = DATABASE();
-- Check table fragmentation
SELECT table_name, data_free,
ROUND(data_free/(data_length+index_length+data_free)*100, 2) as frag_pct
FROM information_schema.tables
WHERE table_schema = DATABASE() AND data_free > 1000000
ORDER BY data_free DESC;
```
### Configuration Template
```sql
-- Connection limits
SET GLOBAL max_connections = 200;
SET GLOBAL max_user_connections = 50;
-- Timeouts
SET GLOBAL wait_timeout = 300;
SET GLOBAL interactive_timeout = 600;
SET GLOBAL max_execution_time = 30000; -- 30s query timeout (MySQL 5.7.8+)
-- Slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 1;
SET GLOBAL log_queries_not_using_indexes = 'ON';
-- InnoDB settings (my.cnf recommended)
-- innodb_buffer_pool_size = 70% of RAM
-- innodb_log_file_size = 256M
-- innodb_flush_log_at_trx_commit = 1
```
### Table Template
```sql
CREATE TABLE `t_example` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'PK',
`example_code` varchar(64) NOT NULL COMMENT 'Business code (UUID)',
-- Business fields here
`status` tinyint NOT NULL DEFAULT 1 COMMENT '0-inactive, 1-active',
-- Audit fields (5 fields)
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Creation time',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
`created_by` varchar(64) NOT NULL DEFAULT '' COMMENT 'Creator (user_code)',
`updated_by` varchar(64) NOT NULL DEFAULT '' COMMENT 'Modifier (user_code)',
`deleted_at` datetime DEFAULT NULL COMMENT 'Soft delete marker',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_example_code` (`example_code`),
KEY `idx_status` (`status`),
KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```
### EXPLAIN Analysis
```sql
EXPLAIN ANALYZE SELECT * FROM t_order WHERE user_code = 'u123';
```
| Indicator | Problem | Solution |
| ----------------- | ------------------- | ------------------ |
| `type: ALL` | Full table scan | Add index |
| `type: index` | Full index scan | Check WHERE |
| `Using filesort` | Sorting not indexed | Add ORDER BY index |
| `Using temporary` | Temp table | Optimize GROUP BY |
| High `rows` | Poor selectivity | Review conditions |
## Related
- Agent: `mysql-database-reviewer` - Full database review workflow
---
_Quick reference for MySQL 5.7+ / 8.0+_
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.