###################
Query Builder Class
###################

CodeIgniter gives you access to a Query Builder class. This pattern
allows information to be retrieved, inserted, and updated in your
database with minimal scripting. In some cases only one or two lines
of code are necessary to perform a database action.
CodeIgniter does not require that each database table be its own class
file. It instead provides a more simplified interface.

Beyond simplicity, a major benefit to using the Query Builder features
is that it allows you to create database independent applications, since
the query syntax is generated by each database adapter. It also allows
for safer queries, since the values are escaped automatically by the
system.

.. contents::
    :local:
    :depth: 1

*************************
Loading the Query Builder
*************************

The Query Builder is loaded through the ``table()`` method on the
database connection. This sets the ``FROM`` portion of the query for you
and returns a new instance of the Query Builder class::

    $db      = \Config\Database::connect();
    $builder = $db->table('users');

The Query Builder is only loaded into memory when you specifically request
the class, so no resources are used by default.

**************
Selecting Data
**************

The following functions allow you to build SQL **SELECT** statements.

**$builder->get()**

Runs the selection query and returns the result. Can be used by itself
to retrieve all records from a table::

    $builder = $db->table('mytable');
    $query   = $builder->get();  // Produces: SELECT * FROM mytable

The first and second parameters enable you to set a limit and offset
clause::

	$query = $builder->get(10, 20);

	// Executes: SELECT * FROM mytable LIMIT 20, 10
	// (in MySQL. Other databases have slightly different syntax)

You'll notice that the above function is assigned to a variable named
$query, which can be used to show the results::

	$query = $builder->get();

	foreach ($query->getResult() as $row)
	{
		echo $row->title;
	}

Please visit the :doc:`result functions <results>` page for a full
discussion regarding result generation.

**$builder->getCompiledSelect()**

Compiles the selection query just like **$builder->get()** but does not *run*
the query. This method simply returns the SQL query as a string.

Example::

	$sql = $builder->getCompiledSelect();
	echo $sql;

	// Prints string: SELECT * FROM mytable

The first parameter enables you to set whether or not the query builder query
will be reset (by default it will be reset, just like when using `$builder->get()`)::

	echo $builder->limit(10,20)->getCompiledSelect(false);

	// Prints string: SELECT * FROM mytable LIMIT 20, 10
	// (in MySQL. Other databases have slightly different syntax)

	echo $builder->select('title, content, date')->getCompiledSelect();

	// Prints string: SELECT title, content, date FROM mytable LIMIT 20, 10

The key thing to notice in the above example is that the second query did not
utilize **$builder->from()** and did not pass a table name into the first
parameter. The reason for this outcome is because the query has not been
executed using **$builder->get()** which resets values or reset directly
using **$builder->resetQuery()**.

**$builder->getWhere()**

Identical to the ``get()`` function except that it permits you to add a
"where" clause in the first parameter, instead of using the db->where()
function::

	$query = $builder->getWhere(['id' => $id], $limit, $offset);

Please read the about the where function below for more information.

**$builder->select()**

Permits you to write the SELECT portion of your query::

	$builder->select('title, content, date');
	$query = $builder->get();

	// Executes: SELECT title, content, date FROM mytable

.. note:: If you are selecting all (\*) from a table you do not need to
	use this function. When omitted, CodeIgniter assumes that you wish
	to select all fields and automatically adds 'SELECT \*'.

``$builder->select()`` accepts an optional second parameter. If you set it
to FALSE, CodeIgniter will not try to protect your field or table names.
This is useful if you need a compound select statement where automatic
escaping of fields may break them.

::

	$builder->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4) AS amount_paid', FALSE);
	$query = $builder->get();

**$builder->selectMax()**

Writes a ``SELECT MAX(field)`` portion for your query. You can optionally
include a second parameter to rename the resulting field.

::

	$builder->selectMax('age');
	$query = $builder->get();  // Produces: SELECT MAX(age) as age FROM mytable

	$builder->selectMax('age', 'member_age');
	$query = $builder->get(); // Produces: SELECT MAX(age) as member_age FROM mytable

**$builder->selectMin()**

Writes a "SELECT MIN(field)" portion for your query. As with
selectMax(), You can optionally include a second parameter to rename
the resulting field.

::

	$builder->selectMin('age');
	$query = $builder->get(); // Produces: SELECT MIN(age) as age FROM mytable

**$builder->selectAvg()**

Writes a "SELECT AVG(field)" portion for your query. As with
selectMax(), You can optionally include a second parameter to rename
the resulting field.

::

	$builder->selectAvg('age');
	$query = $builder->get(); // Produces: SELECT AVG(age) as age FROM mytable

**$builder->selectSum()**

Writes a "SELECT SUM(field)" portion for your query. As with
selectMax(), You can optionally include a second parameter to rename
the resulting field.

