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
Use this skill for performing CRUD operations with dynamic filters or vector similarity search in a PostgreSQL database.
Avoid this skill for simple static queries where raw SQL is fine, or when using an ORM would be more maintainable.
Security analysis
SafeThe 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 madeExamples
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.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.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
- Import
queryfrom@/lib/database - Use parameterized queries with
$1,$2, etc. - Build dynamic queries safely
- Handle results with proper typing
- Include error handling
Parameters
table- Target table nameoperation- SELECT, INSERT, UPDATE, DELETEfilters- Dynamic filter conditionsincludes_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
- Always use parameterized queries - Never concatenate user input
- Use ILIKE for case-insensitive search - Better UX
- Limit results - Always include a LIMIT clause
- Index key columns - Ensure filters use indexed columns
- Handle NULL values - Use COALESCE when needed
- 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 filesThis 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.mdFrom 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.
React Hook Form Best Practices
Development
Master React Hook Form: avoid anti-patterns, manage subscriptions, and handle reset, dirty state, and controlled inputs correctly.
Emotion to Mantine Migration
Development
Migrate Emotion styled-components to Mantine components with style props and CSS modules. Use when converting .styled.tsx files or removing @emotion imports.
Scope Creep Detector
Development
Analyzes git diffs against a stated intent to detect scope creep, unrelated files, broad PRs, and oversized changes, then suggests keep, split, or justify actions.