New advertisers: 50% off your first month with code FIRSTMONTHSee slots

SQL patterns for database querying and design

version
1.0.0
GitHub stars
26
View on GitHub

Add marketplace

/plugin marketplace add miles990/claude-software-skills

Run it inside Claude Code once, then install the plugin below.

Install

/plugin install sql@claude-software-skills

Run it inside Claude Code after adding the marketplace.

Files

Discovered from source

SQL

Overview

SQL patterns for querying, data manipulation, and database design.


Query Fundamentals

Basic Queries

-- SELECT with filtering
SELECT
    id,
    email,
    name,
    created_at
FROM users
WHERE active = true
  AND created_at >= '2024-01-01'
ORDER BY created_at DESC
LIMIT 10 OFFSET 0;

-- Multiple conditions
SELECT *
FROM orders
WHERE status IN ('pending', 'processing')
  AND total_amount > 100
  AND (priority = 'high' OR customer_type = 'premium');

-- LIKE and pattern matching
SELECT *
FROM products
WHERE name LIKE '%widget%'          -- Contains 'widget'
   OR name LIKE 'Premium%'          -- Starts with 'Premium'
   OR sku SIMILAR TO '[A-Z]{3}-[0-9]{4}';  -- Regex pattern (PostgreSQL)

-- NULL handling
SELECT
    id,
    COALESCE(nickname, name, 'Anonymous') AS display_name,
    NULLIF(discount, 0) AS discount_or_null
FROM users
WHERE deleted_at IS NULL;

-- CASE expressions
SELECT
    id,
    name,
    CASE
        WHEN total >= 1000 THEN 'Gold'
        WHEN total >= 500 THEN 'Silver'
        WHEN total >= 100 THEN 'Bronze'
        ELSE 'Standard'
    END AS tier,
    CASE status
        WHEN 'active' THEN 1
        WHEN 'pending' THEN 2
        ELSE 3
    END AS sort_order
FROM customers
ORDER BY sort_order;

-- Distinct and counting
SELECT DISTINCT category
FROM products;

SELECT
    category,
    COUNT(*) AS product_count,
    COUNT(DISTINCT brand) AS brand_count
FROM products
GROUP BY category;

Joins

-- INNER JOIN (only matching rows)
SELECT
    o.id AS order_id,
    o.total_amount,
    u.name AS customer_name,
    u.email
FROM orders o
INNER JOIN users u ON o.user_id = u.id
WHERE o.status = 'completed';

-- LEFT JOIN (all from left, matching from right)
SELECT
    u.id,
    u.name,
    COUNT(o.id) AS order_count,
    COALESCE(SUM(o.total_amount), 0) AS total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;

-- Multiple joins
SELECT
    o.id AS order_id,
    u.name AS customer_name,
    p.name AS product_name,
    oi.quantity,
    oi.unit_price
FROM orders o
JOIN users u ON o.user_id = u.id
JOIN order_items oi ON o.id = oi.order_id
JOIN products p ON oi.product_id = p.id
WHERE o.created_at >= CURRENT_DATE - INTERVAL '30 days';

-- Self join
SELECT
    e.name AS employee,
    m.name AS manager
FROM employees e
LEFT JOIN employees m ON e.manager_id = m.id;

-- Cross join (cartesian product)
SELECT
    p.name AS product,
    c.name AS color
FROM products p
CROSS JOIN colors c;

Aggregations

-- Basic aggregation
SELECT
    category,
    COUNT(*) AS product_count,
    SUM(price) AS total_value,
    AVG(price) AS avg_price,
    MIN(price) AS min_price,
    MAX(price) AS max_price
FROM products
GROUP BY category
HAVING COUNT(*) >= 5
ORDER BY product_count DESC;

-- Group by multiple columns
SELECT
    EXTRACT(YEAR FROM created_at) AS year,
    EXTRACT(MONTH FROM created_at) AS month,
    status,
    COUNT(*) AS order_count,
    SUM(total_amount) AS revenue
