Optimized PostgreSQL Queries

VerifiedSafe

Write safe, optimized PostgreSQL queries with parameterized filters, proper joins, and pg-vector support for similarity search. Helps build efficient database interactions in the portfolio project using dynamic query building and error handling.

Sby Skills Guide Bot
DevelopmentIntermediate
6/2/2026
Claude CodeCursorWindsurf
#postgresql#pgvector#query-building#parameterized-queries#dynamic-queries

Recommended for

Automated summary

Create optimized PostgreSQL queries for the portfolio database, including parameterized queries, joins, and pg-vector operations.

Strengths

  • Secure parameterized queries prevent SQL injection
  • Dynamic filter construction enables flexible query building
  • Vector search support for similarity and hybrid queries
  • Error handling with proper TypeScript typing

Limitations

  • Requires familiarity with the project's database schema
  • Can become verbose for very complex query logic
  • Does not cover all edge cases of dynamic query generation
When to use it

Use this skill for performing CRUD operations with dynamic filters or vector similarity search in a PostgreSQL database.

When not to use it

Avoid this skill for simple static queries where raw SQL is fine, or when using an ORM would be more maintainable.

Security analysis

Safe
Quality score90/100

The skill focuses on safe, parameterized SQL query patterns and does not instruct execution of destructive commands, data exfiltration, or disabling security features. It promotes best practices like avoiding string concatenation.

No concerns found

How this analysis is made

Examples

Dynamic experience query with filters
Generate a PostgreSQL query to select experiences from the database with optional filters on company name (ILIKE), position, and start year, using the project's parameterized query pattern.
Hybrid search with vector and full-text
Create a hybrid search query that combines pg-vector similarity and full-text search to find content chunks, ranking by a combined score with weights 0.3 for text rank and 0.7 for vector similarity.
Join query with skills aggregation
Write a query to fetch experiences along with their associated skills, using a LEFT JOIN and aggregating skills into a JSON array, sorted by start date descending.

Database Query

Create optimized PostgreSQL queries for the portfolio database.

Description

Write safe, optimized PostgreSQL queries using the project's database patterns. Includes parameterized queries, proper joins, and pg-vector operations.

Instructions

  1. Import query from @/lib/database
  2. Use parameterized queries with $1, $2, etc.
  3. Build dynamic queries safely
  4. Handle results with proper typing
  5. Include error handling

Parameters

  • table - Target table name
  • operation - SELECT, INSERT, UPDATE, DELETE
  • filters - Dynamic filter conditions
  • includes_vector - Whether using pg-vector operations

Basic Query Pattern

import { query } from '@/lib/database';

// Simple SELECT
const results = await query(
  'SELECT * FROM experiences WHERE id = $1',
  [experienceId]
);

// INSERT with RETURNING
const inserted = await query(
  `INSERT INTO experiences (company, position, start_date)
   VALUES ($1, $2, $3)
   RETURNING *`,
  [company, position, startDate]
);

// UPDATE
await query(
  `UPDATE experiences 
   SET company = $1, position = $2, updated_at = NOW()
   WHERE id = $3`,
  [company, position, id]
);

// DELETE
await query(
  'DELETE FROM experiences WHERE id = $1',
  [id]
);

Dynamic Query Builder

interface ExperienceFilters {
  company?: string;
  position?: string;
  startYear?: number;
  technology?: string;
  limit?: number;
}

async function getExperiences(filters: ExperienceFilters) {
  const params: any[] = [];
  let sql = 'SELECT * FROM experiences WHERE 1=1';
  
  if (filters.company) {
    sql += ` AND company ILIKE $${params.length + 1}`;
    params.push(`%${filters.company}%`);
  }
  
  if (filters.position) {
    sql += ` AND position ILIKE $${params.length + 1}`;
    params.push(`%${filters.position}%`);
  }
  
  if (filters.startYear) {
    sql += ` AND EXTRACT(YEAR FROM start_date) = $${params.length + 1}`;
    params.push(filters.startYear);
  }
  
  if (filters.technology) {
    sql += ` AND $${params.length + 1} = ANY(technologies)`;
    params.push(filters.technology);
  }
  
  sql += ' ORDER BY start_date DESC';
  
  if (filters.limit) {
    sql += ` LIMIT $${params.length + 1}`;
    params.push(filters.limit);
  }
  
  return query(sql, params);
}

Vector Search Query

import { query } from '@/lib/database';

// Find similar content using pg-vector
async function findSimilarContent(embedding: number[], limit = 5) {
  return query(
    `SELECT 
       id, 
       content, 
       metadata,
       1 - (embedding <=> $1::vector) as similarity
     FROM content_chunks
     WHERE embedding IS NOT NULL
     ORDER BY embedding <=> $1::vector
     LIMIT $2`,
    [`[${embedding.join(',')}]`, limit]
  );
}

// Hybrid search (vector + full-text)
async function hybridSearch(searchText: string, embedding: number[]) {
  return query(
    `SELECT 
       id,
       content,
       ts_rank(search_vector, plainto_tsquery($1)) as text_rank,
       1 - (embedding <=> $2::vector) as vector_similarity,
       (ts_rank(search_vector, plainto_tsquery($1)) * 0.3 + 
        (1 - (embedding <=> $2::vector)) * 0.7) as combined_score
     FROM content_chunks
     WHERE search_vector @@ plainto_tsquery($1)
        OR embedding <=> $2::vector < 0.5
     ORDER BY combined_score DESC
     LIMIT 10`,
    [searchText, `[${embedding.join(',')}]`]
  );
}

Join Queries

// Get experiences with related skills
async function getExperiencesWithSkills() {
  return query(`
    SELECT 
      e.*,
      COALESCE(
        json_agg(
          json_build_object('name', s.skill_name, 'category', s.category)
        ) FILTER (WHERE s.id IS NOT NULL),
        '[]'
      ) as skills
    FROM experiences e
    LEFT JOIN experience_skills es ON e.id = es.experience_id
    LEFT JOIN skills s ON es.skill_id = s.id
    GROUP BY e.id
    ORDER BY e.start_date DESC
  `);
}

Error Handling

async function safeQuery<T>(
  sql: string,
  params: any[] = []
): Promise<{ data: T[] | null; error: Error | null }> {
  try {
    const result = await query(sql, params);
    return { data: result as T[], error: null };
  } catch (error) {
    console.error('Database query error:', error);
    return { data: null, error: error as Error };
  }
}

Best Practices

  1. Always use parameterized queries - Never concatenate user input
  2. Use ILIKE for case-insensitive search - Better UX
  3. Limit results - Always include a LIMIT clause
  4. Index key columns - Ensure filters use indexed columns
  5. Handle NULL values - Use COALESCE when needed
  6. Type your results - Use TypeScript interfaces

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/optimized-postgresql-queries-mma3js0y/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/optimized-postgresql-queries-mma3js0y' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/optimized-postgresql-queries-mma3js0y/download' --output '.skill-downloads/optimized-postgresql-queries-mma3js0y/SKILL.md.part' && mv '.skill-downloads/optimized-postgresql-queries-mma3js0y/SKILL.md.part' '.skill-downloads/optimized-postgresql-queries-mma3js0y/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

This file does not provide a usable name/description header for this native procedure. It remains available to download and inspect; use the manual method below.

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/optimized-postgresql-queries-mma3js0y/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills