Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Passing a single string will group by that one column.
You can also pass a list of column names. A single comma (","
) will be used as the delimiter.
An array of column names can be provided.
Calling groupBy
multiple times will to the current groups.
An Expression
can be passed in place of a column.
Adds a having clause to a query.
Expressions
can be used in place of the column or the value.
Adds a where clause to a query.
Any of the following operators can be used in a where clause.
When using the "="
constraint, you can use a shortcut and define the value as the second argument.
To group where statements together, pass a function to the where clause as the only parameter.
This grouping can be nested as many levels as you require.
A Function or QueryBuilder can be used as a subselect expression when passed to value
.
Adds a where between clause to the query.
If a function or QueryBuilder is passed it is used as a subselect expression.
Adds a where clause to a query that compares two columns.
Just as with where
, when using "="
as the operator you can use a shorthand passing the second column in as the operator and leaving the second column null
.
Expressions
can be passed in place of either column.
Adds a where exists clause to the query.
It can be configured with a function.
It can also be configured with a QueryBuilder instance.
Adds a where in clause to the query.
The values passed to whereIn
can be a single value, a list of values, or an array of values.
Some database grammars have a hard limit on the number of parameters passed to a SQL statement. Keep this in mind while writing your queries.
If a list of values is passed in, it is converted to an array of values using a single comma (","
) delimiter.
Expressions
can be freely mixed in with other values.
A function or QueryBuilder instance can be passed to be used as a subquery expression instead of a list of values.
You may find a whereExists
method performs better for you than a whereIn
with a subquery.
Shorthand to add a raw SQL statement to the where clauses.
Adds a where null clause to the query.
qb uses onMissingMethod
to provide a few different helpers when working with where...
methods.
Every where...
method in qb can be called prefixed with either and
or or
. Doing so will call the original method using the corresponding combinator.
If you call a method starting with where
that does not match an existing qb method, qb will instead call the where
method using the rest of the method name as the first column name. (The rest of the arguments will be shifted to account for this.) This also applies to andWhere{Column}
and orWhere{Column}
method signatures.
Join clauses range from simple to complex including joining complete subqueries on multiple conditions. qb has your back with all of these use cases.
Applies a join to the query. The simplest join is to a table based on two columns:
When doing a simple join using =
as the operator, you can omit it and pass just the column names:
Using raw
will most likely tie your code to a specific database, so think carefully before using the raw
method if you want your project to be database agnostic.
When you need to specify more clauses to join, you can pass a function as the second argument:
Conditions inside a join clause can be grouped using a function.
Adds a join to another table based on a WHERE
clause instead of an ON
clause. WHERE
clauses introduce parameters and parameter bindings whereas on
clauses join between columns and don't need parameter bindings.
For simple joins, this specifies a column on which to join the two tables:
Using joinRaw
will most likely tie your code to a specific database, so think carefully before using the joinRaw
method if you want your project to be database agnostic.
Alternatively, a function may be used to define the derived table:
Complex join conditions are also possible by passing a function as the third parameter:
Using leftJoinRaw
will most likely tie your code to a specific database, so think carefully before using the leftJoinRaw
method if you want your project to be database agnostic.
Using rightJoinRaw
will most likely tie your code to a specific database, so think carefully before using the rightJoinRaw
method if you want your project to be database agnostic.
Uses the raw SQL provided to as the table for the cross join clause. Cross joins cannot be further constrained with on
or where
clauses.
Using crossJoinRaw
will most likely tie your code to a specific database, so think carefully before using the crossJoinRaw
method if you want your project to be database agnostic.
Applies a join condition to the JoinClause
. An alias for whereColumn
.
Applies a join condition to the JoinClause
using an or
combinator. An alias for orWhereColumn
.
You can optionally configure qb to ignore duplicate joins. With this setting turned on each JoinClause
is inspected and checked if it matches any existing JoinClause
instances on the query. This is useful if you have a table shared between optional constraints and want to ensure it is only added once.
You can opt-in to this behavior by setting preventDuplicateJoins = true
in your moduleSettings
in config/ColdBox.cfc
.
Used to set the base table for the query.
You can optionally specify an alias for the table.
An alias for from
where you like how calling table
looks.
Sometimes you need more control over your from
clause in order to add grammar specific instructions, such as adding SQL Server table hints to your queries.
Since the fromRaw()
takes your string verbatim, it's important that you make sure your SQL declaration is escaped properly. Failure to properly escape your table names may result in SQL errors.
Using fromRaw
will most likely tie your code to a specific database, so think carefully before using the fromRaw
method if you want your project to be database agnostic.
Many database engines allow you to define User Defined Functions. For example, SQL Server allows you to define UDFs that will return a table. In these type of cases, it may be necessary to bind parameters to your from
clause.
You can bind parameters to the fromRaw()
method by passing a secondary argument that is an array of the parameters to bind.
Complex queries often contain derived tables. Derived tables are essentially a temporal table defined as a subquery in the from
statement.
In additional a function callback, a separate QueryBuilder
instance can be passed to the fromSub
method.
You may not always want to select all columns from a database table. You can influence the select list of a query with the following methods.
Individual columns can contain fully-qualified names (some_table.some_column
), table aliases (alias.some_column
), and even set column aliases themselves (some_column AS c
). The columns
argument can be a single column, a list of columns (comma-separated), or an array of columns.
When calling select
any previous columns are discarded. If you want to incrementally select columns, use the addSelect
method.
If you pass no columns to this method, it will default to "*"
.
Calling distinct will cause the query to be executed with the DISTINCT
keyword.
distinct
applies to the entire query, not just certain fields.
This method adds the columns passed to it to the currently selected columns.
If the QueryBuilder
is currently selecting all columns ("*"
) when this method is called, the incoming columns will becoming the only columns selected.
A shortcut to use a raw expression in the select clause.
The expression is added to the other already selected columns.
The method lets you pass either a callback or a QueryBuilder
instance to be used as a subselect expression. If a callback is passed it will be passed a new query instance as the only parameter.
The subselect is added to the other already selected columns.
Clears out the selected columns for a query along with any configured select bindings.
Clears out the selected columns for a query along with any configured select bindings. Then adds an Expression or array of expressions to the already selected columns.
The orderBy
method seems simple but has a lot of depth depending on the type of arguments you pass in.
Calling orderBy
multiple times appends to the order list.
Calling orderBy
multiple times will append to the order list.
You can order with a subquery using either a function or a QueryBuilder instance.
qb includes a few methods to help you lock certain rows when executing select
statements.
Note: For locks to work properly, they must be nested inside a transaction
. qb does not handle any of the transaction lifecycle for you.
A shared lock prevents the selected rows from being modified until your transaction is committed.
A lock for update lock prevents the selected rows from being modified or selected with another shared lock until your transaction is committed.
The main difference between a sharedLock
and lockForUpdate
is that a lockForUpdate
prevents other reads or selects as well as updates.
noLock
will instruct your grammar to ignore any shared locks when executing the query.
Currently this only makes a difference in SQL Server grammars.
The lock
method will allow you to add a custom lock directive to your query. Think of it as the raw
method for lock directives.
These lock directives vary from grammar to grammar.
Clears any lock directive on the query.
The query builder also lets you create union statements on your queries using either UNION
or UNION ALL
strategies.
The union
methods take either a Query Builder instance or a closure which you use to define a new QueryBuilder instance.
Union statements are added in the order in which the union
methods are invoked, but the union
statements can be in any order in your API call stack. This means you can safely declare your union
method calls before the select
, from
and orderBy
calls on the source Query Builder instance.
union()
— This method builds a SQL statement using the UNION
clause which combines two SQL queries into a single result set containing all the matching rows. The two queries must have the same defined columns and compatible data types or the SQL engine will generate an error. The union
clause only returns unique rows.
unionAll()
— This builds a SQL statement using the UNION ALL
clause. This is the same as union
but includes duplicate rows.
IMPORTANT: The QueryBuilder instances passed to a union
statement cannot contain a defined order. Any use of the orderBy()
method on the unioned QueryBuilder instances will result in an OrderByNotAllowed
exception. To order the results, add an orderBy()
call to the parent source Query Builder instance.
Adds a UNION statement to the query.
Adding multiple union statements will append it to the query.
It can also add union queries as QueryBuilder instances.
Adds a UNION ALL statement to the query.
Adding multiple unionAll
statements will append it to the query.
It can also add union queries as QueryBuilder instances.
Using the where
method will parameterize the value
passed. If you want to constrain a column to another column, use the method.
You can also pass an as the value.
You may also use statements to simplify this further.
This method is simply an alias for with the combinator set to "and"
.
This method is simply an alias for with the combinator set to "or"
.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
A shortcut for calling with "like"
set as the operator.
A shortcut for calling with "not like"
set as the operator.
Any value in the list or array can also be passed using a to have more control over the parameter settings.
Adds a where not in clause to the query. This behaves identically to the whereIn
method with the negate
flag set to true
. See the documentation for for usage and examples.
Adds a where not in clause to the query. This behaves identically to the method with the negate
flag set to true
. See the documentation for for usage and examples.
`` are also supported as the table
argument (though you may prefer the readability of the method):
You can specify clauses in your joins as well.
A preconfigured can also be passed to the join function. This allows you to extract shared pieces of code out to different functions.
For complex joins, a function can be passed to first
. This allows multiple on
and where
conditions to be applied to the join. See the documentation for for more information.
Uses the raw SQL provided to as the table for the join clause. All the other functionality of joinRaw
matches the method. Additionally, there are , , and crossJoinRaw
methods available.
Adds a join to a derived table. All the functionality of the method applies to constrain the query. The derived table can be defined using a QueryBuilder
instance:
Uses the raw SQL provided to as the table for the left join clause. All the other functionality of leftJoinRaw
matches the method.
Adds a left join to a derived table. All the functionality of the method applies to define and constrain the query.
Uses the raw SQL provided to as the table for the right join clause. All the other functionality of rightJoinRaw
matches the method.
Adds a right join to a derived table. All the functionality of the method applies to define and constrain the query.
Adds a cross join to a derived table. The derived table can be defined using a QueryBuilder
instance or a function just as with . Cross joins cannot be constrained, however.
Creates a new . A is a specialized version of a QueryBuilder
. You may call on
or orOn
to constrain the . You may also call any methods.
Creating a directly is useful when you need to share a join between different queries. You can create and configure the in a function and pass it to queries as needed.
Although a can be passed to , , , and crossJoin
, the type of the will override the type of the function.
A JoinClause
is a specialized version of a QueryBuilder
. You may call on
or orOn
to constrain the JoinClause
. You may also call any methods.
(To learn more about raw and expressions, check out the docs on .)
Clears out the selected columns for a query along with any configured select bindings. Then sets a selection of columns to select from the query. Any valid argument to can be passed here.
This method combines forPage
, count
, and get
to create a pagination struct alongside the results. Information on the simplePaginate
or paginate
methods, including custom pagination collectors, can be found in the section of the documentation.
You can also provide an .
Clears the currently configured orders for the query. Usually used by downstream libraries like .
Clears the currently configured orders for the query and sets the new orders passed in. Any valid argument to can be passed here. Usually used by downstream libraries like .
Name
Type
Required
Default
Description
groups
string | array
true
A single column name, a list of column names, or an array of column names to group by. An Expression
can be passed as well.
Name
Type
Required
Default
Description
column
string | Expression
true
The name of the column or Expression
with which to constrain the query.
operator
any
false
The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the operator
and the value
left null as a shortcut for equals (e.g. where( "column", 1 ) == where( "column", "=", 1 ) ).
value
any
false
The value with which to constrain the column. An Expression
can be passed as well.
combinator
string
false
"and"
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andHaving
and orHaving
methods instead.
Valid Operators |
= | < | > |
<= | >= | <> |
!= | like | like binary |
not like | between | ilike |
& | | | ^ |
<< | >> | rlike |
regexp | not regexp | ~ |
~* | !~ | !~* |
similar to | not similar to |
Name | Type | Required | Default | Description |
operator | string |
|
| The boolean operator for the join clause. |
where | boolean |
|
| Sets if the value of |
Name | Type | Required | Default | Description |
operator | string |
|
| The boolean operator for the join clause. |
where | boolean |
|
| Sets if the value of |
Name | Type | Required | Default | Description |
Name | Type | Required | Default | Description |
table | string |
| ​ | The raw SQL string to use as the table. |
Name | Type | Required | Default | Description |
alias | string |
| The alias for the derived table. |
input | Function | QueryBuilder |
| ​ | Either a |
Name | Type | Required | Default | Description |
from | string |
| ​ | The sql snippet to use as the table. |
bindings | array |
|
| Any bindings needed for the expression. |
Name | Type | Required | Default | Description |
alias | string |
| ​ | The alias for the derived table. |
input | Function | QueryBuilder |
| Either a |
Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to add to the select. |
Name | Type | Required | Default | Description |
expression | any |
| ​ | The raw expression for the select statement. |
bindings | array |
|
| Any bindings needed for the raw expression. |
Name | Type | Required | Default | Description |
alias | string |
| ​ | The alias for the subselect expression. |
query | Function | QueryBuilder |
| The callback or query to use in the subselect. |
Name | Type | Required | Default | Description |
No arguments | `` |
Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to retrieve. |
Name | Type | Required | Default | Description |
expression | any |
| ​ | The raw expression for the select statement. |
bindings | array |
|
| Any bindings needed for the raw expression. |
Name | Type | Required | Default | Description |
value | numeric |
| The offset value for the query. |
Name | Type | Required | Default | Description |
page | numeric |
| The page number to retrieve. |
maxRows | numeric |
| The number of records per page. If a number less than 0 is passed, 0 is used instead. |
Name | Type | Required | Default | Description |
column | any |
| The list of the columns to order by. Each column can optionally declare it's sort direction after a pipe delimiter. (e.g. `"height | desc"`). |
direction | string |
|
| The direction by which to order the query. Accepts |
Name | Type | Required | Default | Description |
column | any |
| The array of the columns to order by. Each column can optionally declare it's sort direction after a pipe delimiter. (e.g. `"height | desc"`). |
direction | string |
|
| The direction by which to order the query. Accepts |
Name | Type | Required | Default | Description |
column | any |
| The array of the columns to order by. Each column can optionally declare it's sort direction using a struct. The struct should have a column key and an optional direction key. (e.g. |
direction | string |
|
| The direction by which to order the query. Accepts |
Name | Type | Required | Default | Description |
expression | string |
| The raw SQL expression to use. |
bindings | array |
|
| Any bindings ( |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
value | string |
| The custom lock directive to add to the query. |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
input | Function | QueryBuilder |
| The function or QueryBuilder instance to use as the unioned query. |
Name | Type | Required | Default | Description |
from | string | Expression |
| ​ | The name of the table or a Expression object from which the query is based. |
Name | Type | Required | Default | Description |
table | string | Expression |
| ​ | The name of the table or a Expression object from which the query is based. |
Name | Type | Required | Default | Description |
columns | string | array |
| ​ | A single column, list of columns, or array of columns to retrieve. |
Name | Type | Required | Default | Description |
state | boolean |
| ​ | Value to set the distinct flag. |
Name | Type | Required | Default | Description |
value | numeric |
| The limit value for the query. |
Name | Type | Required | Default | Description |
value | numeric |
| The limit value for the query. |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
No arguments |
Name | Type | Required | Default | Description |
input | Function | QueryBuilder |
| The function or QueryBuilder instance to use as the unioned query. |
all | boolean |
|
| Determines if statement should be a "UNION ALL". Passing this as an argument is discouraged. Use the dedicated |
Table of Contents |
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
Name | Type | Required | Default | Description |
column |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
value | any |
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
start | any | Function | QueryBuilder |
| The beginning value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
end | any | Function | QueryBuilder |
| The end value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
combinator | string |
|
|
negate | boolean |
|
| False for BETWEEN, True for NOT BETWEEN. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
start | any | Function | QueryBuilder |
| The beginning value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
end | any | Function | QueryBuilder |
| The end value of the BETWEEN statement. If a function or QueryBuilder is passed it is used as a subselect expression. |
combinator | string |
|
|
Name | Type | Required | Default | Description |
first |
|
operator |
| The operator to use for the constraint (i.e. "=", "<", ">=", etc.). A value can be passed as the |
second | string | Expression |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
query | Function | QueryBuilder |
| A function or QueryBuilder instance to be used as the exists subquery. |
combinator | string |
|
|
negate | boolean |
|
| False for EXISTS, True for NOT EXISTS. |
Name | Type | Required | Default | Description |
query | Function | QueryBuilder |
| A function or QueryBuilder instance to be used as the not exists subquery. |
combinator | string |
|
|
Name | Type | Required | Default | Description |
column |
|
value | any |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column |
|
value | any |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
values |
|
combinator | string |
|
|
negate | boolean |
|
| False for IN, True for NOT IN. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
values |
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
sql | string |
| The raw SQL to add to the query. |
whereBindings | array |
|
|
combinator | string |
|
|
Name | Type | Required | Default | Description |
column | string | Expression |
|
combinator | string |
|
|
negate | boolean |
|
| False for NULL, True for NOT NULL. |
Name | Type | Required | Default | Description |
column | string | Expression |
|
combinator | string |
|
|
negate | boolean |
|
| False for NULL, True for NOT NULL. |
Table of Contents |
Name | Type | Required | Default | Description |
table |
| ​ |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
type | string |
|
|
where | boolean |
|
|
Name | Type | Required | Default | Description |
table | string |
| ​ | The raw SQL string to use as the table. |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
type | string |
|
|
Name | Type | Required | Default | Description |
table | string |
| ​ | The raw SQL string to use as the table. |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
type | string |
|
|
where | boolean |
|
| Sets if the value of |
Name | Type | Required | Default | Description |
alias | string |
| The alias for the derived table. |
input | Function | QueryBuilder |
| ​ | Either a |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
type | string |
|
|
where | boolean |
|
| Sets if the value of |
table |
| ​ |
first | string | Expression | Function |
|
second |
|
Name | Type | Required | Default | Description |
table | string |
| ​ | The raw SQL string to use as the table. |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
where | boolean |
|
| Sets if the value of |
Name | Type | Required | Default | Description |
alias | string |
| The alias for the derived table. |
input | Function | QueryBuilder |
| ​ | Either a |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
where | boolean |
|
| Sets if the value of |
table |
| ​ |
first |
|
second |
|
Name | Type | Required | Default | Description |
table | string |
| ​ | The raw SQL string to use as the table. |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
where | boolean |
|
| Sets if the value of |
Name | Type | Required | Default | Description |
alias | string |
| The alias for the derived table. |
input | Function | QueryBuilder |
| ​ | Either a |
first |
|
operator | string |
|
| The boolean operator for the join clause. |
second |
|
where | boolean |
|
| Sets if the value of |
table |
| ​ |
Name | Type | Required | Default | Description |
table |
| ​ |
type | string |
|
| The type of the join. Valid types are |
Name | Type | Required | Default | Description |
first |
|
operator | string |
|
| The boolean operator for the condition. |
second |
|
combinator | string |
|
| The boolean combinator for the clause (e.g. "and" or "or"). |
Name | Type | Required | Default | Description |
first |
|
operator | string |
|
| The boolean operator for the condition. |
second |
|
Name | Type | Required | Default | Description |
column | any |
|
direction | string |
|
| The direction by which to order the query. Accepts |
Name | Type | Required | Default | Description |
column | any |
|
direction | string |
|
| Ignored when using a Function or QueryBuilder instance. |
Name | Type | Required | Default | Description |
column | any |
|
direction | string |
|
| The direction by which to order the query. Accepts |
When passing a parameter to qb, it will infer the sql type to be used. If you pass a number, CF_SQL_NUMERIC
will be used. If it is a date, CF_SQL_TIMESTAMP
, and so forth. If you need more control, you can pass a struct with the parameters you would pass to cfqueryparam
.
You can pass include any parameters you would use with cfqueryparam
including null
, list
, etc. This applies anywhere parameters are used including where
, update
, and insert
methods.
This can be used when inserting or updating records as well.
By default, qb will try to determine if a variable is a date using the built-in isDate
function. This can have some interesting effects with different formatted strings. You can opt in to stricter date detection which will check the underlying Java class of the value to determine if the value is a date. This is more accurate, but does require you to specifically pass date instances instead of strings. For this reason, it is currently opt-in to not break existing applications. It is likely to become the default in the next major version of qb.
You can opt in to stricter date detection by setting strictDateDetection = true
in your moduleSettings
in config/ColdBox.cfc
.
By default, qb will use the CF_SQL_NUMERIC
SQL type when it detects a numeric binding. You can specify your own default SQL type to use with numeric values using the numericSQLType
setting in your moduleSettings
in config/ColdBox.cfc
.
In some combinations of database grammars and CFML engines, the scale
argument on a cfqueryparam
would default to 0
. This would cause issues when attempting to insert a floating point number, even when using the correct SQL type (i.e., CF_SQL_DECIMAL
) . In 8.5.0, qb now automatically calculates a scale based on the value provided if the value is a floating point number. This can be disabled by setting autoAddScale
in your ColdBox config or passing autoAddScale = false
when instantiating your QueryBuilder
instance.
Bindings are the values that will be sent as parameters to a prepared SQL statement. This protects you from SQL injection. In CFML, this uses cfqueryparam
to parameterize the values.
If you need to inspect the bindings for the current query you can retrieve them in order using the getBindings
method.
You can view the current SQL for the query with bindings inline for debugging purposes using the toSQL
method.
Use these methods only for debugging. Modifying the bindings directly will likely cause issues when executing your query. Adding or removing bindings should be done using the public API.
This method returns the current bindings in order to be used for the query.
You can also retrieve the bindings associated to their corresponding types.
This method returns the current bindings to be used for the query associated to their corresponding types.
Raw expressions are the qb escape hatch. While qb strives to provide ways to execute the majority of queries, you will occasionally need to provide raw sql values that are not processed by qb. These SQL snippets are called raw
or Expressions
in qb.
raw
expressions are useful, but should be used only if there is not another way to accomplish the same action using other qb methods. This is because a raw
expression has the potential to use syntax specific to one database grammar or another, preventing you from easily switching from one grammar to another, one of the major benefits of using qb.
The first way to retrieve an Expression
is to call the raw
method on the QueryBuilder
object.
Name | Type | Required | Default | Description |
---|---|---|---|---|
The sql snippet passed to raw
is not processed by qb at all. With that in mind, it is important to follow all best practices and security recommendations with the sql you use with raw
.
Expressions can be passed to most qb methods, like select
, from
, where
, or orderBy
, among others. Additionally, qb provides some convenience methods to add raw values in different parts of the query:
Common Table Expressions (CTEs) are powerful SQL concept that allow you to create re-usable temporal result sets, which can be referenced as a table within your SQL. CTEs are available in many common database engines and are available in latest versions of all of the support grammars.
CTEs come in two basic types:
Non-recursive — These are statements that do not reference themselves, in simplified terms they are like a derived table that can be referenced by a user-defined name.
Recursive — Recursive CTEs reference themselves and are generally used for creating hierarchical data—such as creating a parent/child relationship within a table.
While all of the grammars currently support CTEs, there is enough difference between the various databases implementations of CTEs that unless your CTEs are fairly basic, using CTEs within your project will most likely tie your project to a specific database, unless you account for the differences in your code.
However, CTEs are can be extremely useful to solve certain use cases.
To add CTEs to your queries, you have two methods available:
with()
— Allows you to define a non-recursive CTE.
withRecursive()
— Allows you to define a recursive CTE.
Some database engines require the recursive
keyword anytime at least one of your CTEs is recursive, but some database engines (e.g. SQL Server and Oracle) do not require the keyword. qb will manage adding the keyword, if necessary. If your query does use recursion you should use the withRecursive()
method to avoid issues when migrating grammars.
You can build a CTE using a function:
Alternatively, you can use a QueryBuilder instance instead of a function:
A single query can reference multiple CTEs:
IMPORTANT — The way the SQL in a recursive CTEs are written, using them in your code is likely to lock in you in to a specific database engine, unless you structure your code to build the correct SQL based on the current grammar being used.
Here is an example of building a recursive CTE using SQL Server which would return all parent/child rows and show their generation/level depth:
If you store the builder object in a variable, you can use if
and else
statements like you would expect.
This works, but breaks chainability. To keep chainability you can use the when
helper method.
when
The when
helper is used to allow conditional statements when defining queries without using if statements and having to store temporary variables.
You can pass a third argument to be called in the else
case.
when
callbacks are automatically scoped and grouped. That means that if a where clause is added inside the callback with an OR
combinator the clauses will automatically be grouped (have parenthesis put around them.) You can disable this feature by passing withoutScoping = true
to the when
callback.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the and methods instead.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
string | | Function
The name of the column or with which to constrain the query. A function can be passed to begin a nested where statement.
string |
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The name of the column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string |
The name of the first column or with which to constrain the query.
string |
The name of the second column or with which to constrain the query.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string |
The name of the column or with which to constrain the query.
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string |
The name of the column or with which to constrain the query.
The value with which to constrain the column. An can be passed as well. If a QueryBuilder or Function is passed, it will be used as a subselect expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
string | array | | Function | QueryBuilder
A single value, list of values, or array of values to constrain a column with. may be used in any place a value is used. Alternatively, a function or QueryBuilder instance can be passed in to be used as a subquery expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column or with which to constrain the query.
string | array | | Function | QueryBuilder
A single value, list of values, or array of values to constrain a column with. may be used in any place a value is used. Alternatively, a function or QueryBuilder instance can be passed in to be used as a subquery expression.
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
Any bindings needed for the raw SQL. Bindings can be simple values or .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column to check if it is NULL. Can also pass an .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
The name of the column to check if it is NULL. Can also pass an .
The boolean combinator for the clause. Valid options are "and"
or "or"
. Avoid passing this parameter explicitly. Where possible use the andWhere
and orWhere
instead.
string | |
The name of the table or a object from which the query is based. Alternatively, a configured instance can be passed.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like and where possible.
Sets if the value of second
should be interpreted as a column or a value. Passing this as an argument is discouraged. Use the dedicated or a join closure where possible.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like and with a join function where possible.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like and where possible.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
The type of the join. Passing this as an argument is discouraged for readability. Use the dedicated methods like and where possible.
string | |
The name of the table or a object from which the query is based. Alternatively, a configured instance can be passed.
(Note: a instance may have a different join type than a left
join. The instance's join type will be used.)
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | |
The name of the table or a object from which the query is based. Alternatively, a configured instance can be passed.
(Note: a instance may have a different join type than a right
join. The instance's join type will be used.)
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | | Function
The first column or to join the table on. Alternatively, a function can be passed to configure complex join statements.
string |
The second column or to join the table on.
string | |
The name of the table or a object from which the query is based. Alternatively, a configured instance can be passed.
(Note: a instance may have a different join type than a cross
join. The instance's join type will be used.)
string |
The name of the table or a object from which the query is based.
string | | Function
The first column or of the condition. Alternatively, a function can be passed to nest conditions with parenthesis.
string |
The second column or of the condition.
string | | Function
The first column or of the condition. Alternatively, a function can be passed to nest conditions with parenthesis.
string |
The second column or of the condition.
The name of the column to order by. An can be passed as well.
The name of the column to order by. An can be passed as well. An array can be passed with any combination of simple values, array, struct, or list for each entry in the array (an example with all possible value styles: column = [ "last_name", [ "age", "desc" ], { column = "favorite_color", direction = "desc" }, "height|desc" ];. The column argument can also just accept a comman delimited list with a pipe ( | ) as the secondary delimiter denoting the direction of the order by. The pipe delimiter is also used when parsing the column argument when it is passed as an array and the entry in the array is a pipe delimited string.
The name of the column to order by. An can be passed as well.
Name
Type
Required
Default
Description
No arguments
Name
Type
Required
Default
Description
No arguments
sql
string
true
The raw sql to wrap up in an Expression.
Name
Type
Required
Default
Description
name
string
true
The name of the CTE.
input
QueryBuilder | Function
true
Either a QueryBuilder instance or a function to define the derived query.
columns
Array<String>
false
[]
An optional array containing the columns to include in the CTE.
recursive
boolean
false
false
Determines if the CTE statement should be a recursive CTE. Passing this as an argument is discouraged. Use the dedicated withRecursive
where possible.
Name
Type
Required
Default
Description
name
string
true
The name of the CTE.
input
QueryBuilder | Function
true
Either a QueryBuilder instance or a function to define the derived query.
columns
Array<String>
false
[]
An optional array containing the columns to include in the CTE.
Name | Type | Required | Default | Description |
condition | boolean | true | The condition to switch on. |
onTrue | Function | true | The callback to execute if the condition is true. It is passed the |
onFalse | Function | false | function( q ) { return q; } | The callback to execute if the conditions is false. It is passed the |
withoutScoping | boolean | false |
| Flag to turn off the automatic scoping of where clauses during the callback. |