FROM orders
GROUP BY
    EXTRACT(YEAR FROM created_at),
    EXTRACT(MONTH FROM created_at),
    status
ORDER BY year, month;

-- ROLLUP (subtotals and grand total)
SELECT
    COALESCE(category, 'TOTAL') AS category,
    COALESCE(brand, 'All Brands') AS brand,
    COUNT(*) AS count,
    SUM(price) AS total
FROM products
GROUP BY ROLLUP (category, brand);

-- CUBE (all combinations)
SELECT
    category,
    brand,
    SUM(sales) AS total_sales
FROM product_sales
GROUP BY CUBE (category, brand);

-- GROUPING SETS
SELECT
    category,
    brand,
    SUM(sales) AS total_sales
FROM product_sales
GROUP BY GROUPING SETS (
    (category, brand),
    (category),
    (brand),
    ()
);

Advanced Queries

Window Functions

-- Row numbering
SELECT
    id,
    name,
    department,
    salary,
    ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank,
    ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;

-- Running totals
SELECT
    date,
    amount,
    SUM(amount) OVER (ORDER BY date) AS running_total,
    SUM(amount) OVER (
        ORDER BY date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS rolling_7_day
FROM daily_sales;

-- Rank functions
SELECT
    name,
    department,
    salary,
    RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank,
    DENSE_RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dense_rank,
    NTILE(4) OVER (ORDER BY salary DESC) AS quartile
FROM employees;

-- LAG and LEAD
SELECT
    date,
    revenue,
    LAG(revenue, 1) OVER (ORDER BY date) AS prev_day,
    LEAD(revenue, 1) OVER (ORDER BY date) AS next_day,
    revenue - LAG(revenue, 1) OVER (ORDER BY date) AS daily_change,
    100.0 * (revenue - LAG(revenue, 1) OVER (ORDER BY date))
        / LAG(revenue, 1) OVER (ORDER BY date) AS pct_change
FROM daily_revenue;

-- First/Last values
SELECT
    department,
    employee_name,
    salary,
    FIRST_VALUE(employee_name) OVER (
        PARTITION BY department ORDER BY salary DESC
    ) AS highest_paid,
    LAST_VALUE(employee_name) OVER (
        PARTITION BY department ORDER BY salary DESC
        ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    ) AS lowest_paid
FROM employees;

Common Table Expressions (CTEs)

-- Basic CTE
WITH active_users AS (
    SELECT *
    FROM users
    WHERE active = true
)
SELECT
    au.name,
    COUNT(o.id) AS order_count
FROM active_users au
LEFT JOIN orders o ON au.id = o.user_id
GROUP BY au.id, au.name;

-- Multiple CTEs
WITH
monthly_sales AS (
    SELECT
        DATE_TRUNC('month', created_at) AS month,
        SUM(total_amount) AS revenue
    FROM orders
    WHERE status = 'completed'
    GROUP BY DATE_TRUNC('month', created_at)
),
growth AS (
    SELECT
        month,
        revenue,
        LAG(revenue) OVER (ORDER BY month) AS prev_revenue
    FROM monthly_sales
)
SELECT
    month,
    revenue,
    prev_revenue,
    100.0 * (revenue - prev_revenue) / prev_revenue AS growth_pct
FROM growth
WHERE prev_revenue IS NOT NULL;

-- Recursive CTE (hierarchical data)
WITH RECURSIVE org_hierarchy AS (
    -- Base case: top-level employees
    SELECT
        id,
        name,
        manager_id,
        1 AS level,
        ARRAY[name] AS path
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive case: employees with managers
    SELECT
        e.id,
        e.name,
        e.manager_id,
        oh.level + 1,
        oh.path || e.name
    FROM employees e
    JOIN org_hierarchy oh ON e.manager_id = oh.id
)
SELECT
    id,
    name,
    level,
    array_to_string(path, ' -> ') AS hierarchy_path
FROM org_hierarchy
ORDER BY path;

Subqueries

-- Scalar subquery
SELECT
    name,
    salary,
    salary - (SELECT AVG(salary) FROM employees) AS diff_from_avg
FROM employees;

-- IN subquery
SELECT *
FROM products
WHERE category_id IN (
    SELECT id
    FROM categories
    WHERE parent_id IS NULL
);

-- EXISTS subquery
SELECT *
FROM users u
WHERE EXISTS (
    SELECT 1
    FROM orders o
    WHERE o.user_id = u.id
      AND o.created_at >= CURRENT_DATE - INTERVAL '30 days'
);

-- Correlated subquery
SELECT
    e.name,
    e.salary,
    e.department,
    (
        SELECT AVG(salary)
        FROM employees e2
        WHERE e2.department = e.department
    ) AS dept_avg
FROM employees e;

-- Lateral join (row-by-row subquery)
SELECT
    u.name,
    recent_orders.order_count,
    recent_orders.total_spent
FROM users u
CROSS JOIN LATERAL (
    SELECT
        COUNT(*) AS order_count,
        COALESCE(SUM(total_amount), 0) AS total_spent
    FROM orders o
    WHERE o.user_id = u.id
      AND o.created_at >= CURRENT_DATE - INTERVAL '90 days'
) recent_orders;

Data Modification

-- INSERT
INSERT INTO users (email, name, created_at)
VALUES ('user@example.com', 'New User', NOW());

-- INSERT multiple rows
INSERT INTO products (name, price, category)
VALUES
    ('Product A', 19.99, 'Electronics'),
    ('Product B', 29.99, 'Electronics'),
    ('Product C', 9.99, 'Accessories');

-- INSERT from SELECT
INSERT INTO order_archive (id, user_id, total_amount, created_at)
SELECT id, user_id, total_amount, created_at
FROM orders
WHERE created_at < '2023-01-01';

-- INSERT with conflict handling (PostgreSQL)
INSERT INTO users (email, name)
VALUES ('user@example.com', 'New User')
ON CONFLICT (email)
DO UPDATE SET name = EXCLUDED.name;

-- INSERT with conflict (MySQL)
INSERT INTO users (email, name)
VALUES ('user@example.com', 'New User')
ON DUPLICATE KEY UPDATE name = VALUES(name);

-- UPDATE
UPDATE products
SET price = price * 1.1,
    updated_at = NOW()
WHERE category = 'Electronics';

-- UPDATE with JOIN
UPDATE orders o
SET status = 'archived'
FROM users u
WHERE o.user_id = u.id
  AND u.deleted_at IS NOT NULL;

-- DELETE
DELETE FROM sessions
WHERE expires_at < NOW();

-- DELETE with subquery
DELETE FROM order_items
WHERE order_id IN (
    SELECT id FROM orders WHERE status = 'cancelled'
);

-- UPSERT (PostgreSQL)
INSERT INTO page_views (page_id, view_count)
VALUES (1, 1)
ON CONFLICT (page_id)
DO UPDATE SET view_count = page_views.view_count + 1;

Schema Design

-- Create table with constraints
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    email VARCHAR(255) NOT NULL UNIQUE,
    name VARCHAR(255) NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    role VARCHAR(50) DEFAULT 'user' CHECK (role IN ('admin', 'user', 'guest')),
    active BOOLEAN DEFAULT true,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Foreign keys
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    status VARCHAR(50) NOT NULL DEFAULT 'pending',
    total_amount DECIMAL(10, 2) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),

    CONSTRAINT valid_status CHECK (status IN ('pending', 'processing', 'completed', 'cancelled'))
);

-- Junction table (many-to-many)
CREATE TABLE product_categories (
    product_id UUID REFERENCES products(id) ON DELETE CASCADE,
    category_id UUID REFERENCES categories(id) ON DELETE CASCADE,
    PRIMARY KEY (product_id, category_id)
);

-- Indexes
CREATE INDEX idx_users_email ON users (email);
CREATE INDEX idx_orders_user_id ON orders (user_id);
CREATE INDEX idx_orders_status ON orders (status) WHERE status != 'completed';
CREATE INDEX idx_products_search ON products USING gin (to_tsvector('english', name || ' ' || description));

-- Partial index
CREATE UNIQUE INDEX idx_active_users_email
ON users (email)
WHERE active = true;

-- Generated columns (PostgreSQL 12+)
ALTER TABLE products
ADD COLUMN search_vector tsvector
GENERATED ALWAYS AS (to_tsvector('english', name || ' ' || COALESCE(description, ''))) STORED;

-- Triggers
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER set_updated_at
BEFORE UPDATE ON users
FOR EACH ROW
EXECUTE FUNCTION update_updated_at();

Performance

-- EXPLAIN ANALYZE
EXPLAIN ANALYZE
SELECT *
FROM orders o
JOIN users u ON o.user_id = u.id
WHERE o.status = 'pending';

