Name computed fields
A query selects a computed SQL value such as a lowercased column and needs a predictable result property.
Drizzle ORM · Module
Drizzle ORM’s .as() helper assigns an explicit alias to a selected field or SQL expression. It is useful for naming computed fields clearly, especially in complex queries.
The .as() helper assigns an explicit alias to a selected field, making computed expressions easier to identify in query results. It is especially useful for complex SQL expressions where the generated field name would otherwise be unclear.
sql<T>`expression`.as('alias_name')| Name | Type | Description |
|---|---|---|
alias_name | string | The string to use as the selected field's alias. |
A SQL expression representing the aliased field.
.as() when a selected field needs a deliberate, explicit name..as() to name its selected result.sql<T> affects TypeScript typing only; it does not transform the value returned at runtime.import { sql } from "drizzle-orm";
const lowerName = sql<string>`lower(${users.name})`.as("lower_name");Creates a SQL expression whose selected result is named lower_name.
A query selects a computed SQL value such as a lowercased column and needs a predictable result property.
A complex projection contains custom expressions whose generated names are unclear.
.as() solve?.as("name") gives a selected column or SQL expression an explicit result alias. For example, a lowercased name can be selected as lower_name.
Follow-up: How would you alias a computed expression? Use sql<T> for the expression and call .as() on the resulting SQL object.
.as() particularly useful?It makes custom selected fields clearer and more readable by controlling the name exposed in the query result. This is useful when an expression does not have a meaningful default field name.
Follow-up: What should be checked when using a typed SQL expression? Verify that the TypeScript type matches the database value because sql<T> does not perform runtime mapping.
A SQL expression can be aliased with a call such as sql<string>0lower(${users.name}).as("lower_name"). The generated SQL uses the corresponding AS alias.
Follow-up: How can the alias be used in a larger query? Select the aliased expression as a field in the query projection and reference the resulting property by its chosen name.
sql`` operatorsql<T>SQL Select