::

	$builder->selectSum('age');
	$query = $builder->get(); // Produces: SELECT SUM(age) as age FROM mytable

**$builder->from()**

Permits you to write the FROM portion of your query::

	$builder->select('title, content, date');
	$builder->from('mytable');
	$query = $builder->get();  // Produces: SELECT title, content, date FROM mytable

.. note:: As shown earlier, the FROM portion of your query can is specified
	in the $db->table() function. Additional calls to from() will add more tables
	to the FROM portion of your query.

**$builder->join()**

Permits you to write the JOIN portion of your query::

    $builder->db->table('blog');
    $builder->select('*');
    $builder->join('comments', 'comments.id = blogs.id');
    $query = $builder->get();

    // Produces:
    // SELECT * FROM blogs JOIN comments ON comments.id = blogs.id

Multiple function calls can be made if you need several joins in one
query.

If you need a specific type of JOIN you can specify it via the third
parameter of the function. Options are: left, right, outer, inner, left
outer, and right outer.

::

	$builder->join('comments', 'comments.id = blogs.id', 'left');
	// Produces: LEFT JOIN comments ON comments.id = blogs.id

*************************
Looking for Specific Data
*************************

**$builder->where()**

This function enables you to set **WHERE** clauses using one of four
methods:

.. note:: All values passed to this function are escaped automatically,
	producing safer queries.

#. **Simple key/value method:**

	::

		$builder->where('name', $name); // Produces: WHERE name = 'Joe'

	Notice that the equal sign is added for you.

	If you use multiple function calls they will be chained together with
	AND between them:

	::

		$builder->where('name', $name);
		$builder->where('title', $title);
		$builder->where('status', $status);
		// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

#. **Custom key/value method:**

	You can include an operator in the first parameter in order to
	control the comparison:

	::

		$builder->where('name !=', $name);
		$builder->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45

#. **Associative array method:**

	::

		$array = ['name' => $name, 'title' => $title, 'status' => $status];
		$builder->where($array);
		// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

	You can include your own operators using this method as well:

	::

		$array = ['name !=' => $name, 'id <' => $id, 'date >' => $date];
		$builder->where($array);

#. **Custom string:**
	You can write your own clauses manually::

		$where = "name='Joe' AND status='boss' OR status='active'";
		$builder->where($where);

``$builder->where()`` accepts an optional third parameter. If you set it to
FALSE, CodeIgniter will not try to protect your field or table names.

::

	$builder->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

**$builder->orWhere()**

This function is identical to the one above, except that multiple
instances are joined by OR::

	$builder->where('name !=', $name);
	$builder->orWhere('id >', $id);  // Produces: WHERE name != 'Joe' OR id > 50

**$builder->whereIn()**

Generates a WHERE field IN ('item', 'item') SQL query joined with AND if
appropriate

::

	$names = array('Frank', 'Todd', 'James');
	$builder->whereIn('username', $names);
	// Produces: WHERE username IN ('Frank', 'Todd', 'James')

**$builder->orWhereIn()**

Generates a WHERE field IN ('item', 'item') SQL query joined with OR if
appropriate

::

	$names = array('Frank', 'Todd', 'James');
	$builder->orWhereIn('username', $names);
	// Produces: OR username IN ('Frank', 'Todd', 'James')

**$builder->whereNotIn()**

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with
AND if appropriate

::

	$names = array('Frank', 'Todd', 'James');
	$builder->whereNotIn('username', $names);
	// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

**$builder->orWhereNotIn()**

Generates a WHERE field NOT IN ('item', 'item') SQL query joined with OR
if appropriate

::

	$names = array('Frank', 'Todd', 'James');
	$builder->orWhereNotIn('username', $names);
	// Produces: OR username NOT IN ('Frank', 'Todd', 'James')

************************
Looking for Similar Data
************************

**$builder->like()**

This method enables you to generate **LIKE** clauses, useful for doing
searches.

.. note:: All values passed to this method are escaped automatically.

.. note:: All ``like*`` method variations can be forced to be perform case-insensitive searches by passing
        a fifth parameter of ``true`` to the method. This will use platform-specific features where available
        otherwise, will force the values to be lowercase, i.e. ``WHERE LOWER(column) LIKE '%search%'``. This
        may require indexes to be made for ``LOWER(column)`` instead of ``column`` to be effective.

#. **Simple key/value method:**

	::

		$builder->like('title', 'match');
		// Produces: WHERE `title` LIKE '%match%' ESCAPE '!'

	If you use multiple method calls they will be chained together with
	AND between them::

		$builder->like('title', 'match');
		$builder->like('body', 'match');
		// WHERE `title` LIKE '%match%' ESCAPE '!' AND  `body` LIKE '%match% ESCAPE '!'

	If you want to control where the wildcard (%) is placed, you can use
	an optional third argument. Your options are 'before', 'after' and
	'both' (which is the default).

	::

		$builder->like('title', 'match', 'before');	// Produces: WHERE `title` LIKE '%match' ESCAPE '!'
		$builder->like('title', 'match', 'after');	// Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
		$builder->like('title', 'match', 'both');	// Produces: WHERE `title` LIKE '%match%' ESCAPE '!'