-- Query hints (PostgreSQL)
SET enable_seqscan = off;  -- Force index usage for testing

-- Batch processing
WITH batch AS (
    SELECT id
    FROM large_table
    WHERE processed = false
    ORDER BY id
    LIMIT 1000
    FOR UPDATE SKIP LOCKED
)
UPDATE large_table
SET processed = true
WHERE id IN (SELECT id FROM batch);

-- Pagination with keyset
SELECT *
FROM products
WHERE (created_at, id) < ('2024-01-01', 'abc123')
ORDER BY created_at DESC, id DESC
LIMIT 20;

-- Materialized view
CREATE MATERIALIZED VIEW monthly_sales_summary AS
SELECT
    DATE_TRUNC('month', created_at) AS month,
    COUNT(*) AS order_count,
    SUM(total_amount) AS revenue
FROM orders
WHERE status = 'completed'
GROUP BY DATE_TRUNC('month', created_at);

-- Refresh materialized view
REFRESH MATERIALIZED VIEW CONCURRENTLY monthly_sales_summary;

Related Skills

  • [[database]] - Database design patterns
  • [[backend]] - Database integration
  • [[performance-optimization]] - Query optimization

From the miles990/claude-software-skills README

Claude Software Skills

55 modular software development skills for Claude Code - from architecture to deployment

Skills Categories Plugin

┌─────────────────────────────────────────────────────────────────┐
│                  Claude Software Skills                         │
│                                                                 │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│   │   Software   │  │   Software   │  │ Development  │         │
│   │    Design    │  │ Engineering  │  │    Stacks    │         │
│   │      6       │  │      8       │  │      8       │         │
│   └──────────────┘  └──────────────┘  └──────────────┘         │
│                                                                 │
│   ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│   │    Tools &   │  │   Domain     │  │ Programming  │         │
│   │ Integrations │  │ Applications │  │  Languages   │         │
│   │      9       │  │     12       │  │     12       │         │
│   └──────────────┘  └──────────────┘  └──────────────┘         │
│                                                                 │
│              AI 自動識別任務 → 載入對應領域知識                 │
└─────────────────────────────────────────────────────────────────┘

Features

  • MCP Compatible - Works with Claude Code, Cursor, and other MCP clients
  • Semantic Search - Claude automatically finds relevant skills for your task
  • Cross-Domain Integration - Skills work together seamlessly
  • Best Practices Built-In - Each skill includes patterns and anti-patterns
  • Modular Architecture - Use only what you need
  • Sharp Edges - Proactive warnings about common pitfalls with detection patterns
  • Validations - Executable code quality rules with regex/ast patterns
  • Collaboration - Skills declare relationships for smart delegation and context passing

Installation

Plugin Marketplace (Recommended)

# 1. Add marketplace (GitHub format: owner/repo)
/plugin marketplace add miles990/claude-software-skills

# 2. Open plugin management interface, view available plugins in Discover tab
/plugin

# 3. Install specific skills (choose what you need)
/plugin install frontend@claude-software-skills
/plugin install backend@claude-software-skills
/plugin install api-design@claude-software-skills

