Documentation menu

Data

SqlQuery

SqlQuery builds one SQL statement: SELECT (with joins, grouping, sub-queries, CTEs, set operations and window functions), INSERT, UPDATE, DELETE or an upsert. Use it for statements that do not map to one DataStore; for single-table work the DataStore query builder (datastores.md) is shorter. The DataStore query builder uses SqlQuery internally.

Values are bound as ? parameters. Column names given to orderBy(), groupBy() and condition arrays are checked and quoted for the connection's database (MySQL/MariaDB, PostgreSQL, SQLite; SQL Server statements are generated but not tested against a server). Every PHP example below runs as written, in order, against SQLite.

Contents

#

Setup

#

SqlQuery takes a connection. In a Taphra app, DatabaseConnection::load() returns one by name from app/Config/databases.yml: the same connection the DataStores on that name use, also returned by $ds->connectionManager->getConnection().

PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$conn   = DatabaseConnection::load('app_master');
$schema = new SchemaBuilder($conn);

foreach (['orders', 'employees', 'customers'] as $table) {
    $schema->dropIfExists($table);
}
$schema->create('customers', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->string('email')->unique();
    $t->boolean('active')->default(true);
});
$schema->create('orders', function ($t) {
    $t->id();
    $t->integer('customer_id');
    $t->decimal('total', 10, 2);
    $t->string('status', 20)->default('new');
    $t->dateTime('created_at');
});
$schema->create('employees', function ($t) {
    $t->id();
    $t->string('name', 100);
    $t->string('dept', 50);
    $t->integer('salary');
    $t->integer('manager_id')->nullable();
});

