Overview
Drizzle provides thesql template tag for writing raw SQL expressions while maintaining type safety and proper parameter binding. This allows you to:
- Extend the query builder: Add functionality not yet supported by Drizzle
- Use database-specific features: Leverage PostgreSQL, MySQL, or SQLite functions
- Build dynamic expressions: Construct complex WHERE clauses and calculations
- Maintain type safety: Specify return types for SQL expressions
The SQL Template Tag
Basic Usage
Use thesql template tag for raw SQL:
Type Safety
Specify the return type of SQL expressions:Parameter Binding
Drizzle automatically handles parameter binding:Common Patterns
String Functions
Date and Time Functions
Mathematical Operations
JSON Operations
Array Operations
Advanced Techniques
Window Functions
Perform complex analytical queries:Common Table Expressions (CTEs)
Build complex queries with WITH clauses:Subqueries
Embed queries within queries:CASE Expressions
Conditional logic in SQL:Dynamic Operators
Build conditional WHERE clauses:Database-Specific Functions
PostgreSQL
MySQL
SQLite
Combining with Query Builder
WHERE Clauses
Mix SQL expressions with Drizzle operators:ORDER BY
Custom sorting logic:HAVING Clauses
Filter aggregated results:Using SQL.raw
Raw SQL Execution
Execute completely custom SQL:Performance Considerations
SQL expressions are sent directly to the database, so their performance depends on your SQL syntax and database optimization.
Indexing
Ensure expressions can use indexes:Query Planning
Use EXPLAIN to understand query performance:Type Inference
Aliasing SQL Expressions
Create reusable typed expressions:MapWith for Custom Decoding
Transform values returned from the database:Best Practices
1
Use sql for database-specific features
Don’t reinvent the wheel - leverage your database’s capabilities.
2
Always specify types
Use
sql<Type> to maintain type safety in your application.3
Prefer query builder when possible
Only use raw SQL when the query builder doesn’t support your use case.
4
Test SQL expressions
Raw SQL isn’t validated at compile time, so write tests.
5
Document complex expressions
Add comments explaining what your SQL expressions do.