ShortIQ

ShortIQ

AI

50 AI Prompts for PostgreSQL: Queries, Indexes, and Schema Design

Developer-tested AI prompts for writing PostgreSQL queries, designing schemas, creating indexes, writing migrations, debugging slow queries, and working with advanced features like CTEs, window functions, and JSONB.

July 2, 2026ShortIQ Editorial Team

Why AI Prompts Work Well for PostgreSQL

SQL is one of the most structured languages in software development — it has strict syntax, predictable output formats, and well-defined semantics. This makes it an excellent target for AI generation: given a clear description of the data and the result you want, AI produces accurate SQL reliably. The challenge is giving the AI enough context. Without your schema, AI generates SQL for hypothetical tables that do not match yours.

The prompts in this guide follow one rule: always include the relevant schema. Paste the CREATE TABLE statements for the tables involved in the query before describing what you want. AI produces dramatically more accurate SQL with the actual column names, types, and constraints than it does from a description alone.

  • Always paste the CREATE TABLE definitions before asking for a query
  • Specify PostgreSQL explicitly — AI defaults to generic SQL that may not work on Postgres
  • Include sample data for complex queries so AI can verify the expected output
  • Ask for EXPLAIN ANALYZE output interpretation alongside query generation
  • Request index recommendations alongside the queries that need them

Schema Design and Table Structure Prompts

Good PostgreSQL schema design uses proper data types (UUID for IDs, timestamptz for timestamps, not varchar for everything), foreign key constraints with appropriate ON DELETE behavior, and indexes on columns used in WHERE clauses and JOIN conditions. AI generates well-structured schemas when you describe the entity, its relationships, and the queries you need to run against it.

These prompts generate CREATE TABLE statements with constraints, check constraints, default values, and index creation statements. Specify whether you are using Supabase (which has auth.users and RLS concerns), Prisma (which generates its own migrations), or raw PostgreSQL.

text
Act as a PostgreSQL schema design expert.

Task:
Design the database schema for a multi-tenant SaaS billing system.

Entities needed:
- tenants: id, name, slug (unique), plan (free/pro/enterprise),
  created_at, is_active
- users: id, tenant_id (FK), email (unique per tenant), role,
  created_at, last_login_at
- subscriptions: id, tenant_id (FK), plan_name, status
  (active/cancelled/past_due), current_period_start, current_period_end,
  stripe_subscription_id (unique)
- invoices: id, tenant_id (FK), subscription_id (FK), amount_cents,
  currency, status (paid/unpaid/void), due_date, paid_at

Requirements:
- Use UUID primary keys with gen_random_uuid() default
- All timestamps must be timestamptz
- Add CHECK constraints for enum-like columns (plan, status, role)
- Add appropriate foreign key ON DELETE behavior
- Add indexes for all FK columns and frequently queried columns
- Include a unique constraint for email scoped to tenant_id

Output: complete SQL migration file

Complex Query Prompts: JOINs, CTEs, and Aggregations

CTEs (Common Table Expressions) make complex multi-step queries readable by breaking them into named sub-queries. Window functions compute running totals, ranks, and moving averages without collapsing rows. These are two of the most powerful PostgreSQL features that developers underuse because the syntax is unfamiliar. AI generates accurate CTEs and window functions when given the schema and the expected output format.

These prompts generate complex analytical queries for reporting, dashboards, and data aggregation. Include the schema and describe the output columns and grouping logic precisely.

text
Act as a PostgreSQL expert specializing in analytical queries.

Schema:
[paste your CREATE TABLE statements here]

Task:
Write a PostgreSQL query for this dashboard metric:

Monthly Revenue Report:
- Group invoices by year and month
- Show: year_month, total_revenue_cents, invoice_count,
  paying_tenant_count, avg_invoice_value_cents
- Include only invoices with status = 'paid'
- Add a running_total_cents column (cumulative revenue month over month)
- Add a mom_growth_pct column (month-over-month percentage growth)
- Order by year_month ascending
- Show the last 12 months only

Use: CTEs for readability, window functions for running total and MoM growth
Explain each CTE step in a comment above it

Index Design and Query Performance Prompts

PostgreSQL supports B-tree, GIN, GIST, BRIN, and partial indexes. Most queries need B-tree indexes on columns in WHERE, JOIN ON, and ORDER BY clauses. JSONB columns need GIN indexes for fast key/value lookups. Partial indexes (CREATE INDEX ... WHERE condition) are smaller and faster than full-table indexes when only a subset of rows is queried.

These prompts generate index recommendations for specific query patterns and interpret EXPLAIN ANALYZE output to identify missing indexes, sequential scans on large tables, and hash join vs nested loop trade-offs.

text
Act as a PostgreSQL performance expert.

Task:
Recommend indexes for these frequently-run queries on our database.

Schema:
[paste your CREATE TABLE statements here]

Queries that are slow (each runs thousands of times per day):
1. SELECT * FROM orders WHERE tenant_id = $1 AND status = 'pending'
   ORDER BY created_at DESC LIMIT 50;

2. SELECT user_id, COUNT(*) as order_count, SUM(total_cents) as revenue
   FROM orders WHERE created_at > NOW() - INTERVAL '30 days'
   GROUP BY user_id ORDER BY revenue DESC;

3. SELECT * FROM products WHERE metadata @> '{"category": "electronics"}'
   AND is_active = true;

For each index:
- Write the CREATE INDEX statement
- Explain which query it helps and why
- Estimate the index type (B-tree, GIN, partial)
- Note any trade-offs (index size, write overhead)

JSONB and Advanced PostgreSQL Feature Prompts