$conn->execute("INSERT INTO customers (name, email, active) VALUES ('Ann', '[email protected]', 1), ('Ben', '[email protected]', 1), ('Cy', '[email protected]', 0)");
$conn->execute("INSERT INTO orders (customer_id, total, status, created_at) VALUES
    (1, 120.00, 'paid', '2026-01-05 10:00:00'), (1, 30.50, 'paid', '2026-02-01 09:00:00'),
    (2, 75.00, 'new', '2026-02-03 12:00:00'), (3, 10.00, 'cancelled', '2026-02-04 08:00:00')");
$conn->execute("INSERT INTO employees (name, dept, salary, manager_id) VALUES
    ('Eve', 'eng', 120, NULL), ('Finn', 'eng', 100, 1), ('Gus', 'eng', 90, 2), ('Hal', 'ops', 80, 1)");

SELECT

#
PHP
use Taphra\SqlQuery;

$rows = (new SqlQuery($conn))
    ->select(['id', 'name'])           // a list of columns; select('name', 'alias') sets one column and its alias
    ->from('customers')
    ->fetch(true, false);              // all rows, flat: [['id' => 1, 'name' => 'Ann'], ...]

$one = (new SqlQuery($conn))->select('*')->from('customers')->where(['id' => 1])->fetch(false, false);   // one row

$distinct = (new SqlQuery($conn))->select('status')->distinct()->from('orders')->fetch(true, false);

$totals = (new SqlQuery($conn))
    ->select('customer_id')
    ->selectRaw('SUM(total) AS spent, COUNT(*) AS n')
    ->from('orders')
    ->groupBy('customer_id')
    ->fetch(true, false);

fetch($all, $withAliases): with $withAliases = true (the default) each row is grouped by table name, [['customers' => ['id' => 1, ...]]]; pass false for plain rows.


Conditions

#

where() takes a Criteria, an array, or a raw SQL string. Calling it again ANDs the new conditions.

PHP
use Taphra\Criteria;
use Taphra\SqlQuery;

// Array: column => value, with an optional operator in the key
$rows = (new SqlQuery($conn))->select('*')->from('orders')
    ->where(['status' => 'paid', 'total >=' => 50, 'customer_id in' => [1, 2]])
    ->fetch(true, false);

// Criteria: field, operator, value
$rows = (new SqlQuery($conn))->select('*')->from('orders')
    ->where(new Criteria('status', '!=', 'cancelled'))
    ->where(new Criteria('created_at', '>=', '2026-02-01'))
    ->fetch(true, false);

// Groups: status = 'paid' AND (total > 100 OR customer_id = 2)
$c = new Criteria('status', '=', 'paid');
$c->orGroup(function (Criteria $g) {
    $g->add('total', '>', 100);
    $g->add('customer_id', '=', 2);
});
$rows = (new SqlQuery($conn))->select('*')->from('orders')->where($c)->fetch(true, false);

// BETWEEN, IN, IS NULL
$rows = (new SqlQuery($conn))->select('*')->from('employees')
    ->where(new Criteria('salary', 'BETWEEN', [85, 110]))
    ->where(new Criteria('manager_id', 'IS NOT NULL'))
    ->fetch(true, false);

// A server-side expression as the value: SqlRawExpr is written as SQL, not bound
$rows = (new SqlQuery($conn))->select('*')->from('orders')
    ->where(new Criteria('created_at', '<=', $conn->now()))   // NOW(), datetime('now') or GETDATE()
    ->fetch(true, false);

Allowed operators: =, !=, <>, <, >, <=, >=, <=>, LIKE, NOT LIKE, ILIKE, NOT ILIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, IS, IS NOT, IS NULL, IS NOT NULL, EXISTS, NOT EXISTS, REGEXP, NOT REGEXP, RLIKE, GLOB, SIMILAR TO, NOT SIMILAR TO, ~, ~*, !~, !~*, @>, <@, &&. Others throw a DbException.

Array keys must be column names (table.column allowed). A field given to Criteria and a string condition are SQL: write them in code, never from request data.


Joins

#
PHP
use Taphra\Criteria;
use Taphra\SqlQuery;

$rows = (new SqlQuery($conn))
    ->select(['c.name', 'o.total'])
    ->from('customers', 'c')
    ->join('orders', 'o.customer_id = c.id', 'o')          // INNER JOIN
    ->where(new Criteria('o.status', '=', 'paid'))
    ->fetch(true, false);

$withOrders = (new SqlQuery($conn))
    ->select(['c.name'])
    ->selectRaw('COUNT(o.id) AS orders')
    ->from('customers', 'c')
    ->leftJoin('orders', 'o.customer_id = c.id', 'o')
    ->groupBy(['c.id', 'c.name'])
    ->fetch(true, false);

Also rightJoin(), fullOuterJoin() (not MySQL) and crossJoin($table, $alias). The join condition is SQL.


Grouping, ordering, limits

#
PHP
use Taphra\SqlQuery;

$rows = (new SqlQuery($conn))
    ->select('customer_id')
    ->selectRaw('SUM(total) AS spent')
    ->from('orders')
    ->groupBy('customer_id')
    ->havingRaw('SUM(total) > ?', [50])
    ->orderBy('spent', 'DESC')            // a column or alias; 'a DESC, b' lists work too
    ->limit(10, 0)                        // limit, offset
    ->fetch(true, false);

$byMonth = (new SqlQuery($conn))
    ->selectRaw("substr(created_at, 1, 7) AS month, COUNT(*) AS n")
    ->from('orders')
    ->groupByRaw('substr(created_at, 1, 7)')
    ->orderByRaw('month')
    ->fetch(true, false);

orderBy() and groupBy() accept column names (and table.column, or a column position) only; orderByRaw() and groupByRaw() take expressions. limit() and offset() cast to integers.


Raw SQL fragments

#

selectRaw(), whereRaw(), havingRaw() and orderByRaw() take SQL with ? placeholders and the values to bind:

PHP
use Taphra\SqlQuery;

$rows = (new SqlQuery($conn))
    ->selectRaw('name, salary * ? AS raised', [1.1])
    ->from('employees')
    ->whereRaw('salary >= ? AND dept = ?', [90, 'eng'])
    ->orderByRaw('salary * ? DESC', [1])
    ->fetch(true, false);

getBindings() returns the values of these raw fragments in placeholder order.


Sub-queries

#
PHP
use Taphra\SqlQuery;

$payers = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid']);

$rows = (new SqlQuery($conn))->select('*')->from('customers')
    ->whereSubquery('id', 'IN', $payers)          // values of the sub-query are bound too
    ->fetch(true, false);

$withOpen = (new SqlQuery($conn))->select('*')->from('customers', 'c')
    ->whereExists((new SqlQuery($conn))->select('id')->from('orders', 'o')
        ->whereRaw('o.customer_id = c.id')->where(['o.status' => 'new']))
    ->fetch(true, false);

$fromSub = (new SqlQuery($conn))->select('*')
    ->from((new SqlQuery($conn))->select(['customer_id', 'total'])->from('orders')->where(['status' => 'paid']), 'paid')
    ->fetch(true, false);

Common table expressions

#
PHP
use Taphra\SqlQuery;

$recent = (new SqlQuery($conn))->select(['id', 'total'])->from('orders')->where(['created_at >=' => '2026-02-01']);

$rows = (new SqlQuery($conn))
    ->with('recent', $recent)
    ->select('*')
    ->from('recent')
    ->fetch(true, false);

// Recursive: Eve and everyone below her. The CTE body is the anchor UNION ALL the recursive part.
$anchor    = (new SqlQuery($conn))->select(['id', 'name', 'manager_id'])->from('employees')->where(['id' => 1]);
$recursive = (new SqlQuery($conn))->select(['e.id', 'e.name', 'e.manager_id'])
    ->from('employees', 'e')->join('tree', 'tree.id = e.manager_id');
$tree = (new SqlQuery($conn))
    ->withRecursive('tree', $anchor->unionAll($recursive))
    ->select('*')->from('tree')
    ->fetch(true, false);                    // Eve, Finn, Hal, Gus

Set operations

#
PHP
use Taphra\SqlQuery;

$paid = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid']);
$new  = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'new']);

$either = (new SqlQuery($conn))->select('customer_id')->from('orders')->where(['status' => 'paid'])
    ->union($new)->fetch(true, false);                    // UNION
$both   = (new SqlQuery($conn))->select('id')->from('customers')
    ->intersect((new SqlQuery($conn))->select('customer_id')->from('orders'))->fetch(true, false);   // INTERSECT
