New to Claude Skills? Learn how to install them →

affaan-m on GitHub

PostgreSQL Patterns

Free

Optimize your PostgreSQL database with proven patterns.

by affaan-m239.3k stars on affaan-m/ecc
2 views
Updated Aug 10, 2026
Get this skill

Free · Opens the source repo

What PostgreSQL Patterns does

PostgreSQL Patterns is a reference guide designed to help developers and database administrators implement best practices in PostgreSQL. This skill provides a comprehensive overview of query optimization, schema design, indexing strategies, and security measures based on established guidelines from Supabase. It serves as a quick reference to enhance your database performance and security while ensuring that your SQL queries are efficient and effective.

The skill includes various patterns for indexing, such as B-tree, GIN, and BRIN, along with examples of how to create these indexes for specific query types. It also outlines the correct data types to use in different scenarios, helping you avoid common pitfalls that can lead to performance issues. Additionally, the skill presents common patterns for constructing queries, such as composite indexes and upsert operations, which can streamline your database interactions.

Another key feature of PostgreSQL Patterns is its focus on security, particularly through Row Level Security (RLS) policies. It provides practical examples of how to implement RLS to ensure that users can only access data they are authorized to view. Furthermore, the skill offers templates for configuring connection pooling and monitoring settings, which are crucial for maintaining a healthy database environment.

This skill is particularly useful for developers writing SQL queries or migrations, database designers creating schemas, and anyone diagnosing slow queries or implementing security measures. By leveraging these patterns, users can enhance their understanding of PostgreSQL and improve the overall performance and security of their databases.

When to use it

Use this skill when writing SQL queries, designing database schemas, diagnosing slow queries, or implementing Row Level Security.

When not to use it

This skill is not suitable for users looking for a comprehensive database management tool or those needing advanced database administration features beyond optimization patterns.

What you can build with it

Optimizing Slow Queries

Use this skill to identify and implement indexing strategies that can drastically improve the performance of slow-running queries.

Designing a New Schema

Refer to the data type recommendations and indexing patterns when designing a new database schema to ensure optimal performance.

Implementing Row Level Security

Utilize the provided examples to set up Row Level Security policies that restrict data access based on user roles.

How to install PostgreSQL Patterns

View source

1. Install with the skills CLI

npx skills add affaan-m/ecc/postgres-patterns --agent claude-code

2. Or install it manually

Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.

Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs

Inside SKILL.md

Written by affaan-m

Patrones PostgreSQL

Referencia rápida de las buenas prácticas de PostgreSQL. Para orientación detallada, usa el agente database-reviewer.

Cuándo Activar

  • Escribir consultas SQL o migraciones
  • Diseñar esquemas de base de datos
  • Diagnosticar consultas lentas
  • Implementar Row Level Security
  • Configurar connection pooling

Referencia Rápida

Tabla de Índices

Patrón de ConsultaTipo de ÍndiceEjemplo
WHERE col = valueB-tree (por defecto)CREATE INDEX idx ON t (col)
WHERE col > valueB-treeCREATE INDEX idx ON t (col)
WHERE a = x AND b > yCompuestoCREATE INDEX idx ON t (a, b)
WHERE jsonb @> '{}'GINCREATE INDEX idx ON t USING gin (col)
WHERE tsv @@ queryGINCREATE INDEX idx ON t USING gin (col)
Rangos de series temporalesBRINCREATE INDEX idx ON t USING brin (col)

Referencia Rápida de Tipos de Datos

Caso de UsoTipo CorrectoEvitar
IDsbigintint, UUID aleatorio
Cadenastextvarchar(255)
Timestampstimestamptztimestamp
Dineronumeric(10,2)float
Flagsbooleanvarchar, int

Patrones Comunes

Orden del Índice Compuesto:

-- Columnas de igualdad primero, luego columnas de rango
CREATE INDEX idx ON orders (status, created_at);
-- Funciona para: WHERE status = 'pending' AND created_at > '2024-01-01'

Índice de Cobertura:

CREATE INDEX idx ON users (email) INCLUDE (name, created_at);
-- Evita la búsqueda en tabla para SELECT email, name, created_at

Índice Parcial:

CREATE INDEX idx ON users (email) WHERE deleted_at IS NULL;
-- Índice más pequeño, solo incluye usuarios activos

Política RLS (Optimizada):

CREATE POLICY policy ON orders
  USING ((SELECT auth.uid()) = user_id);  -- ¡Envolver en SELECT!

UPSERT:

INSERT INTO settings (user_id, key, value)
VALUES (123, 'theme', 'dark')
ON CONFLICT (user_id, key)
DO UPDATE SET value = EXCLUDED.value;

Paginación por Cursor:

SELECT * FROM products WHERE id > $last_id ORDER BY id LIMIT 20;
-- O(1) vs OFFSET que es O(n)

Procesamiento de Cola:

UPDATE jobs SET status = 'processing'
WHERE id = (
  SELECT id FROM jobs WHERE status = 'pending'
  ORDER BY created_at LIMIT 1
  FOR UPDATE SKIP LOCKED
) RETURNING *;

Detección de Anti-Patrones

-- Encontrar claves foráneas sin índice
SELECT conrelid::regclass, a.attname
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)
WHERE c.contype = 'f'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i
    WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)
  );

-- Encontrar consultas lentas
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;

-- Verificar bloat de tablas
SELECT relname, n_dead_tup, last_vacuum
FROM pg_stat_user_tables
WHERE n_dead_tup > 1000
ORDER BY n_dead_tup DESC;

Plantilla de Configuración

-- Límites de conexión (ajustar según RAM)
ALTER SYSTEM SET max_connections = 100;
ALTER SYSTEM SET work_mem = '8MB';

-- Timeouts
ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s';
ALTER SYSTEM SET statement_timeout = '30s';

-- Monitoreo
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Valores predeterminados de seguridad
REVOKE ALL ON SCHEMA public FROM public;

SELECT pg_reload_conf();

Relacionado

  • Agente: database-reviewer - Flujo de trabajo completo de revisión de base de datos
  • Skill: clickhouse-io - Patrones de analítica en ClickHouse
  • Skill: backend-patterns - Patrones de API y backend

Basado en Agent Skills de Supabase (crédito: equipo de Supabase) (Licencia MIT)

Frequently asked questions about PostgreSQL Patterns

Similar skills