PostgreSQL JSONB column type stores semi-structured data with full indexing support. JSONB supports operators for containment (@>), key existence (?), and path navigation (->>, #>>). These operators have unfamiliar syntax that AI handles well when given examples of the data structure and the query goal.

These prompts also cover PostgreSQL-specific features like full-text search with tsvector, recursive CTEs for tree structures, LATERAL JOINs, and generated columns. Specify the PostgreSQL version (14, 15, 16, 17) since some features are version-specific.

text
Act as a PostgreSQL JSONB and full-text search expert.

Schema:
CREATE TABLE articles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  title TEXT NOT NULL,
  body TEXT NOT NULL,
  metadata JSONB DEFAULT '{}',
  search_vector TSVECTOR GENERATED ALWAYS AS (
    to_tsvector('english', title || ' ' || body)
  ) STORED,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

Sample metadata structure:
{"tags": ["tech", "ai"], "author_id": "uuid", "reading_time": 5, "published": true}

Tasks:
1. Find all published articles tagged with 'ai' OR 'ml', ordered by relevance to
   the search term 'neural network'

2. Return the top 5 tags by article count across all published articles
   (tags is a JSONB array)

3. Create the optimal GIN index for full-text search on search_vector
   and another GIN index for JSONB metadata queries

Use: PostgreSQL 16, explain the tsvector and tsquery operators used

Database Migration and Maintenance Prompts

Zero-downtime migrations are critical for production PostgreSQL databases. Adding a NOT NULL column to a large table without a default value locks the table. Adding a column with a constant default in PostgreSQL 11+ is instant. Adding a foreign key without NOT VALID first locks both tables. AI knows these patterns when you specify that you need a zero-downtime migration.

These prompts generate safe migration scripts, VACUUM and ANALYZE commands for maintenance, pg_stat_user_tables queries for monitoring table bloat, and pg_stat_statements queries for identifying slow queries in production.

text
Act as a PostgreSQL production operations expert.

Task:
Write a zero-downtime migration to add a new column to a large table.

Table: orders (50 million rows, high write volume, cannot be locked)
Change: add column fulfillment_status TEXT NOT NULL DEFAULT 'pending'
        with a CHECK constraint: ('pending', 'shipped', 'delivered', 'cancelled')

Constraints:
- The migration must not lock the table for more than a few milliseconds
- The application must continue writing to the table during migration
- The column must have a NOT NULL constraint after migration is complete
- PostgreSQL version: 15

Provide:
1. The safe migration steps in order with explanation for each
2. The SQL for each step
3. How to verify each step completed successfully
4. How to roll back if something goes wrong

FAQ

What is the best way to use AI for writing PostgreSQL queries?

Always paste the CREATE TABLE statements for the tables involved before asking for a query. AI generates dramatically more accurate SQL with the actual schema than with a description alone. Specify PostgreSQL explicitly, include sample data for complex queries, and ask for an explanation of the query alongside the SQL so you can verify the logic.

Can AI write CTEs and window functions?

Yes. AI handles CTEs and window functions well when given the schema and a clear description of the expected output. Describe the columns you want, the grouping logic, and any running totals or rankings. The prompt in Section 3 shows the structure for asking for CTEs with window function columns like running totals and month-over-month growth.

Can AI recommend PostgreSQL indexes?

Yes. Paste the schema and the slow queries, and ask AI to recommend indexes with the index type and the reason each one helps. Also ask AI to interpret EXPLAIN ANALYZE output — paste the output of EXPLAIN (ANALYZE, BUFFERS) and AI identifies sequential scans on large tables, missing indexes, and suboptimal join strategies.

How do I prompt AI for a zero-downtime PostgreSQL migration?

Specify that the migration must not lock the table, the table size and write volume, and the PostgreSQL version. Ask for the migration steps in order with rollback instructions. AI knows the safe patterns: adding columns with defaults, using NOT VALID for new foreign keys, and building indexes with CREATE INDEX CONCURRENTLY.

Can AI help with PostgreSQL JSONB queries?

Yes. Show a sample JSONB structure and describe the query goal. AI generates the correct JSONB operators (@>, ?, ->>, #>>) and recommends the appropriate GIN index. The JSONB operator syntax is non-obvious, making it one of the highest-value areas to use AI for PostgreSQL.

What PostgreSQL features are best to use AI for?

The highest-value uses are: complex analytical queries with CTEs and window functions, JSONB operators and GIN indexes, full-text search with tsvector, zero-downtime migration planning, and EXPLAIN ANALYZE interpretation. These are all areas where the syntax is correct but non-obvious, and where AI with the right schema context produces working code reliably.

Do these prompts work with MySQL or SQLite?

Most prompts work for MySQL and SQLite with minor syntax differences. Specify your database system in the prompt. PostgreSQL-specific features like JSONB, tsvector, CTEs with MATERIALIZED hint, and gen_random_uuid() are not available in MySQL or SQLite. AI adapts the query when you specify the target database.

Related free tools

If you want to turn this topic into action, use one of ShortIQ's free tools for campaign planning, UTM structure, or QR distribution.

Continue Reading

Explore more guides on link shortener SaaS strategy, Bitly alternatives, and white label link management.

Free newsletter

Get new guides in your inbox

We publish practical guides on dev tooling, prompt engineering, marketing workflows, and deployment. No fluff — straight to the point.

No spam. Unsubscribe any time.

Was this article helpful?

Tell us if this guide solved the problem or what was still missing. We use this to improve the blog and only follow up if you explicitly allow it.

We use this to improve tutorials, examples, and technical depth.