
PostgreSQL Patterns
FreeOptimize your PostgreSQL database with proven patterns.
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 source1. Install with the skills CLI
npx skills add affaan-m/ecc/postgres-patterns --agent claude-code2. 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-mPatrones 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 Consulta | Tipo de Índice | Ejemplo |
|---|---|---|
WHERE col = value | B-tree (por defecto) | CREATE INDEX idx ON t (col) |
WHERE col > value | B-tree | CREATE INDEX idx ON t (col) |
WHERE a = x AND b > y | Compuesto | CREATE INDEX idx ON t (a, b) |
WHERE jsonb @> '{}' | GIN | CREATE INDEX idx ON t USING gin (col) |
WHERE tsv @@ query | GIN | CREATE INDEX idx ON t USING gin (col) |
| Rangos de series temporales | BRIN | CREATE INDEX idx ON t USING brin (col) |
Referencia Rápida de Tipos de Datos
| Caso de Uso | Tipo Correcto | Evitar |
|---|---|---|
| IDs | bigint | int, UUID aleatorio |
| Cadenas | text | varchar(255) |
| Timestamps | timestamptz | timestamp |
| Dinero | numeric(10,2) | float |
| Flags | boolean | varchar, 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
ClickHouse Logs Queries
Efficiently manage Supabase logs with ClickHouse SQL.
EF Core D2 Database Diagram Generator
Visualize your EF Core models as D2 diagrams effortlessly.
Safe SQL Execution
Ensure secure SQL execution in Supabase applications.
Oracle to PostgreSQL Migration
Identify migration risks between Oracle and PostgreSQL.
SSMA Console
Streamline Oracle to SQL Server migrations with ease.
SQL Performance Optimization
Enhance SQL query efficiency across all databases.
