AI
50 AI Prompts for PostgreSQL and SQL Query Development
50 AI prompts for PostgreSQL database development. Covers schema design, complex queries, window functions, full-text search, indexing, partitioning, JSON columns, performance tuning, backups, and Node.js and Python integration.
How to Use These PostgreSQL Prompts
PostgreSQL is the most popular open-source relational database and the default choice for new backend projects in 2026. These 50 prompts cover everything from schema design and complex query writing to performance tuning, partitioning, and production operations. All prompts assume PostgreSQL 16 or later.
For best results, always include your current schema when asking for queries. An AI assistant needs to know your exact table names, column names, and data types to generate correct SQL. Paste the relevant CREATE TABLE statements before the prompt and specify what result you expect in plain English.
Schema Design and Basic Queries (Prompts 1-14)
Prompt 1: Design a PostgreSQL schema for a multi-tenant SaaS application with organisations, users, projects, and tasks. Use a organisations table as the root, add an organisation_id foreign key to all tenant-scoped tables, create indexes for all foreign keys, add created_at and updated_at timestamp columns with default now(), and add a Row Level Security policy on each table that restricts access to the current organisation using a session variable.
Prompt 2: Write a PostgreSQL schema for a link shortener service. Tables: links (id, short_code, destination_url, user_id, created_at, expires_at, is_active), link_clicks (id, link_id, clicked_at, ip_address, user_agent, country_code, referrer). Add appropriate indexes for the most frequent queries: looking up a link by short_code and listing all links for a user. Prompt 3: Create a PostgreSQL migration file that adds a soft delete pattern to an existing users table. Add a deleted_at TIMESTAMP WITH TIME ZONE column defaulting to NULL, create a partial index on id WHERE deleted_at IS NULL for fast active user lookups, and create a view called active_users that shows only non-deleted rows.
- Prompt 4: Write a PostgreSQL query that finds the top 10 users by total order value in the last 30 days. Join users, orders, and order_items tables. Filter orders to the last 30 days. Group by user, sum the order_items quantity * unit_price, and order by total descending. Include users with no recent orders as zero.
- Prompt 5: Create a recursive CTE query that fetches an organisation hierarchy. Given a departments table with id, name, and parent_id, write a recursive WITH query that starts from a root department and returns all descendants with their depth level and path from root to leaf.
- Prompt 6: Write a PostgreSQL query using window functions to calculate a 7-day rolling average of daily revenue. The source is an orders table with created_at and total_amount. Return each date, the daily total, and the 7-day rolling average using AVG() OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW).
- Prompt 7: Create a PostgreSQL full-text search query for a blog posts table. Add a tsvector column generated from the title and body fields (title weighted A, body weighted B), create a GIN index on the tsvector column, and write a search query using to_tsquery that ranks results by ts_rank and highlights matching terms with ts_headline.
- Prompt 8: Write a PostgreSQL query that efficiently paginates using keyset (cursor) pagination. Given a posts table ordered by created_at descending then id descending, write a query that accepts a cursor of (last_seen_created_at, last_seen_id) and returns the next page of 20 results without an OFFSET.
- Prompt 9: Create a PostgreSQL upsert using INSERT ... ON CONFLICT. Insert a new product or update the price and stock if a product with the same sku already exists. Return the full row whether it was inserted or updated using the RETURNING clause.
- Prompt 10: Write a PostgreSQL query that pivots rows into columns. Given a daily_metrics table with metric_name and metric_value columns, produce a result where each metric name becomes a column and each row is a date.
- Prompt 11: Create a PostgreSQL trigger that automatically updates the updated_at column on every UPDATE. Write the trigger function in PL/pgSQL and the trigger definition that fires BEFORE UPDATE on each row.
- Prompt 12: Write a PostgreSQL query using JSONB operators. Given a products table with a metadata JSONB column, query products where metadata contains a specific key, filter by a nested value using the ->> operator, and index the JSONB column with a GIN index for fast containment queries.
- Prompt 13: Create a PostgreSQL lateral join query. For each user, find their most recent 3 orders using LATERAL (SELECT ... FROM orders WHERE user_id = u.id ORDER BY created_at DESC LIMIT 3). Show why LATERAL is needed here instead of a regular subquery.
- Prompt 14: Write a PostgreSQL query using DISTINCT ON to find the latest order per customer. Show how DISTINCT ON (customer_id) with ORDER BY customer_id, created_at DESC returns exactly one row per customer — the most recent — more efficiently than a subquery with MAX.
Performance, Indexing, Partitioning, and Operations (Prompts 15-50)
Prompt 15: Write an EXPLAIN ANALYZE query plan interpretation guide for a slow query. Paste an EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT) output and explain: what each node type means (Seq Scan vs Index Scan vs Bitmap Heap Scan), what the actual rows vs estimated rows difference indicates, what the Buffers hits and reads tell you about cache efficiency, and suggest specific index or query changes to improve it.
Prompt 16: Create a PostgreSQL indexing strategy for a table with 50 million rows. Show when to use a B-tree index, when to use a GIN index for JSONB or array columns, when to use a BRIN index for naturally ordered timestamp columns, how to create indexes CONCURRENTLY to avoid locking the table, and how to identify unused indexes with pg_stat_user_indexes. Prompt 17: Write a PostgreSQL table partitioning setup for a large link_clicks table. Partition by range on the clicked_at column with monthly partitions. Show the parent table definition, how to create child partitions for specific months, how to attach and detach partitions, and how partition pruning automatically skips irrelevant partitions in queries filtered by date.
- Prompt 18: Create a PostgreSQL Row Level Security (RLS) policy for a multi-tenant application. Enable RLS on the projects table, create a policy that allows SELECT only when organisation_id equals the value stored in the app.current_organisation session variable, and show the Node.js code that sets the session variable before running queries.
- Prompt 19: Write a PostgreSQL logical replication setup for zero-downtime migration. Show how to set up a publication on the source database, create a subscription on the target, let replication catch up, then switch the application connection string with zero data loss.
- Prompt 20: Create a PostgreSQL backup strategy using pg_dump and pg_basebackup. Show a daily pg_dump command for logical backup, a pg_basebackup command for a full cluster backup, the pg_restore command to restore a specific table from a dump, and a cron job that rotates backups and deletes those older than 30 days.
- Prompt 21: Write a PostgreSQL connection pooling setup using PgBouncer. Configure PgBouncer in transaction pooling mode, set pool_size to 20 connections, show the pgbouncer.ini configuration for a Node.js application, and explain why connection pooling is necessary for serverless or high-concurrency applications.
- Prompt 22: Create a PostgreSQL extension setup for UUID primary keys using gen_random_uuid(). Add the pgcrypto or uuid-ossp extension, define a table that uses UUID as the primary key with a default value, and show the trade-offs of UUID versus serial integer primary keys for distributed inserts and index fragmentation.
- Prompt 23: Write a PostgreSQL advisory lock pattern for a distributed application. Use pg_try_advisory_lock with a hash of a job ID to ensure only one application instance processes a specific job at a time, release the lock when the job completes, and handle the case where the lock is already held by returning without processing.
- Prompt 24: Create a Node.js PostgreSQL connection setup using node-postgres (pg). Configure a connection pool with max 10 connections, set a connection timeout and query timeout, add an error handler for idle client errors, use the pool.query method for simple queries, and use pool.connect for transactions that need to hold a client for multiple queries.
- Prompt 25: Write a Python PostgreSQL connection setup using asyncpg for async access. Create a connection pool on application startup, write an async query function that fetches rows as dict-like records, handle connection errors with retry logic, and close the pool on application shutdown.
FAQ
When should I use PostgreSQL instead of a NoSQL database?
Use PostgreSQL when your data has relationships (users have orders, orders have items), when you need complex queries with JOINs and aggregations, when ACID transactions are important (financial records, inventory), or when you need full-text search. Use a NoSQL database like MongoDB when your data is document-shaped with no fixed schema, when you need horizontal sharding at massive scale, or when you are storing denormalised data for maximum read performance. For most business applications, PostgreSQL is the correct default.
How do I speed up slow PostgreSQL queries?
Start with EXPLAIN (ANALYZE, BUFFERS) to see the query plan. Look for Seq Scans on large tables — these usually need an index. Check estimated vs actual row counts: large discrepancies mean stale statistics, run ANALYZE. Add indexes on columns used in WHERE, JOIN, and ORDER BY clauses. Avoid SELECT * and fetch only needed columns. Use LIMIT early. For complex reports, consider materialised views. If the query is fundamentally slow due to data volume, consider partitioning or pre-aggregation.
What is the difference between JSONB and JSON in PostgreSQL?
JSON stores the text exactly as inserted, preserving whitespace and key order. JSONB decomposes and stores the JSON in binary format, removes whitespace, and does not preserve key order or duplicate keys. JSONB is almost always the right choice because it supports GIN indexing (JSON does not), allows fast containment queries (@>, ?), and has lower parsing overhead on read. Use JSON only if you need to preserve the exact original text including whitespace and duplicate keys.
How many connections can PostgreSQL handle?
Each PostgreSQL connection is a separate OS process using around 5-10MB of memory. The default max_connections is 100. With 1GB RAM on the database server you can comfortably support 20-50 active connections. Beyond that, use PgBouncer as a connection pooler — it keeps a small number of PostgreSQL connections and multiplexes thousands of application connections onto them. For serverless applications with many concurrent Lambda functions, PgBouncer or AWS RDS Proxy is mandatory to avoid exhausting PostgreSQL connections.
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.