$never  = (new SqlQuery($conn))->select('id')->from('customers')
    ->except((new SqlQuery($conn))->select('customer_id')->from('orders'))->fetch(true, false);      // EXCEPT
$all    = (new SqlQuery($conn))->select('customer_id')->from('orders')->unionAll($paid)->fetch(true, false);

MySQL supports INTERSECT and EXCEPT from 8.0.31 (MariaDB from 10.3).


Window functions

#
PHP
use Taphra\WindowSpec;
use Taphra\SqlQuery;

$rank = (new WindowSpec())->partitionBy('dept')->orderBy('salary', 'DESC');
$run  = (new WindowSpec())->orderBy('id', 'ASC')->rowsBetween('UNBOUNDED PRECEDING', 'CURRENT ROW');

$rows = (new SqlQuery($conn))
    ->select(['name', 'dept', 'salary'])
    ->selectWindow('RANK()', $rank, 'dept_rank')
    ->selectWindow('SUM(salary)', $run, 'running_total')
    ->selectWindow('AVG(salary)', new WindowSpec(), 'company_avg')   // OVER ()
    ->from('employees')
    ->fetch(true, false);

WindowSpec: partitionBy(...$columns), orderBy($column, $direction), rowsBetween($start, $end), rangeBetween($start, $end), toSql(). SQLite needs 3.25 or later, MySQL 8.0.


INSERT, UPDATE, DELETE, upsert

#
PHP
use Taphra\Criteria;
use Taphra\SqlQuery;

(new SqlQuery($conn))->insert('customers', ['name' => 'Dee', 'email' => '[email protected]'])->execute();

(new SqlQuery($conn))->insert('orders', [                 // several rows in one statement
    ['customer_id' => 4, 'total' => 5.00, 'status' => 'new', 'created_at' => '2026-03-01 10:00:00'],
    ['customer_id' => 4, 'total' => 6.00, 'status' => 'new', 'created_at' => '2026-03-02 10:00:00'],
])->execute();

// UPDATE and DELETE need a condition: a third argument or where().
(new SqlQuery($conn))->update('orders', ['status' => 'paid'])->where(new Criteria('customer_id', '=', 4))->execute();
(new SqlQuery($conn))->update('customers', ['active' => 0], new Criteria('email', '=', '[email protected]'))->execute();
(new SqlQuery($conn))->delete('orders')->where(['customer_id' => 4, 'total <' => 6])->execute();

// Insert, or update the given columns when the unique key already exists
(new SqlQuery($conn))
    ->upsert('customers', ['name' => 'Dee D.', 'email' => '[email protected]', 'active' => 1], ['email'], ['name', 'active'])
    ->execute();

// RETURNING (PostgreSQL, SQLite 3.35+): execute() returns the rows
$created = (new SqlQuery($conn))
    ->insert('customers', ['name' => 'Eli', 'email' => '[email protected]'])
    ->returning(['id', 'name'])
    ->execute();                                          // [['id' => 5, 'name' => 'Eli']]

An upsert is INSERT ... ON DUPLICATE KEY UPDATE on MySQL, INSERT ... ON CONFLICT (...) DO UPDATE on PostgreSQL and SQLite (onConflictWhere() adds a partial-index predicate), and MERGE on SQL Server. Column names in the data are quoted; a name containing a quote character is rejected.


Row locking

#

lockForUpdate() adds FOR UPDATE and sharedLock() adds LOCK IN SHARE MODE (MySQL) or FOR SHARE (PostgreSQL), inside a transaction. SQLite and SQL Server have no row locks; the query throws instead:

PHP
use Taphra\SqlQuery;

try {
    (new SqlQuery($conn))->select('*')->from('orders')->where(['id' => 1])->lockForUpdate()->fetch(true, false);
} catch (\Taphra\Db\DbException $e) {
    // SQLite does not support row-level locking
}

Running SQL on the connection

#
PHP
$affected = $conn->execute('UPDATE customers SET active = ? WHERE id = ?', [1, 3]);
$rows     = $conn->query('SELECT name FROM customers WHERE active = ? ORDER BY id', true, false, [1]);
$row      = $conn->query('SELECT name FROM customers WHERE id = ?', false, false, [1]);

$conn->beginTransaction();
$conn->execute('UPDATE orders SET status = ? WHERE id = ?', ['paid', 3]);
$conn->commit();             // or $conn->rollback()

Inspecting a statement

#
PHP
use Taphra\SqlQuery;

$q = (new SqlQuery($conn))->select('*')->from('orders')->where(['status' => 'paid'])->limit(5);

$st  = $q->toString();       // ['sqlWithParams' => 'SELECT * FROM orders ... = ? LIMIT 5', 'values' => ['paid']]
$sql = $q->toSqlString();    // the same SQL with the values inlined (quoted by the driver), for logs
$conn->quoteIdentifier('orders.status');   // `orders`.`status` here, "orders"."status" on PostgreSQL

toSqlString() output is for reading; run statements with fetch() or execute(), which bind the values.