#. **Associative array method:**

	::

		$array = ['title' => $match, 'page1' => $match, 'page2' => $match];
		$builder->like($array);
		// WHERE `title` LIKE '%match%' ESCAPE '!' AND  `page1` LIKE '%match%' ESCAPE '!' AND  `page2` LIKE '%match%' ESCAPE '!'

**$builder->orLike()**

This method is identical to the one above, except that multiple
instances are joined by OR::

	$builder->like('title', 'match'); $builder->orLike('body', $match);
	// WHERE `title` LIKE '%match%' ESCAPE '!' OR  `body` LIKE '%match%' ESCAPE '!'

**$builder->notLike()**

This method is identical to ``like()``, except that it generates
NOT LIKE statements::

	$builder->notLike('title', 'match');	// WHERE `title` NOT LIKE '%match% ESCAPE '!'

**$builder->orNotLike()**

This method is identical to ``notLike()``, except that multiple
instances are joined by OR::

	$builder->like('title', 'match');
	$builder->orNotLike('body', 'match');
	// WHERE `title` LIKE '%match% OR  `body` NOT LIKE '%match%' ESCAPE '!'

**$builder->groupBy()**

Permits you to write the GROUP BY portion of your query::

	$builder->groupBy("title"); // Produces: GROUP BY title

You can also pass an array of multiple values as well::

	$builder->groupBy(array("title", "date"));  // Produces: GROUP BY title, date

**$builder->distinct()**

Adds the "DISTINCT" keyword to a query

::

	$builder->distinct();
	$builder->get(); // Produces: SELECT DISTINCT * FROM mytable

**$builder->having()**

Permits you to write the HAVING portion of your query. There are 2
possible syntaxes, 1 argument or 2::

	$builder->having('user_id = 45');  // Produces: HAVING user_id = 45
	$builder->having('user_id',  45);  // Produces: HAVING user_id = 45

You can also pass an array of multiple values as well::

	$builder->having(['title =' => 'My Title', 'id <' => $id]);
	// Produces: HAVING title = 'My Title', id < 45

If you are using a database that CodeIgniter escapes queries for, you
can prevent escaping content by passing an optional third argument, and
setting it to FALSE.

::

	$builder->having('user_id',  45);  // Produces: HAVING `user_id` = 45 in some databases such as MySQL
	$builder->having('user_id',  45, FALSE);  // Produces: HAVING user_id = 45

**$builder->orHaving()**

Identical to having(), only separates multiple clauses with "OR".

****************
Ordering results
****************

**$builder->orderBy()**

Lets you set an ORDER BY clause.

The first parameter contains the name of the column you would like to order by.

The second parameter lets you set the direction of the result.
Options are **ASC**, **DESC** AND **RANDOM**.

::

	$builder->orderBy('title', 'DESC');
	// Produces: ORDER BY `title` DESC

You can also pass your own string in the first parameter::

	$builder->orderBy('title DESC, name ASC');
	// Produces: ORDER BY `title` DESC, `name` ASC

Or multiple function calls can be made if you need multiple fields.

::

	$builder->orderBy('title', 'DESC');
	$builder->orderBy('name', 'ASC');
	// Produces: ORDER BY `title` DESC, `name` ASC

If you choose the **RANDOM** direction option, then the first parameters will
be ignored, unless you specify a numeric seed value.

::

	$builder->orderBy('title', 'RANDOM');
	// Produces: ORDER BY RAND()

	$builder->orderBy(42, 'RANDOM');
	// Produces: ORDER BY RAND(42)

.. note:: Random ordering is not currently supported in Oracle and
	will default to ASC instead.

****************************
Limiting or Counting Results
****************************

**$builder->limit()**

Lets you limit the number of rows you would like returned by the query::

	$builder->limit(10);  // Produces: LIMIT 10

The second parameter lets you set a result offset.

::

	$builder->limit(10, 20);  // Produces: LIMIT 20, 10 (in MySQL.  Other databases have slightly different syntax)

**$builder->countAllResults()**

Permits you to determine the number of rows in a particular Query
Builder query. Queries will accept Query Builder restrictors such as
``where()``, ``orWhere()``, ``like()``, ``orLike()``, etc. Example::

	echo $builder->countAllResults('my_table');  // Produces an integer, like 25
	$builder->like('title', 'match');
	$builder->from('my_table');
	echo $builder->countAllResults(); // Produces an integer, like 17

