rawAs
The rawAs
function allows you to inject a raw SQL expression and assign it an alias in your query. This is useful for computed columns or advanced SQL expressions that need to be referenced by name.
Usage
import { qb } from 'hypequery';
qb('orders')
.select([
'id',
qb.rawAs('SUM(amount)', 'total_amount')
])
.groupBy(['id'])
.toSQL();
// SELECT id, SUM(amount) AS total_amount FROM orders GROUP BY id
Parameters
expression: string
– The raw SQL string. You can use?
placeholders for parameterized values.alias: string
– The alias to assign to the expression.params?: any[]
– (Optional) Array of values to safely interpolate into the SQL string.
Examples
Aggregations with Aliases
qb('orders')
.select([
'user_id',
qb.rawAs('SUM(total)', 'total_spent'),
qb.rawAs('COUNT(*)', 'order_count')
])
.groupBy(['user_id'])
.toSQL();
// SELECT user_id, SUM(total) AS total_spent, COUNT(*) AS order_count FROM orders GROUP BY user_id
Computed Columns
qb('users')
.select([
'id',
qb.rawAs('CONCAT(first_name, \' \', last_name)', 'full_name'),
qb.rawAs('YEAR(created_at)', 'join_year')
])
.toSQL();
// SELECT id, CONCAT(first_name, ' ', last_name) AS full_name, YEAR(created_at) AS join_year FROM users
Referencing Aliased Columns
qb('orders')
.select([
'user_id',
qb.rawAs('SUM(total)', 'total_spent'),
qb.rawAs('COUNT(*)', 'order_count'),
qb.rawAs('AVG(total)', 'avg_order')
])
.groupBy(['user_id'])
.having(qb.raw('total_spent > 1000'))
.orderBy(qb.raw('total_spent DESC'))
.toSQL();
// SELECT user_id, SUM(total) AS total_spent, COUNT(*) AS order_count, AVG(total) AS avg_order
// FROM orders GROUP BY user_id HAVING total_spent > 1000 ORDER BY total_spent DESC
Complex Aggregations
qb('sales')
.select([
'product_id',
qb.rawAs('SUM(quantity)', 'total_quantity'),
qb.rawAs('SUM(quantity * price)', 'total_revenue'),
qb.rawAs('AVG(price)', 'avg_price'),
qb.rawAs('COUNT(DISTINCT customer_id)', 'unique_customers')
])
.groupBy(['product_id'])
.having(qb.raw('total_revenue > 10000'))
.toSQL();
// SELECT product_id, SUM(quantity) AS total_quantity, SUM(quantity * price) AS total_revenue,
// AVG(price) AS avg_price, COUNT(DISTINCT customer_id) AS unique_customers
// FROM sales GROUP BY product_id HAVING total_revenue > 10000
Notes
- Use
rawAs
with caution. It bypasses automatic escaping and type safety for the injected SQL. - Prefer query builder methods when possible for safety and maintainability.
- Aliased columns can be referenced in
having()
,orderBy()
, and other clauses using the alias name.