database-sql
- Repo stars 0
- Author updated Live
- Author repo skills-registry
- Domain
- Design
- Compatible agents
-
- Claude Code
- Cursor
- Cline
- Codex
- Windsurf
- Gemini CLI
- +20
- Trust score
- 88 / 100 · community maintained
- Author / version / license
- @tomevault-io · no license declared
- Token usage
- Lean
- Setup complexity
- Plug-and-play
- External API key
- Not required
- Operating systems
- macOS · Linux · Windows
- Runtime requirements
- No special requirements
- Permissions
-
- Read-only
- Write / modify
- Network behavior
- Local-only
- Install commands
- 26 variants
Profile is derived at build time from SKILL.md and install vectors. Subject to drift from author intent.
Heads up: 未限定 allowed-tools,默认拥有全部工具权限。
---
name: database-sql
description: Design database schemas, write efficient SQL queries, create migrations, and optimize database p…
category: design
runtime: no special runtime
---
# database-sql output preview
## PART A: Task fit
- Use case: Design database schemas, write efficient SQL queries, create migrations, and optimize database performance. Use when working with databases, writing queries, or designing data models. Use when this capability is needed..
- Inputs: target material, constraints, expected output, and acceptance criteria.
- Evidence boundary: follow “When to use this skill / Schema design principles / Naming conventions” and do not present inference as author intent.
## PART B: Execution result
- **01** The card summarizes the use case; runtime output centers on “Design database schemas, write efficient SQL queries, create migrations, and optimize database performance. Use when working with databases, writing queries, or designing data models. Use when this capability is needed.”.
- **02** When the source has headings, the agent prioritizes “When to use this skill / Schema design principles / Naming conventions” so the result follows the author’s structure.
- **03** Typical output includes task judgment, concrete steps, required commands or file edits, validation, and follow-up options.
- **04** Risk context follows the fingerprint: read files, write/modify files; mostly runs locally; usually needs no extra API key.
## Running Rules
- read files, write/modify files; mostly runs locally; usually needs no extra API key.
- Validate with a small sample before expanding scope.
- Return the result, validation criteria, and next iteration options. The source does not require a stable slash command. After installation, invoke the skill by name and describe the task.
Name target files or source material, expected output, forbidden changes, and whether network or shell access is allowed. Permission fingerprint: read files, write/modify files.
Start with a small task and check whether the result follows “When to use this skill / Schema design principles / Naming conventions”. Inspect diffs, logs, previews, or tests before expanding scope.
Confirm the final output includes a concrete result, evidence, and next action. If it stays generic, tighten inputs, boundaries, and acceptance criteria.
---
name: database-sql
description: Design database schemas, write efficient SQL queries, create migrations, and optimize database p…
category: design
source: tomevault-io/skills-registry
---
# database-sql
## When to use
- Design database schemas, write efficient SQL queries, create migrations, and optimize database performance. Use when w…
- Use it when the task has clear inputs, repeatable steps, and validation criteria.
## What to provide
- Target material, scope, expected result, and forbidden changes.
- Whether network, commands, file writes, or external services are allowed.
## Execution rules
- Organize steps around “When to use this skill / Schema design principles / Naming conventions” and keep inference separate from source facts.
- read files, write/modify files; mostly runs locally; usually needs no extra API key.
- Validate with a small sample before expanding the task.
## Output requirements
- Return the deliverable, key evidence, validation method, and next action.
- Mark missing information as unknown; do not invent commands, platforms, or dependencies. The author source anchors workflow facts; repository files anchor sources and commands; Fluxly only adds fit, limitations, and quality judgment.
skill "database-sql" {
input -> user goal + target files + boundaries + acceptance criteria
context -> When to use this skill / Schema design principles / Naming conventions
rules -> SKILL.md triggers / order / output contract
runtime -> no special runtime | read files, write/modify files | mostly runs locally
guardrails -> usually needs no extra API key + small-sample validation + diff/log review
output -> copyable result + checklist + next iteration
} Database & SQL
When to use this skill
- Designing a database schema
- Writing or optimizing SQL queries
- Creating database migrations
- Setting up an ORM (Prisma, Drizzle, TypeORM, SQLAlchemy)
- Debugging query performance
- Adding indexes
Schema design principles
Naming conventions
- Tables: plural, snake_case —
users,order_items - Columns: snake_case —
created_at,first_name - Primary keys:
id(auto-increment or UUID) - Foreign keys:
<singular_table>_id—user_id,order_id - Indexes:
idx_<table>_<columns>—idx_users_email - Booleans:
is_orhas_prefix —is_active,has_verified
Common patterns
-- Standard table template
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'user',
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- Junction table for many-to-many
CREATE TABLE user_roles (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role_id UUID NOT NULL REFERENCES roles(id) ON DELETE CASCADE,
assigned_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, role_id)
);
-- Soft delete pattern
ALTER TABLE users ADD COLUMN deleted_at TIMESTAMPTZ;
CREATE INDEX idx_users_active ON users (id) WHERE deleted_at IS NULL;
Data types guide
| Use case | PostgreSQL | MySQL |
|---|---|---|
| Primary key | UUID or BIGSERIAL |
BIGINT AUTO_INCREMENT |
| Short text | VARCHAR(n) |
VARCHAR(n) |
| Long text | TEXT |
TEXT |
| Currency | NUMERIC(12,2) |
DECIMAL(12,2) |
| Timestamps | TIMESTAMPTZ |
DATETIME |
| JSON | JSONB |
JSON |
| Booleans | BOOLEAN |
TINYINT(1) |
| Enums | VARCHAR + CHECK |
ENUM(...) |
Migrations
Prisma
// schema.prisma
model User {
id String @id @default(uuid())
email String @unique
name String
orders Order[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("users")
}
model Order {
id String @id @default(uuid())
userId String @map("user_id")
user User @relation(fields: [userId], references: [id])
status OrderStatus @default(PENDING)
total Decimal @db.Decimal(12, 2)
createdAt DateTime @default(now()) @map("created_at")
@@index([userId])
@@map("orders")
}
enum OrderStatus {
PENDING
CONFIRMED
SHIPPED
DELIVERED
CANCELLED
}
# Generate and apply migration
npx prisma migrate dev --name add_orders_table
npx prisma generate
Raw SQL migration
-- migrations/001_create_users.up.sql
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_users_email ON users (email);
-- migrations/001_create_users.down.sql
DROP TABLE IF EXISTS users;
Query patterns
Pagination
-- Offset-based (simple, but slow for large offsets)
SELECT * FROM users
ORDER BY created_at DESC
LIMIT 20 OFFSET 40;
-- Cursor-based (performant for large datasets)
SELECT * FROM users
WHERE created_at < $1 -- cursor from previous page
ORDER BY created_at DESC
LIMIT 20;
Aggregation
-- Order summary by status
SELECT
status,
COUNT(*) AS count,
SUM(total) AS revenue,
AVG(total) AS avg_order
FROM orders
WHERE created_at >= now() - INTERVAL '30 days'
GROUP BY status
ORDER BY revenue DESC;
Common Table Expressions (CTEs)
-- Readable complex queries with CTEs
WITH monthly_revenue AS (
SELECT
date_trunc('month', created_at) AS month,
SUM(total) AS revenue
FROM orders
WHERE status = 'DELIVERED'
GROUP BY month
),
growth AS (
SELECT
month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly_revenue
)
SELECT
month,
revenue,
ROUND((revenue - prev_revenue) / prev_revenue * 100, 1) AS growth_pct
FROM growth
ORDER BY month DESC;
Upsert
-- PostgreSQL
INSERT INTO users (email, name)
VALUES ('alice@example.com', 'Alice')
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name, updated_at = now();
-- MySQL
INSERT INTO users (email, name)
VALUES ('alice@example.com', 'Alice')
ON DUPLICATE KEY UPDATE name = VALUES(name);
Indexing strategy
-- Single column (most common queries)
CREATE INDEX idx_users_email ON users (email);
-- Composite (multi-column WHERE clauses)
CREATE INDEX idx_orders_user_status ON orders (user_id, status);
-- Rule: put equality columns first, range columns last
-- Partial index (subset of rows)
CREATE INDEX idx_orders_pending ON orders (created_at)
WHERE status = 'PENDING';
-- CONCURRENTLY (no table lock in production)
CREATE INDEX CONCURRENTLY idx_users_name ON users (name);
When to add indexes
- Columns in WHERE clauses used frequently
- Columns in JOIN conditions
- Columns in ORDER BY (if not already covered)
- Foreign key columns
When NOT to index
- Small tables (< 1000 rows)
- Columns with very low cardinality (booleans)
- Tables with heavy write load and few reads
Performance debugging
-- Explain query plan
EXPLAIN ANALYZE
SELECT * FROM orders WHERE user_id = $1 AND status = 'active';
-- Look for:
-- Seq Scan → missing index
-- Nested Loop → potential N+1
-- Sort → missing index for ORDER BY
-- High "actual time" → slow operation
Checklist
- Tables follow naming conventions
- Primary keys and foreign keys defined
- Appropriate data types chosen
- NOT NULL constraints where appropriate
- Indexes on frequently queried columns
- Foreign keys have ON DELETE behavior
- Migrations are reversible (up + down)
- Queries use parameterized values (no interpolation)
- Large result sets are paginated
- Query performance checked with EXPLAIN ANALYZE
Source: asgarovf/locusai — distributed by TomeVault.
Decide Fit First
Design Intent
How To Use It
Boundaries And Review