However, this method also resets any field values that you may have passed
to ``select()``. If you need to keep them, you can pass ``FALSE`` as the
second parameter::

	echo $builder->countAllResults('my_table', FALSE);

**$builder->countAll()**

Permits you to determine the number of rows in a particular table.
Submit the table name in the first parameter. Example::

	echo $builder->countAll('my_table');  // Produces an integer, like 25

**************
Query grouping
**************

Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow
you to create queries with complex WHERE clauses. Nested groups are supported. Example::

	$builder->select('*')->from('my_table')
		->groupStart()
			->where('a', 'a')
			->orGroupStart()
				->where('b', 'b')
				->where('c', 'c')
			->groupEnd()
		->groupEnd()
		->where('d', 'd')
	->get();

	// Generates:
	// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

.. note:: groups need to be balanced, make sure every groupStart() is matched by a groupEnd().

**$builder->groupStart()**

Starts a new group by adding an opening parenthesis to the WHERE clause of the query.

**$builder->orGroupStart()**

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR'.

**$builder->notGroupStart()**

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'NOT'.

**$builder->orNotGroupStart()**

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with 'OR NOT'.

**$builder->groupEnd()**

Ends the current group by adding an closing parenthesis to the WHERE clause of the query.

**************
Inserting Data
**************

**$builder->insert()**

Generates an insert string based on the data you supply, and runs the
query. You can either pass an **array** or an **object** to the
function. Here is an example using an array::

	$data = array(
		'title' => 'My title',
		'name'  => 'My Name',
		'date'  => 'My date'
	);

	$builder->insert($data);
	// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

The first parameter is an associative array of values.

Here is an example using an object::

	/*
	class Myclass {
		public $title   = 'My Title';
		public $content = 'My Content';
		public $date    = 'My Date';
	}
	*/

	$object = new Myclass;
	$builder->insert($object);
	// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')

The first parameter is an object.

.. note:: All values are escaped automatically producing safer queries.

**$builder->getCompiledInsert()**

Compiles the insertion query just like $builder->insert() but does not
*run* the query. This method simply returns the SQL query as a string.

Example::

	$data = array(
		'title' => 'My title',
		'name'  => 'My Name',
		'date'  => 'My date'
	);

	$sql = $builder->set($data)->getCompiledInsert('mytable');
	echo $sql;

	// Produces string: INSERT INTO mytable (`title`, `name`, `date`) VALUES ('My title', 'My name', 'My date')

The second parameter enables you to set whether or not the query builder query
will be reset (by default it will be--just like $builder->insert())::

	echo $builder->set('title', 'My Title')->getCompiledInsert('mytable', FALSE);

	// Produces string: INSERT INTO mytable (`title`) VALUES ('My Title')

	echo $builder->set('content', 'My Content')->getCompiledInsert();

	// Produces string: INSERT INTO mytable (`title`, `content`) VALUES ('My Title', 'My Content')

The key thing to notice in the above example is that the second query did not
utilize `$builder->from()` nor did it pass a table name into the first
parameter. The reason this worked is because the query has not been executed
using `$builder->insert()` which resets values or reset directly using
`$builder->resetQuery()`.

.. note:: This method doesn't work for batched inserts.

**$builder->insertBatch()**

Generates an insert string based on the data you supply, and runs the
query. You can either pass an **array** or an **object** to the
function. Here is an example using an array::

	$data = array(
		array(
			'title' => 'My title',
			'name'  => 'My Name',
			'date'  => 'My date'
		),
		array(
			'title' => 'Another title',
			'name'  => 'Another Name',
			'date'  => 'Another date'
		)
	);

	$builder->insertBatch($data);
	// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

The first parameter is an associative array of values.

.. note:: All values are escaped automatically producing safer queries.

*************
Updating Data
*************

**$builder->replace()**

This method executes a REPLACE statement, which is basically the SQL
standard for (optional) DELETE + INSERT, using *PRIMARY* and *UNIQUE*
keys as the determining factor.
In our case, it will save you from the need to implement complex
logics with different combinations of  ``select()``, ``update()``,
``delete()`` and ``insert()`` calls.

Example::

	$data = array(
		'title' => 'My title',
		'name'  => 'My Name',
		'date'  => 'My date'
	);

	$builder->replace($data);

	// Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

In the above example, if we assume that the *title* field is our primary
key, then if a row containing 'My title' as the *title* value, that row
will be deleted with our new row data replacing it.

Usage of the ``set()`` method is also allowed and all fields are
automatically escaped, just like with ``insert()``.

**$builder->set()**

This function enables you to set values for inserts or updates.

**It can be used instead of passing a data array directly to the insert
or update functions:**

::

	$builder->set('name', $name);
	$builder->insert();  // Produces: INSERT INTO mytable (`name`) VALUES ('{$name}')

