All skills
supabase avatar

/supabase-postgres-best-practices

@3291216 official
by supabasesupabase/agent-skills2.7k stars
214

Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pg_cron, pgmq), vector/semantic search (pgvector), and restoring dumps (pg_restore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.

Use this Skill: https://skilld.dev/gh/supabase/agent-skills/supabase-postgres-best-practices

This session only. Nothing lands on disk.

references_contributing.md

≈1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Writing Guidelines for Postgres References

This document provides guidelines for creating effective Postgres best practice references that work well with AI agents and LLMs.

Key Principles

1. Concrete Transformation Patterns

Show exact SQL rewrites. Avoid philosophical advice.

Good: "Use WHERE id = ANY(ARRAY[...]) instead of WHERE id IN (SELECT ...)" Bad: "Design good schemas"

2. Error-First Structure

Always show the problematic pattern first, then the solution. This trains agents to recognize anti-patterns.

**Incorrect (sequential queries):** [bad example]

**Correct (batched query):** [good example]

3. Quantified Impact

Include specific metrics. Helps agents prioritize fixes.

Good: "10x faster queries", "50% smaller index", "Eliminates N+1" Bad: "Faster", "Better", "More efficient"

4. Self-Contained Examples

Examples should be complete and runnable (or close to it). Include CREATE TABLE if context is needed.

-- Include table definition when needed for clarity
CREATE TABLE users (
  id bigint PRIMARY KEY,
  email text NOT NULL,
  deleted_at timestamptz
);

-- Now show the index
CREATE INDEX users_active_email_idx ON users(email) WHERE deleted_at IS NULL;

5. Semantic Naming

Use meaningful table/column names. Names carry intent for LLMs.

Good: users, email, created_at, is_active Bad: table1, col1, field, flag


Code Example Standards

SQL Formatting

-- Use lowercase keywords, clear formatting
CREATE INDEX CONCURRENTLY users_email_idx
  ON users(email)
  WHERE deleted_at IS NULL;

-- Not cramped or ALL CAPS
CREATE INDEX CONCURRENTLY USERS_EMAIL_IDX ON USERS(EMAIL) WHERE DELETED_AT IS NULL;

Comments

  • Explain why, not what
  • Highlight performance implications
  • Point out common pitfalls

Language Tags

  • sql - Standard SQL queries
  • plpgsql - Stored procedures/functions
  • typescript - Application code (when needed)
  • python - Application code (when needed)

When to Include Application Code

Default: SQL Only

Most references should focus on pure SQL patterns. This keeps examples portable.

Include Application Code When:

  • Connection pooling configuration
  • Transaction management in application context
  • ORM anti-patterns (N+1 in Prisma/TypeORM)
  • Prepared statement usage

Format for Mixed Examples:

**Incorrect (N+1 in application):**

```typescript
for (const user of users) {
  const posts = await db.query("SELECT * FROM posts WHERE user_id = $1", [
    user.id,
  ]);
}
```

Correct (batch query):

const posts = await db.query("SELECT * FROM posts WHERE user_id = ANY($1)", [
  userIds,
]);

Impact Level Guidelines

Level Improvement Use When
CRITICAL 10-100x Missing indexes, connection exhaustion, sequential scans on large tables
HIGH 5-20x Wrong index types, poor partitioning, missing covering indexes
MEDIUM-HIGH 2-5x N+1 queries, inefficient pagination, RLS optimization
MEDIUM 1.5-3x Redundant indexes, query plan instability
LOW-MEDIUM 1.2-2x VACUUM tuning, configuration tweaks
LOW Incremental Advanced patterns, edge cases

Reference Standards

Primary Sources:

  • Official Postgres documentation
  • Supabase documentation
  • Postgres wiki
  • Established blogs (2ndQuadrant, Crunchy Data)

Format:

Reference:
[Postgres Indexes](https://www.postgresql.org/docs/current/indexes.html)

Review Checklist

Before submitting a reference:

  • Title is clear and action-oriented
  • Impact level matches the performance gain
  • impactDescription includes quantification
  • Explanation is concise (1-2 sentences)
  • Has at least 1 Incorrect SQL example
  • Has at least 1 Correct SQL example
  • SQL uses semantic naming
  • Comments explain why, not what
  • Trade-offs mentioned if applicable
  • Reference links included
  • pnpm test passes

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    This skill provides a comprehensive set of Postgres best practices maintained by Supabase, focusing on performance, schema design, and security. It includes specific guidance on Row-Level Security (RLS) and the principle of least privilege to enhance database security. The content is educational and follows established security and performance guidelines for PostgreSQL.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    9/38 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at 3291216. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 3 days ago.

Activeupdated 2 months ago
Other metadata
metadata
{
  "author": "supabase",
  "version": "1.1.1",
  "organization": "Supabase",
  "date": "January 2026",
  "abstract": "Comprehensive Postgres performance optimization guide for developers using Supabase and Postgres. Contains performance rules across 8 categories, prioritized by impact from critical (query performance, connection management) to incremental (advanced features). Each rule includes detailed explanations, incorrect vs. correct SQL examples, query plan analysis, and specific performance metrics to guide automated optimization and code generation."
}
  • Performance
  • postgres
  • supabase
  • query-optimization
  • schema-design
  • indexing
  • connection-pooling
  • rls

README badge

README badge for supabase/agent-skills/supabase-postgres-best-practices

Guides query optimization, schema design, and connection management for Postgres databases on Supabase through 8 categories of best practices, from query performance and RLS to monitoring and advanced features. Includes SQL examples, EXPLAIN output, and performance metrics for each rule.

Generated from the current SKILL.md.

Does this skill work with non-Supabase Postgres databases?
Yes. The skill covers general Postgres performance optimization and best practices. While maintained by Supabase and includes Supabase-specific notes where relevant, the core rules apply to any Postgres instance.
What does this skill actually do — does it automatically optimize queries?
No. The skill is a reference guide containing 8 categories of optimization rules with SQL examples, query plan analysis, and performance metrics. It's meant to inform code generation and manual optimization, not to run automated fixes.
Does this cover Row-Level Security (RLS)?
Yes. Security and RLS is one of three critical-priority categories in the skill, with dedicated rules for secure schema and access patterns.
Does this skill include connection pooling guidance?
Yes. Connection management is a critical-priority category with rules on pooling configuration and scaling, marked with the `conn-` prefix.
What if I'm using a different SQL dialect or database?
This skill is Postgres-specific and will not apply to MySQL, SQLite, or other databases. Some concepts may transfer, but query syntax and optimization strategies differ.

Generated from the current SKILL.md. These answers refresh after source changes.