본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)280k · #215

mysql-patterns

하는 일

이 도구는 MySQL과 MariaDB 데이터베이스를 만들고 최적화하도록 돕습니다. 테이블을 정리하고, 효율적인 인덱스를 만들고, 빠른 쿼리를 작성하는 패턴을 제공합니다.

사용하는 경우

  • ✓테이블 구조와 인덱스를 설계할 때.
  • ✓데이터베이스 쿼리가 왜 느린지 알아볼 때.
  • ✓애플리케이션의 데이터베이스 연결을 설정할 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/mysql-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/mysql-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“users 테이블에서 이름과 생성 날짜로 검색을 더 빠르게 하려면 인덱스를 어떻게 만들어야 할까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 도구는 코드 예시와 설명을 바탕으로 모범 사례를 제안합니다. 테이블을 정의하는 방법, 적합한 데이터 타입, 성능이 좋은 쿼리를 작성하는 방법을 보여 줍니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

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:

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

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 NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_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:

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 >= ?
ORDER BY created_at DESC
LIMIT 50;

Use EXPLAIN before adding or changing an index:

EXPLAIN
SELECT id, total
FROM orders
WHERE account_id = 123 AND status = 'pending'
ORDER BY 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:

INSERT INTO user_settings (user_id, setting_key, setting_value)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
    setting_value = VALUES(setting_value),
    updated_at = CURRENT_TIMESTAMP;

MySQL row-alias form:

INSERT INTO user_settings (user_id, setting_key, setting_value)
VALUES (?, ?, ?) AS new
ON DUPLICATE KEY UPDATE
    setting_value = new.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

SELECT id, name, created_at
FROM products
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT 50;

…

자주 묻는 질문

이 맥락에서 ‘패턴’이란 무엇인가요?

데이터베이스 사용에서 흔히 생기는 문제, 예를 들어 데이터를 정리하거나 검색을 빠르게 하는 데 검증되고 권장되는 해결책입니다.

MySQL/MariaDB 버전을 왜 신경 써야 하나요?

버전마다 SQL 명령을 해석하는 방식에 작은 차이가 있을 수 있으므로, 어떤 버전을 쓰는지 알아야 올바른 패턴을 적용할 수 있습니다.

‘키셋 페이지네이션(keyset pagination)’이란 무엇인가요?

데이터를 페이지 단위로 가져오는 효율적인 방법입니다. 특히 큰 테이블에서 ‘offset’을 쓰는 기존 방식보다 빠릅니다.

상세 정보

작성자의 원본 설명

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.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#215
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