If you use multiple function called they will be assembled properly
based on whether you are doing an insert or an update::

	$builder->set('name', $name);
	$builder->set('title', $title);
	$builder->set('status', $status);
	$builder->insert();

**set()** will also accept an optional third parameter (``$escape``), that
will prevent data from being escaped if set to FALSE. To illustrate the
difference, here is ``set()`` used both with and without the escape
parameter.

::

	$builder->set('field', 'field+1', FALSE);
	$builder->where('id', 2);
	$builder->update(); // gives UPDATE mytable SET field = field+1 WHERE `id` = 2

	$builder->set('field', 'field+1');
	$builder->where('id', 2);
	$builder->update(); // gives UPDATE `mytable` SET `field` = 'field+1' WHERE `id` = 2

You can also pass an associative array to this function::

	$array = array(
		'name'   => $name,
		'title'  => $title,
		'status' => $status
	);

	$builder->set($array);
	$builder->insert();

Or an object::

	/*
	class Myclass {
		public $title   = 'My Title';
		public $content = 'My Content';
		public $date    = 'My Date';
	}
	*/

	$object = new Myclass;
	$builder->set($object);
	$builder->insert();

**$builder->update()**

Generates an update string and runs the query based on the data you
supply. You can pass an **array** or an **object** to the function. Here
is an example using an array::

	$data = array(
		'title' => $title,
		'name'  => $name,
		'date'  => $date
	);

	$builder->where('id', $id);
	$builder->update($data);
	// Produces:
	//
	//	UPDATE mytable
	//	SET title = '{$title}', name = '{$name}', date = '{$date}'
	//	WHERE id = $id

Or you can supply an object::

	/*
	class Myclass {
		public $title   = 'My Title';
		public $content = 'My Content';
		public $date    = 'My Date';
	}
	*/

	$object = new Myclass;
	$builder->where('id', $id);
	$builder->update($object);
	// Produces:
	//
	// UPDATE `mytable`
	// SET `title` = '{$title}', `name` = '{$name}', `date` = '{$date}'
	// WHERE id = `$id`

.. note:: All values are escaped automatically producing safer queries.

You'll notice the use of the $builder->where() function, enabling you
to set the WHERE clause. You can optionally pass this information
directly into the update function as a string::

	$builder->update($data, "id = 4");

Or as an array::

	$builder->update($data, array('id' => $id));

You may also use the $builder->set() function described above when
performing updates.

**$builder->updateBatch()**

Generates an update string based on the data you supply, and runs the query.
You can either pass an **array** or an **object** to the function.
Here is an example using an array::

	$data = array(
	   array(
	      'title' => 'My title' ,
	      'name'  => 'My Name 2' ,
	      'date'  => 'My date 2'
	   ),
	   array(
	      'title' => 'Another title' ,
	      'name'  => 'Another Name 2' ,
	      'date'  => 'Another date 2'
	   )
	);

	$builder->updateBatch($data, 'title');

	// Produces:
	// UPDATE `mytable` SET `name` = CASE
	// WHEN `title` = 'My title' THEN 'My Name 2'
	// WHEN `title` = 'Another title' THEN 'Another Name 2'
	// ELSE `name` END,
	// `date` = CASE
	// WHEN `title` = 'My title' THEN 'My date 2'
	// WHEN `title` = 'Another title' THEN 'Another date 2'
	// ELSE `date` END
	// WHERE `title` IN ('My title','Another title')

The first parameter is an associative array of values, the second parameter is the where key.

.. note:: All values are escaped automatically producing safer queries.

.. note:: ``affectedRows()`` won't give you proper results with this method,
	due to the very nature of how it works. Instead, ``updateBatch()``
	returns the number of rows affected.

**$builder->getCompiledUpdate()**

This works exactly the same way as ``$builder->getCompiledInsert()`` except
that it produces an UPDATE SQL string instead of an INSERT SQL string.

For more information view documentation for `$builder->getCompiledInsert()`.

.. note:: This method doesn't work for batched updates.

*************
Deleting Data
*************

**$builder->delete()**

Generates a delete SQL string and runs the query.

::

	$builder->delete(array('id' => $id));  // Produces: // DELETE FROM mytable  // WHERE id = $id

The first parameter is the where clause.
You can also use the where() or or_where() functions instead of passing
the data to the first parameter of the function::

	$builder->where('id', $id);
	$builder->delete();

	// Produces:
	// DELETE FROM mytable
	// WHERE id = $id

If you want to delete all data from a table, you can use the truncate()
function, or empty_table().

**$builder->emptyTable()**

Generates a delete SQL string and runs the
query::

	  $builder->emptyTable('mytable'); // Produces: DELETE FROM mytable

**$builder->truncate()**

Generates a truncate SQL string and runs the query.

