Master Parameterized SQL Queries for Dynamic Data Analysis
Writes secure, flexible parameterized SQL queries: optional filters, multi-value params, dynamic sorting, and BI cascading.
Maintainer of this project? Claim this page to edit the listing.
1.0.0Add to Favorites
Why it matters
Develop secure, efficient, and flexible parameterized SQL queries for business intelligence and data analysis. This skill enables dynamic filtering, conditional logic, and reusable data access patterns across various SQL databases and BI platforms.
Outcomes
What it gets done
Implement static, dynamic, optional, multi-value, and date-range parameters.
Prevent SQL injection and optimize query performance with parameter binding and caching.
Handle hierarchical and cascading parameter dependencies for complex data filtering.
Design parameterized queries for period-over-period comparisons and dynamic sorting.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/vb-query-parameterization | bash Overview
Query Parameterization Specialist
Provides secure, performant parameterized SQL query patterns for optional filters, multi-value and hierarchical parameters, and BI reporting. Use when designing parameterized queries with optional filters, building BI cascading filters, or optimizing parameter-sensitive query performance.
What it does
Provides expert guidance for query parameterization in business intelligence and data analysis - creating flexible, secure, performant parameterized queries for dynamic filtering, conditional logic, and reusable data access across SQL databases and BI platforms.
When to use - and when NOT to
Use this skill when designing parameterized queries with optional filters, building multi-value or hierarchical (cascading) parameters for BI reports, implementing dynamic sorting or conditional joins, or optimizing parameter-sensitive query performance. Not a fit for static, single-purpose queries with no runtime variability, or for NoSQL query patterns outside SQL parameter binding.
Inputs and outputs
Defines six parameter types: static (fixed at execution), dynamic (changes query structure/logic), optional (may be null/empty), multi-value (arrays for IN clauses), date range, and hierarchical (cascading dependencies). Security and performance principles require proper parameter binding to prevent SQL injection, parameter validation/sanitization, optimized query plans, execution plan caching, and graceful NULL/empty handling.
Shows basic parameter binding syntax for PostgreSQL/MySQL ($1, $2) and SQL Server (@param) styles, optional parameter handling via COALESCE or explicit IS NULL OR conditional logic, and multi-value parameters via SQL Server's STRING_SPLIT or PostgreSQL array parameters with = ANY(). Dynamic query construction covers conditional JOIN logic toggled by boolean flags, and parameterized dynamic ORDER BY using CASE expressions per sort field/direction combination.
BI-specific patterns include hierarchical parameter cascading (region to country to city) using a CTE to pre-filter locations, and period-over-period comparison queries computing current vs. previous period sums and growth percentage with a division-by-zero guard. Advanced techniques cover parameter validation with defaults (e.g. defaulting a date range to the last month, clamping an invalid end date to the start date) and performance-optimized handling using OPTION (RECOMPILE) for highly variable filter parameters.
Best practices cover parameter naming and documentation (descriptive names, documented types/ranges/defaults, consistent prefixes), query structure (placing parameter checks early in WHERE clauses, preferring EXISTS over IN for large lists, temp tables for complex multi-value processing), testing/maintenance (testing NULL/empty/boundary values, monitoring performance across parameter combinations, parameter logging), and BI tool integration (matching parameter design to tool capabilities like Tableau/Power BI, consistent formats across reports, cascading filter UX).
Integrations
Covers PostgreSQL, MySQL, and SQL Server parameter binding syntax, with BI tool integration guidance for Tableau and Power BI-style parameter and cascading filter design.
Who it's for
Data analysts and BI developers building parameterized SQL queries and reports who need concrete patterns for optional filters, multi-value/hierarchical parameters, and performance tuning rather than static hardcoded queries.
WHERE (@category_filter IS NULL OR category = @category_filter)
AND (@min_price IS NULL OR price >= @min_price)
Source README
Query Parameterization Expert
You are an expert in query parameterization for business intelligence and data analysis. You specialize in creating flexible, secure, and performant parameterized queries that enable dynamic filtering, conditional logic, and reusable data access patterns across SQL databases, reporting tools, and BI platforms.
Core Principles
Parameter Types and Scope
- Static Parameters: Fixed values passed at execution time
- Dynamic Parameters: Values that change query structure or logic
- Optional Parameters: Parameters that may be null or empty
- Multi-value Parameters: Arrays or lists for IN clauses
- Date Range Parameters: Start/end dates with proper handling
- Hierarchical Parameters: Cascading parameter dependencies
Security and Performance
- Always use proper parameter binding to prevent SQL injection
- Implement parameter validation and sanitization
- Optimize query plans for parameterized execution
- Cache execution plans when possible
- Handle NULL and empty parameter values gracefully
SQL Parameterization Patterns
Basic Parameter Binding
-- PostgreSQL/MySQL style
SELECT customer_id, order_date, total_amount
FROM orders
WHERE customer_id = $1
AND order_date >= $2
AND order_date <= $3;
-- SQL Server style
SELECT customer_id, order_date, total_amount
FROM orders
WHERE customer_id = @customer_id
AND order_date >= @start_date
AND order_date <= @end_date;
Optional Parameter Handling
-- Handle optional filters with COALESCE
SELECT product_id, product_name, category, price
FROM products
WHERE category = COALESCE(@category_filter, category)
AND price >= COALESCE(@min_price, 0)
AND price <= COALESCE(@max_price, price);
-- Alternative with conditional logic
SELECT product_id, product_name, category, price
FROM products
WHERE (@category_filter IS NULL OR category = @category_filter)
AND (@min_price IS NULL OR price >= @min_price)
AND (@max_price IS NULL OR price <= @max_price);
Multi-Value Parameters
-- Using STRING_SPLIT for comma-separated values (SQL Server)
SELECT o.order_id, o.customer_id, o.total_amount
FROM orders o
WHERE (@status_list IS NULL
OR o.status IN (SELECT value FROM STRING_SPLIT(@status_list, ',')))
-- PostgreSQL array parameter
SELECT o.order_id, o.customer_id, o.total_amount
FROM orders o
WHERE ($1::text[] IS NULL OR o.status = ANY($1::text[]));
Dynamic Query Construction
Conditional JOIN Logic
-- Base query with optional JOINs
SELECT
c.customer_id,
c.customer_name,
CASE WHEN @include_orders = 1 THEN o.order_count ELSE NULL END as order_count,
CASE WHEN @include_revenue = 1 THEN o.total_revenue ELSE NULL END as total_revenue
FROM customers c
LEFT JOIN (
SELECT
customer_id,
COUNT(*) as order_count,
SUM(total_amount) as total_revenue
FROM orders
WHERE (@date_filter = 0 OR order_date >= @start_date)
GROUP BY customer_id
) o ON (@include_orders = 1 OR @include_revenue = 1) AND c.customer_id = o.customer_id
WHERE (@region_filter IS NULL OR c.region = @region_filter);
Dynamic Sorting
-- Parameterized ORDER BY
SELECT product_id, product_name, price, created_date
FROM products
WHERE category = @category
ORDER BY
CASE WHEN @sort_field = 'name' AND @sort_direction = 'ASC' THEN product_name END ASC,
CASE WHEN @sort_field = 'name' AND @sort_direction = 'DESC' THEN product_name END DESC,
CASE WHEN @sort_field = 'price' AND @sort_direction = 'ASC' THEN price END ASC,
CASE WHEN @sort_field = 'price' AND @sort_direction = 'DESC' THEN price END DESC,
CASE WHEN @sort_field = 'date' AND @sort_direction = 'ASC' THEN created_date END ASC,
CASE WHEN @sort_field = 'date' AND @sort_direction = 'DESC' THEN created_date END DESC;
Business Intelligence Patterns
Hierarchical Parameter Cascading
-- Region -> Country -> City cascade
WITH filtered_locations AS (
SELECT location_id, region, country, city
FROM locations
WHERE (@region IS NULL OR region = @region)
AND (@country IS NULL OR country = @country)
AND (@city IS NULL OR city = @city)
)
SELECT
s.sale_id,
s.sale_amount,
l.region,
l.country,
l.city
FROM sales s
JOIN filtered_locations l ON s.location_id = l.location_id
WHERE s.sale_date BETWEEN @start_date AND @end_date;
Period-over-Period Comparisons
-- Flexible period comparison
WITH period_data AS (
SELECT
product_id,
SUM(CASE WHEN sale_date BETWEEN @current_start AND @current_end
THEN sale_amount ELSE 0 END) as current_period,
SUM(CASE WHEN sale_date BETWEEN @previous_start AND @previous_end
THEN sale_amount ELSE 0 END) as previous_period
FROM sales
WHERE sale_date BETWEEN @previous_start AND @current_end
AND (@product_category IS NULL OR product_category = @product_category)
GROUP BY product_id
)
SELECT
product_id,
current_period,
previous_period,
CASE WHEN previous_period > 0
THEN ((current_period - previous_period) / previous_period) * 100
ELSE NULL END as growth_percentage
FROM period_data
WHERE (@min_current_sales IS NULL OR current_period >= @min_current_sales);
Advanced Parameterization Techniques
Parameter Validation and Defaults
-- Input validation and default handling
DECLARE @validated_start_date DATE = COALESCE(@start_date, DATEADD(month, -1, GETDATE()));
DECLARE @validated_end_date DATE = CASE
WHEN @end_date IS NULL THEN GETDATE()
WHEN @end_date < @validated_start_date THEN @validated_start_date
ELSE @end_date
END;
SELECT order_id, customer_id, order_date, total_amount
FROM orders
WHERE order_date BETWEEN @validated_start_date AND @validated_end_date;
Performance-Optimized Parameter Handling
-- Use OPTION (RECOMPILE) for highly variable parameters
SELECT customer_id, order_count, total_spent
FROM customer_summary
WHERE (@dynamic_filter = 0
OR (@filter_type = 'high_value' AND total_spent > @threshold)
OR (@filter_type = 'frequent' AND order_count > @min_orders)
OR (@filter_type = 'recent' AND last_order_date > @recent_date))
OPTION (RECOMPILE);
Best Practices and Recommendations
Parameter Naming and Documentation
- Use descriptive parameter names (e.g.,
@sales_region_filternot@param1) - Document parameter data types, valid ranges, and default behaviors
- Group related parameters with consistent prefixes
- Include parameter validation in stored procedures
Query Structure Guidelines
- Place parameter checks early in WHERE clauses for performance
- Use EXISTS instead of IN for better performance with large parameter lists
- Consider using temp tables for complex multi-value parameter processing
- Implement proper NULL handling throughout the query logic
Testing and Maintenance
- Test queries with NULL, empty, and boundary value parameters
- Monitor query performance across different parameter combinations
- Use query hints judiciously for parameter-sensitive queries
- Implement parameter logging for troubleshooting and optimization
Integration with BI Tools
- Design parameters to match BI tool capabilities (Tableau, Power BI, etc.)
- Use consistent parameter formats across related reports
- Implement parameter dependencies and cascading filters appropriately
- Consider user experience when designing multi-parameter interfaces
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.