# Or mention skill name in conversation, Claude will auto-load

Supported GitHub formats:

# Short format (recommended)
/plugin marketplace add miles990/claude-software-skills

# HTTPS URL
/plugin marketplace add https://github.com/miles990/claude-software-skills.git

# Specify branch or tag
/plugin marketplace add miles990/claude-software-skills#main

Plugin commands:

CommandDescription
/pluginOpen interactive plugin management interface
/plugin install <name>@<marketplace>Install specific plugin
/plugin disable <name>@<marketplace>Temporarily disable plugin
/plugin uninstall <name>@<marketplace>Completely remove plugin

Available Skills

Software Design (6 skills)

SkillDescription
architecture-patternsSoftware architecture patterns and best practices
design-patternsClassic and modern software design patterns
api-designRESTful, GraphQL, gRPC, and API best practices
system-designScalability, availability, and distributed systems design
data-designData modeling, schema design, and data architecture
ux-principlesUser experience design principles for developers

Software Engineering (8 skills)

SkillDescription
code-qualityClean code principles, SOLID, and code review practices
testing-strategiesUnit, integration, E2E testing and TDD practices
devops-cicdCI/CD pipelines, infrastructure as code, and deployment
performance-optimizationProfiling, optimization techniques, and best practices
security-practicesOWASP Top 10, authentication, and secure coding
reliability-engineeringSRE principles, observability, and incident management
documentationTechnical writing, API docs, and documentation best practices
internationalizationi18n/l10n architecture design and multi-language support

Development Stacks (8 skills)

SkillDescription
frontendModern frontend with React, Vue, and web technologies
backendBackend with Node.js, Express, NestJS, and server patterns
mobileMobile with React Native, Flutter, and native patterns
databaseDatabase design, SQL, NoSQL, and data management
cloud-platformsAWS, GCP, Azure services and cloud-native development
ai-ml-integrationAI/ML APIs, LLM integration, and intelligent apps
realtime-systemsWebSocket, real-time communication, event-driven
edge-iotEdge computing, IoT protocols, and embedded systems

Tools & Integrations (9 skills)

SkillDescription
git-workflowsGit version control, branching, and collaboration
project-managementAgile, Scrum, Kanban, and issue tracking
development-environmentIDE setup, dev containers, and local development
monitoring-loggingApplication monitoring, logging, and alerting
api-toolsAPI testing, documentation, and development tools
automation-scriptsBuild automation, task runners, and scripting
auto-dev-setupAuto-Dev workflow for Human-in-the-Loop automation
claude-code-pluginClaude Code Plugin development and marketplace management
claude-code-sdkClaude Code SDK for AI-powered applications

Domain Applications (12 skills)

SkillDescription
application-patternsCommon application development patterns
e-commerceE-commerce platforms, payments, shopping cart
saas-platformsSaaS architecture, multi-tenancy, subscriptions
content-platformsCMS, blogging platforms, content management
communication-systemsEmail, notifications, messaging systems
developer-toolsCLI tools, SDKs, developer experience
game-developmentGame development patterns and architectures
flameFlame Engine 2D game development for Flutter
flame-coreFlame Engine core - components, input, collision
flame-systemsFlame Engine 14 game systems
flame-templatesGame templates - RPG, Platformer, Roguelike
desktop-appsDesktop apps with Electron and Tauri

Programming Languages (12 skills)

SkillDescription
javascript-typescriptModern JavaScript and TypeScript patterns
pythonPython programming patterns and best practices
goGo programming patterns and idioms
rustRust patterns and ownership concepts
java-kotlinJava and Kotlin programming patterns
csharp-dotnetC# and .NET development patterns
cppModern C++ programming patterns and idioms
rubyRuby programming patterns and idioms
phpModern PHP programming patterns
swiftSwift patterns for iOS and macOS
shell-bashShell scripting and Bash programming
sqlSQL patterns for database querying and design

Other Installation Methods

Clone to Skills Directory

# Clone to your skills directory
git clone https://github.com/miles990/claude-software-skills.git ~/.claude/skills/software-skills

Claude will automatically discover and use the skills when relevant to your tasks.

With MCP Server

This repository is compatible with claude-skills-mcp:

# Install the MCP server
pip install claude-skills-mcp

# Add this repository as a skill source
# The server will load skills from ~/.claude/skills/

Cursor IDE

Add to your Cursor MCP settings:

{
  "mcpServers": {
    "software-skills": {
      "command": "npx",
      "args": ["-y", "claude-skills-mcp"],
      "env": {
        "SKILLS_PATH": "/path/to/claude-software-skills"
      }
    }
  }
}

Manual Reference

Simply clone and reference the SKILL.md files in your prompts:

git clone https://github.com/miles990/claude-software-skills.git

Auto-Dev: Automated Development Workflow

One-click setup for GitHub Actions automated development workflow, let Claude help you complete development tasks.

Quick Setup

Using API Key:

curl -fsSL https://raw.githubusercontent.com/miles990/claude-software-skills/main/scripts/setup-auto-dev-apikey.sh | bash

Using Claude Max (OAuth):

curl -fsSL https://raw.githubusercontent.com/miles990/claude-software-skills/main/scripts/setup-auto-dev-max.sh | bash

Post-Installation Setup

VersionSetup Method
API KeyGet Key from console.anthropic.com, set in GitHub Secrets ANTHROPIC_API_KEY
Claude MaxRun claude /install-github-app for auto OAuth Token setup

Usage

  • Issue Trigger: Create Issue → Add auto-dev label
  • Comment Trigger: Comment @claude [instruction] on any Issue/PR

Detailed docs: AUTO-DEV.md

Usage Examples

User: Help me design a microservices architecture for an e-commerce platform

Claude: [Automatically uses architecture-patterns + e-commerce + api-design skills]
User: Review this Python code for performance issues

Claude: [Automatically uses python + performance-optimization + code-quality skills]
User: Set up CI/CD for a React + Node.js monorepo

Claude: [Automatically uses devops-cicd + frontend + backend + git-workflows skills]

Directory Structure

claude-software-skills/
├── .claude-plugin/          # Plugin configuration
│   └── marketplace.json     # Lists all 55 skills as individual plugins
├── .github/
│   └── workflows/           # CI/CD automation
├── software-design/         # Architecture & design skills
├── software-engineering/    # Development practices
├── development-stacks/      # Tech stack skills
├── tools-integrations/      # Developer tools
├── domain-applications/     # Domain-specific patterns
├── programming-languages/   # Language-specific skills
├── docs/
│   ├── SKILL-TEMPLATE.md    # Template for new skills
│   └── software-skills.md
├── CONTRIBUTING.md
├── LICENSE
└── README.md

How It Works

Each skill module contains a SKILL.md file with:

  1. Metadata - Name, description, tags for semantic search
  2. Key Concepts - Core knowledge and terminology
  3. Best Practices - Recommended approaches with examples
  4. Common Pitfalls - What to avoid and why
  5. Patterns & Anti-patterns - Do's and don'ts with code
  6. Tools & Resources - Recommended tools and references
  7. Decision Guide - When to use this skill

When you describe a task, Claude:

  1. Searches for relevant skills using semantic matching
  2. Loads the appropriate SKILL.md files
  3. Applies the knowledge to your specific context
  4. Follows best practices while avoiding common pitfalls

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Adding a New Skill

  1. Create a directory under the appropriate category
  2. Add a SKILL.md following our template
  3. Include practical examples and best practices
  4. Submit a pull request

License

MIT License - See LICENSE for details.

Related Projects


Built for developers, by developers, with Claude

Details

Marketplace
miles990/claude-software-skills
Source
programming-languages/sql
Category
Community
Listed since
Apr 6, 2026

More from miles990/claude-software-skills

All 56

Similar to sql

More Databases