::

	$builder->truncate();

	// Produce:
	// TRUNCATE mytable

.. note:: If the TRUNCATE command isn't available, truncate() will
	execute as "DELETE FROM table".

**$builder->getCompiledDelete()**

This works exactly the same way as ``$builder->getCompiledInsert()`` except
that it produces a DELETE SQL string instead of an INSERT SQL string.

For more information view documentation for $builder->getCompiledInsert().

***************
Method Chaining
***************

Method chaining allows you to simplify your syntax by connecting
multiple functions. Consider this example::

	$query = $builder->select('title')
			 ->where('id', $id)
			 ->limit(10, 20)
			 ->get();

.. _ar-caching:

***********************
Resetting Query Builder
***********************

**$builder->resetQuery()**

Resetting Query Builder allows you to start fresh with your query without
executing it first using a method like $builder->get() or $builder->insert().

This is useful in situations where you are using Query Builder to generate SQL
(ex. ``$builder->getCompiledSelect()``) but then choose to, for instance,
run the query::

    // Note that the second parameter of the get_compiled_select method is FALSE
    $sql = $builder->select(array('field1','field2'))
                   ->where('field3',5)
                   ->getCompiledSelect(false);

    // ...
    // Do something crazy with the SQL code... like add it to a cron script for
    // later execution or something...
    // ...

    $data = $builder->get()->getResultArray();

    // Would execute and return an array of results of the following query:
    // SELECT field1, field1 from mytable where field3 = 5;

***************
Class Reference
***************

