{
    "url": "https://delaparra-services.nl/skills/postgresql-table-design",
    "locale": "en",
    "title": "PostgreSQL Table Design | DeLaParra Services",
    "description": "Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features",
    "alternates": {
        "en": "https://delaparra-services.nl/skills/postgresql-table-design",
        "nl": "https://delaparra-services.nl/nl/skills/postgresql-table-design"
    },
    "formats": {
        "csv": "https://delaparra-services.nl/skills/postgresql-table-design.csv",
        "md": "https://delaparra-services.nl/skills/postgresql-table-design.md",
        "json": "https://delaparra-services.nl/skills/postgresql-table-design.json",
        "zip": "https://delaparra-services.nl/skills/postgresql-table-design.zip",
        "pdf": "https://delaparra-services.nl/skills/postgresql-table-design.pdf"
    },
    "downloads": [
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design.csv",
            "encodingFormat": "text/csv",
            "name": "postgresql-table-design.csv"
        },
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design.json",
            "encodingFormat": "application/json",
            "name": "postgresql-table-design.json"
        },
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design.md",
            "encodingFormat": "text/markdown",
            "name": "postgresql-table-design.md"
        },
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design.pdf",
            "encodingFormat": "application/pdf",
            "name": "postgresql-table-design.pdf"
        },
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design.zip",
            "encodingFormat": "application/zip",
            "name": "postgresql-table-design.zip"
        },
        {
            "url": "https://delaparra-services.nl/skills/postgresql-table-design/download",
            "encodingFormat": "application/zip",
            "name": "postgresql-table-design-files.zip"
        }
    ],
    "markdown": "# PostgreSQL Table Design\n\n \n\nUse this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features\n\n \n\n**Licence** MIT\n\n \n\n**Source** wshobson/agents\n\n [Download zip](<https://delaparra-services.nl/skills/postgresql-table-design/download>)   \n\n# PostgreSQL Table Design\n\n \n\n## When to Use\n\n \n\n- Designing a new PostgreSQL schema, or reviewing one before it ships. \n- Choosing column types, keys, constraints, or indexes for PostgreSQL specifically. \n- Deciding whether and how to partition a large table, or how to store semi-structured data. \n- Planning a schema change on a live database without downtime.\n\n \n\nThe rules and decision points for a PostgreSQL schema. The full data-type catalog, workload patterns (update-heavy, insert-heavy, upsert, schema evolution), extensions, JSONB indexing, and worked DDL examples are in ` references/details.md `; open it when a section below points there.\n\n \n\n## Core Rules\n\n \n\n- Define a **PRIMARY KEY** for reference tables (users, orders, etc.). Not always needed for time-series/event/log data. When used, prefer ` BIGINT GENERATED ALWAYS AS IDENTITY `; use ` UUID ` only when global uniqueness/opacity is needed. \n- **Normalize first (to 3NF)** to eliminate data redundancy and update anomalies; denormalize **only** for measured, high-ROI reads where join performance is proven problematic. \n- Add **NOT NULL** everywhere it is semantically required; use **DEFAULT**s for common values. \n- Create **indexes for access paths you actually query**: PK/unique (auto), **FK columns (manual!)**, frequent filters/sorts, and join keys. \n- Prefer **TIMESTAMPTZ** for event time; **NUMERIC** for money; **TEXT** for strings; **BIGINT** for integers; **DOUBLE PRECISION** for floats (or ` NUMERIC ` for exact decimal arithmetic).\n\n \n\n## PostgreSQL Gotchas\n\n \n\n- **Identifiers**: unquoted → lowercased. Avoid quoted/mixed-case names; use ` snake_case `. \n- **Unique + NULLs**: UNIQUE allows multiple NULLs. Use ` UNIQUE NULLS NOT DISTINCT (...) ` (PG15+) to restrict to one NULL. \n- **FK indexes**: PostgreSQL **does not** auto-index FK columns. Add them. \n- **No silent coercions**: length/precision overflows error out (no truncation). Inserting 999 into ` NUMERIC(2,0) ` fails, unlike databases that silently truncate or round. \n- **Sequences/identity have gaps** (normal; don't \"fix\"). Rollbacks, crashes, and concurrent transactions leave gaps (1, 2, 5, 6...). \n- **Heap storage**: no clustered PK by default; ` CLUSTER ` is a one-off reorganization, not maintained on later inserts. \n- **MVCC**: updates/deletes leave dead tuples; vacuum handles them—design to avoid hot wide-row churn.\n\n \n\n## Data Types\n\n \n\n- **IDs**: ` BIGINT GENERATED ALWAYS AS IDENTITY `; ` UUID ` for distributed or opaque IDs, generated with ` uuidv7() ` (PG18+) or ` gen_random_uuid() `. \n- **Numbers**: ` BIGINT ` unless storage is critical; ` DOUBLE PRECISION ` over ` REAL `; ` NUMERIC(p,s) ` for money and exact decimals. \n- **Strings**: ` TEXT `, with ` CHECK (LENGTH(col) <= n) ` when a limit is needed; ` BYTEA ` for binary. Case-insensitive lookups: expression index on ` LOWER(col) `, or ` CITEXT ` when a constraint must be case-insensitive. \n- **Time**: ` TIMESTAMPTZ `, ` DATE `, ` INTERVAL `. ` now() ` is transaction start; ` clock_timestamp() ` is wall clock. \n- **Booleans**: ` BOOLEAN NOT NULL ` unless tri-state is required. \n- **Enums**: ` CREATE TYPE ... AS ENUM ` only for small, stable sets; evolving business values get ` TEXT ` + ` CHECK ` or a lookup table. \n- **JSONB** over JSON, indexed with GIN, for optional/semi-structured attributes only. \n- Arrays, ranges, network, geometric, full-text, domain, composite, and vector types, plus TOAST storage and collation control: see ` references/details.md `.\n\n \n\n### Types to avoid\n\n    Avoid Use instead     ` timestamp ` (without time zone) ` timestamptz `   ` char(n) `, ` varchar(n) ` ` text ` (+ ` CHECK ` on length if needed)   ` money ` ` numeric `   ` timetz ` ` timestamptz `   ` timestamptz(0) ` or any precision ` timestamptz `   ` serial ` ` generated always as identity `    \n\n## Constraints\n\n \n\n- **PK**: implicit UNIQUE + NOT NULL; creates a B-tree index. \n- **FK**: specify ` ON DELETE/UPDATE ` (` CASCADE `, ` RESTRICT `, ` SET NULL `, ` SET DEFAULT `). Index the referencing column. Use ` DEFERRABLE INITIALLY DEFERRED ` for circular dependencies checked at commit. \n- **UNIQUE**: creates a B-tree index; allows multiple NULLs unless ` NULLS NOT DISTINCT ` (PG15+). Prefer ` NULLS NOT DISTINCT ` unless duplicate NULLs are wanted. \n- **CHECK**: row-local; NULL passes (three-valued logic). Combine with ` NOT NULL `: ` price NUMERIC NOT NULL CHECK (price > 0) `. \n- **EXCLUDE**: prevents overlaps with operators, e.g. ` EXCLUDE USING gist (room_id WITH =, booking_period WITH &&) ` stops double-booking. Needs a GiST-capable type.\n\n \n\n## Indexing\n\n \n\n- **B-tree**: default for equality/range (` = `, ` < `, ` > `, ` BETWEEN `, ` ORDER BY `). \n- **Composite**: leftmost-prefix rule (` WHERE a = ? AND b > ? ` uses ` (a,b) `; ` WHERE b = ? ` does not). Most selective columns first. \n- **Covering**: ` CREATE INDEX ON tbl (id) INCLUDE (name, email) ` for index-only scans. \n- **Partial**: hot subsets, ` CREATE INDEX ON tbl (user_id) WHERE status = 'active' `. \n- **Expression**: ` CREATE INDEX ON tbl (LOWER(email)) `; the query must use the same expression. \n- **GIN**: JSONB containment/existence, arrays, full-text search. **GiST**: ranges, geometry, exclusion constraints. \n- **BRIN**: large, naturally ordered data (time-series) at minimal storage cost; effective when disk order correlates with the indexed column.\n\n \n\n## Partitioning\n\n \n\n- Use for large tables (\\>100M rows) whose queries consistently filter on the partition key, or where maintenance (pruning, bulk replacement) follows a key. \n- **RANGE** for time-series (` PARTITION BY RANGE (created_at) `; **TimescaleDB** automates it with retention and compression), **LIST** for discrete values, **HASH** for even distribution without a natural key. \n- **Constraint exclusion**: the planner prunes partitions through their ` CHECK ` constraints; declarative partitioning (PG10+) creates them for you. \n- Prefer declarative partitioning or hypertables. Do NOT use table inheritance. \n- **Limitations**: no global UNIQUE constraints—include the partition key in PK/UNIQUE. FKs from partitioned tables need PG11+, FKs referencing a partitioned table need PG12+; on older versions, use triggers.\n\n \n\n## Examples\n\n \n\n```\nCREATE TABLE users (\n  user_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  email TEXT NOT NULL UNIQUE,\n  name TEXT NOT NULL,\n  created_at TIMESTAMPTZ NOT NULL DEFAULT now()\n);\nCREATE UNIQUE INDEX ON users (LOWER(email));\nCREATE INDEX ON users (created_at);\n```\n\n \n\n```\nCREATE TABLE orders (\n  order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n  user_id BIGINT NOT NULL REFERENCES users(user_id),\n  status TEXT NOT NULL DEFAULT 'PENDING' CHECK (status IN ('PENDING','PAID','CANCELED')),\n  total NUMERIC(10,2) NOT NULL CHECK (total > 0),\n  created_at TIMESTAMPTZ NOT NULL DEFAULT now()\n);\nCREATE INDEX ON orders (user_id);\nCREATE INDEX ON orders (created_at);\n```\n\n \n\n```\n-- JSONB attributes with a generated, indexable scalar\nCREATE TABLE profiles (\n  user_id BIGINT PRIMARY KEY REFERENCES users(user_id),\n  attrs JSONB NOT NULL DEFAULT '{}',\n  theme TEXT GENERATED ALWAYS AS (attrs->>'theme') STORED\n);\nCREATE INDEX profiles_attrs_gin ON profiles USING GIN (attrs);\n```\n\n \n\n## Going deeper\n\n \n\n` references/details.md ` holds the material this file only names:\n\n \n\n- The full data-type catalog: TOAST storage, collations, arrays, ranges, network, geometric, text search, domains, composites, vectors. \n- Table types (` TEMPORARY `, ` UNLOGGED `) and row-level security. \n- Constraint and index notes, and partitioning DDL for RANGE, LIST, and HASH. \n- Workload patterns: update-heavy, insert-heavy, upsert design, safe schema evolution. \n- Generated columns and extensions (` pg_trgm `, ` citext `, ` timescaledb `, ` postgis `, ` pgvector `, and more). \n- JSONB indexing strategies, including ` jsonb_path_ops ` and extracted B-tree columns.\n\n \n\n## Files\n\n \n\n- ` LICENSE ` \n- ` SKILL.md ` \n- ` SOURCE.md ` \n- ` references/details.md `\n\n \n\n## Related terms\n\n \n\n- [Document / NoSQL Database](<https://delaparra-services.nl/knowledge-hub/document-nosql-database>) \n- [Globally Distributed SQL](<https://delaparra-services.nl/knowledge-hub/globally-distributed-sql>) \n- [Managed Cache](<https://delaparra-services.nl/knowledge-hub/managed-cache>) \n- [Managed Database (SQL/Relational)](<https://delaparra-services.nl/knowledge-hub/managed-database-sqlrelational>)\n\n \n\n[Installing an agent skill in Claude Code, Codex, Cursor and Copilot](<https://delaparra-services.nl/manuals/een-skill-installeren-in-je-ai-assistent>)\n\n[HTML version](https://delaparra-services.nl/skills/postgresql-table-design)\n",
    "structured_data": {
        "@context": "https://schema.org",
        "@graph": [
            {
                "@type": "Organization",
                "@id": "https://delaparra-services.nl/#practice",
                "logo": "https://delaparra-services.nl/logo.png",
                "name": "DeLaParra Services",
                "legalName": "DeLaParra Services",
                "url": "https://delaparra-services.nl/",
                "description": "Bespoke software, web applications and mobile apps, developed in Laravel by a single developer in Groningen. Fixed price agreed in advance, full source code provided upon delivery.",
                "email": "info@delaparra-services.nl",
                "address": {
                    "@type": "PostalAddress",
                    "addressLocality": "Groningen",
                    "addressRegion": "Groningen",
                    "addressCountry": "NL"
                },
                "areaServed": "Groningen, the Netherlands",
                "knowsLanguage": [
                    "en",
                    "nl"
                ],
                "knowsAbout": [
                    "Web design and development",
                    "App development",
                    "Custom software and web applications",
                    "OpenSpec",
                    "AI code review",
                    "Your own coding agent"
                ],
                "founder": {
                    "@id": "https://delaparra-services.nl/#person"
                }
            },
            {
                "@type": "WebPage",
                "@id": "https://delaparra-services.nl/skills/postgresql-table-design#webpage",
                "url": "https://delaparra-services.nl/skills/postgresql-table-design",
                "name": "PostgreSQL Table Design | DeLaParra Services",
                "description": "Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features",
                "isPartOf": {
                    "@id": "https://delaparra-services.nl/#website"
                },
                "about": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "inLanguage": "en",
                "breadcrumb": {
                    "@id": "https://delaparra-services.nl/skills/postgresql-table-design#breadcrumb"
                }
            },
            {
                "@type": "BreadcrumbList",
                "@id": "https://delaparra-services.nl/skills/postgresql-table-design#breadcrumb",
                "itemListElement": [
                    {
                        "@type": "ListItem",
                        "position": 1,
                        "name": "Home",
                        "item": "https://delaparra-services.nl/"
                    },
                    {
                        "@type": "ListItem",
                        "position": 2,
                        "name": "PostgreSQL Table Design"
                    }
                ]
            },
            {
                "@type": "Person",
                "@id": "https://delaparra-services.nl/#person",
                "name": "Reinier de la Parra",
                "url": "https://delaparra-services.nl/about"
            },
            {
                "@type": "SoftwareSourceCode",
                "@id": "https://delaparra-services.nl/skills/postgresql-table-design#skill",
                "url": "https://delaparra-services.nl/skills/postgresql-table-design",
                "name": "PostgreSQL Table Design",
                "description": "Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features",
                "inLanguage": "en",
                "license": "https://spdx.org/licenses/MIT.html",
                "subjectOf": {
                    "@id": "https://delaparra-services.nl/skills/postgresql-table-design#dataset"
                }
            },
            {
                "@type": "Dataset",
                "@id": "https://delaparra-services.nl/skills/postgresql-table-design#dataset",
                "name": "PostgreSQL Table Design",
                "description": "Use this skill when designing or reviewing a PostgreSQL-specific schema. Covers best-practices, data types, indexing, constraints, performance patterns, and advanced features",
                "url": "https://delaparra-services.nl/skills/postgresql-table-design",
                "identifier": "https://delaparra-services.nl/skills/postgresql-table-design#dataset",
                "about": {
                    "@id": "https://delaparra-services.nl/skills/postgresql-table-design#skill"
                },
                "creditText": "wshobson/agents",
                "publisher": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "license": "https://spdx.org/licenses/MIT.html",
                "isAccessibleForFree": true,
                "inLanguage": "en",
                "dateModified": "2026-11-28T14:00:12+00:00",
                "isPartOf": {
                    "@type": "Dataset",
                    "@id": "https://delaparra-services.nl/knowledge-hub#skills",
                    "name": "Skills for AI coding assistants",
                    "url": "https://delaparra-services.nl/knowledge-hub"
                },
                "includedInDataCatalog": {
                    "@type": "DataCatalog",
                    "@id": "https://delaparra-services.nl/knowledge-hub#catalog",
                    "name": "Knowledge hub data catalog",
                    "url": "https://delaparra-services.nl/knowledge-hub"
                },
                "distribution": [
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design.csv",
                        "encodingFormat": "text/csv",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design.csv",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design.json",
                        "encodingFormat": "application/json",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design.json",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design.md",
                        "encodingFormat": "text/markdown",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design.md",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design.pdf",
                        "encodingFormat": "application/pdf",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design.pdf",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design.zip",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "postgresql-table-design-files.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/skills/postgresql-table-design/download",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:12+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    }
                ]
            }
        ]
    }
}