.. php:class:: \CodeIgniter\Database\BaseBuilder

	.. php:method:: resetQuery()

		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Resets the current Query Builder state.  Useful when you want
		to build a query that can be canceled under certain conditions.

	.. php:method:: countAllResults([$reset = TRUE])

		:param	bool	$reset: Whether to reset values for SELECTs
		:returns:	Number of rows in the query result
		:rtype:	int

		Generates a platform-specific query string that counts
		all records returned by an Query Builder query.

	.. php:method:: get([$limit = NULL[, $offset = NULL]])

		:param	int	$limit: The LIMIT clause
		:param	int	$offset: The OFFSET clause
		:returns:	\CodeIgniter\Database\ResultInterface instance (method chaining)
		:rtype:	\CodeIgniter\Database\ResultInterface

		Compiles and runs SELECT statement based on the already
		called Query Builder methods.

	.. php:method:: getWhere([$where = NULL[, $limit = NULL[, $offset = NULL]]])

		:param	string	$where: The WHERE clause
		:param	int	$limit: The LIMIT clause
		:param	int	$offset: The OFFSET clause
		:returns:	\CodeIgniter\Database\ResultInterface instance (method chaining)
		:rtype:	\CodeIgniter\Database\ResultInterface

		Same as ``get()``, but also allows the WHERE to be added directly.

	.. php:method:: select([$select = '*'[, $escape = NULL]])

		:param	string	$select: The SELECT portion of a query
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a SELECT clause to a query.

	.. php:method:: selectAvg([$select = ''[, $alias = '']])

		:param	string	$select: Field to compute the average of
		:param	string	$alias: Alias for the resulting value name
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a SELECT AVG(field) clause to a query.

	.. php:method:: selectMax([$select = ''[, $alias = '']])

		:param	string	$select: Field to compute the maximum of
		:param	string	$alias: Alias for the resulting value name
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a SELECT MAX(field) clause to a query.

	.. php:method:: selectMin([$select = ''[, $alias = '']])

		:param	string	$select: Field to compute the minimum of
		:param	string	$alias: Alias for the resulting value name
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a SELECT MIN(field) clause to a query.

	.. php:method:: selectSum([$select = ''[, $alias = '']])

		:param	string	$select: Field to compute the sum of
		:param	string	$alias: Alias for the resulting value name
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a SELECT SUM(field) clause to a query.

	.. php:method:: distinct([$val = TRUE])

		:param	bool	$val: Desired value of the "distinct" flag
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Sets a flag which tells the query builder to add
		a DISTINCT clause to the SELECT portion of the query.

	.. php:method:: from($from)

		:param	mixed	$from: Table name(s); string or array
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Specifies the FROM clause of a query.

	.. php:method:: join($table, $cond[, $type = ''[, $escape = NULL]])

		:param	string	$table: Table name to join
		:param	string	$cond: The JOIN ON condition
		:param	string	$type: The JOIN type
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a JOIN clause to a query.

	.. php:method:: where($key[, $value = NULL[, $escape = NULL]])

		:param	mixed	$key: Name of field to compare, or associative array
		:param	mixed	$value: If a single key, compared to this value
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates the WHERE portion of the query.
                Separates multiple calls with 'AND'.

	.. php:method:: orWhere($key[, $value = NULL[, $escape = NULL]])

		:param	mixed	$key: Name of field to compare, or associative array
		:param	mixed	$value: If a single key, compared to this value
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates the WHERE portion of the query.
                Separates multiple calls with 'OR'.

	.. php:method:: orWhereIn([$key = NULL[, $values = NULL[, $escape = NULL]]])

		:param	string	$key: The field to search
		:param	array	$values: The values searched on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates a WHERE field IN('item', 'item') SQL query,
                joined with 'OR' if appropriate.

	.. php:method:: orWhereNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])

		:param	string	$key: The field to search
		:param	array	$values: The values searched on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates a WHERE field NOT IN('item', 'item') SQL query,
                joined with 'OR' if appropriate.

	.. php:method:: whereIn([$key = NULL[, $values = NULL[, $escape = NULL]]])

		:param	string	$key: Name of field to examine
		:param	array	$values: Array of target values
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates a WHERE field IN('item', 'item') SQL query,
                joined with 'AND' if appropriate.

	.. php:method:: whereNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])

		:param	string	$key: Name of field to examine
		:param	array	$values: Array of target values
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance
		:rtype:	object

		Generates a WHERE field NOT IN('item', 'item') SQL query,
                joined with 'AND' if appropriate.

	.. php:method:: groupStart()

		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Starts a group expression, using ANDs for the conditions inside it.

	.. php:method:: orGroupStart()

		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Starts a group expression, using ORs for the conditions inside it.

	.. php:method:: notGroupStart()

		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Starts a group expression, using AND NOTs for the conditions inside it.

	.. php:method:: orNotGroupStart()

		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Starts a group expression, using OR NOTs for the conditions inside it.

	.. php:method:: groupEnd()

		:returns:	BaseBuilder instance
		:rtype:	object

		Ends a group expression.

	.. php:method:: like($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])

		:param	string	$field: Field name
		:param	string	$match: Text portion to match
		:param	string	$side: Which side of the expression to put the '%' wildcard on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a LIKE clause to a query, separating multiple calls with AND.

	.. php:method:: orLike($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])

		:param	string	$field: Field name
		:param	string	$match: Text portion to match
		:param	string	$side: Which side of the expression to put the '%' wildcard on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a LIKE clause to a query, separating multiple class with OR.

	.. php:method:: notLike($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])

		:param	string	$field: Field name
		:param	string	$match: Text portion to match
		:param	string	$side: Which side of the expression to put the '%' wildcard on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a NOT LIKE clause to a query, separating multiple calls with AND.

	.. php:method:: orNotLike($field[, $match = ''[, $side = 'both'[, $escape = NULL]]])

		:param	string	$field: Field name
		:param	string	$match: Text portion to match
		:param	string	$side: Which side of the expression to put the '%' wildcard on
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a NOT LIKE clause to a query, separating multiple calls with OR.

	.. php:method:: having($key[, $value = NULL[, $escape = NULL]])

		:param	mixed	$key: Identifier (string) or associative array of field/value pairs
		:param	string	$value: Value sought if $key is an identifier
		:param	string	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a HAVING clause to a query, separating multiple calls with AND.

	.. php:method:: orHaving($key[, $value = NULL[, $escape = NULL]])

		:param	mixed	$key: Identifier (string) or associative array of field/value pairs
		:param	string	$value: Value sought if $key is an identifier
		:param	string	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a HAVING clause to a query, separating multiple calls with OR.

	.. php:method:: groupBy($by[, $escape = NULL])

		:param	mixed	$by: Field(s) to group by; string or array
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds a GROUP BY clause to a query.

	.. php:method:: orderBy($orderby[, $direction = ''[, $escape = NULL]])

		:param	string	$orderby: Field to order by
		:param	string	$direction: The order requested - ASC, DESC or random
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds an ORDER BY clause to a query.

	.. php:method:: limit($value[, $offset = 0])

		:param	int	$value: Number of rows to limit the results to
		:param	int	$offset: Number of rows to skip
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds LIMIT and OFFSET clauses to a query.

	.. php:method:: offset($offset)

		:param	int	$offset: Number of rows to skip
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds an OFFSET clause to a query.

	.. php:method:: set($key[, $value = ''[, $escape = NULL]])

		:param	mixed	$key: Field name, or an array of field/value pairs
		:param	string	$value: Field value, if $key is a single field
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds field/value pairs to be passed later to ``insert()``,
		``update()`` or ``replace()``.

	.. php:method:: insert([$set = NULL[, $escape = NULL]])

		:param	array	$set: An associative array of field/value pairs
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	TRUE on success, FALSE on failure
		:rtype:	bool

		Compiles and executes an INSERT statement.

	.. php:method:: insertBatch([$set = NULL[, $escape = NULL[, $batch_size = 100]]])

		:param	array	$set: Data to insert
		:param	bool	$escape: Whether to escape values and identifiers
		:param	int	$batch_size: Count of rows to insert at once
		:returns:	Number of rows inserted or FALSE on failure
		:rtype:	mixed

		Compiles and executes batch ``INSERT`` statements.

		.. note:: When more than ``$batch_size`` rows are provided, multiple
			``INSERT`` queries will be executed, each trying to insert
			up to ``$batch_size`` rows.

	.. php:method:: setInsertBatch($key[, $value = ''[, $escape = NULL]])

		:param	mixed	$key: Field name or an array of field/value pairs
		:param	string	$value: Field value, if $key is a single field
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds field/value pairs to be inserted in a table later via ``insertBatch()``.

	.. php:method:: update([$set = NULL[, $where = NULL[, $limit = NULL]]])

		:param	array	$set: An associative array of field/value pairs
		:param	string	$where: The WHERE clause
		:param	int	$limit: The LIMIT clause
		:returns:	TRUE on success, FALSE on failure
		:rtype:	bool

		Compiles and executes an UPDATE statement.

	.. php:method:: updateBatch([$set = NULL[, $value = NULL[, $batch_size = 100]]])

		:param	array	$set: Field name, or an associative array of field/value pairs
		:param	string	$value: Field value, if $set is a single field
		:param	int	$batch_size: Count of conditions to group in a single query
		:returns:	Number of rows updated or FALSE on failure
		:rtype:	mixed

		Compiles and executes batch ``UPDATE`` statements.

		.. note:: When more than ``$batch_size`` field/value pairs are provided,
			multiple queries will be executed, each handling up to
			``$batch_size`` field/value pairs.

	.. php:method:: setUpdateBatch($key[, $value = ''[, $escape = NULL]])

		:param	mixed	$key: Field name or an array of field/value pairs
		:param	string	$value: Field value, if $key is a single field
		:param	bool	$escape: Whether to escape values and identifiers
		:returns:	BaseBuilder instance (method chaining)
		:rtype:	BaseBuilder

		Adds field/value pairs to be updated in a table later via ``updateBatch()``.

	.. php:method:: replace([$set = NULL])

		:param	array	$set: An associative array of field/value pairs
		:returns:	TRUE on success, FALSE on failure
		:rtype:	bool

		Compiles and executes a REPLACE statement.

	.. php:method:: delete([$where = ''[, $limit = NULL[, $reset_data = TRUE]]])

		:param	string	$where: The WHERE clause
		:param	int	$limit: The LIMIT clause
		:param	bool	$reset_data: TRUE to reset the query "write" clause
		:returns:	BaseBuilder instance (method chaining) or FALSE on failure
		:rtype:	mixed

		Compiles and executes a DELETE query.

    .. php:method:: increment($column[, $value = 1])

        :param string $column: The name of the column to increment
        :param int    $value:  The amount to increment the column by

        Increments the value of a field by the specified amount. If the field
        is not a numeric field, like a VARCHAR, it will likely be replaced
        with $value.

    .. php:method:: decrement($column[, $value = 1])

        :param string $column: The name of the column to decrement
        :param int    $value:  The amount to decrement the column by

        Decrements the value of a field by the specified amount. If the field
        is not a numeric field, like a VARCHAR, it will likely be replaced
        with $value.

	.. php:method:: truncate()

		:returns:	TRUE on success, FALSE on failure
		:rtype:	bool

		Executes a TRUNCATE statement on a table.

		.. note:: If the database platform in use doesn't support TRUNCATE,
			a DELETE statement will be used instead.

	.. php:method:: emptyTable()

		:returns:	TRUE on success, FALSE on failure
		:rtype:	bool

		Deletes all records from a table via a DELETE statement.

	.. php:method:: getCompiledSelect([$reset = TRUE])

		:param	bool	$reset: Whether to reset the current QB values or not
		:returns:	The compiled SQL statement as a string
		:rtype:	string

		Compiles a SELECT statement and returns it as a string.

	.. php:method:: getCompiledInsert([$reset = TRUE])

		:param	bool	$reset: Whether to reset the current QB values or not
		:returns:	The compiled SQL statement as a string
		:rtype:	string

		Compiles an INSERT statement and returns it as a string.

	.. php:method:: getCompiledUpdate([$reset = TRUE])

		:param	bool	$reset: Whether to reset the current QB values or not
		:returns:	The compiled SQL statement as a string
		:rtype:	string

		Compiles an UPDATE statement and returns it as a string.

	.. php:method:: getCompiledDelete([$reset = TRUE])

		:param	bool	$reset: Whether to reset the current QB values or not
		:returns:	The compiled SQL statement as a string
		:rtype:	string

		Compiles a DELETE statement and returns it as a string.
