Object oriented representation of SQL queries.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.


Object oriented representation of SQL queries.

This library does not generate any SQL, instead it provides an object oriented representation of SQL queries, allowing the structure of queries to be defined by the developer whilst gaining the benefits of inheritance.

When a PHP application reaches scale, it is often the database that is the performance bottleneck. When queries are generated on behalf of the developer, they are often difficult to optimise because control is lost. With SqlBuilder, the developer is always in control of the raw SQL.

Build status Code quality Code coverage Current version PHP.Gt/SqlBuilder documentation

Example usage: selecting from the student table

Imagine a typical database application with a student table used to store details of each student. A basic select might look something like this:


The above query will return a list of all students. The problem here is that when you come to need to select from the student table again, this time with some constraints such as an age range or ordered by surname, the whole query will need to be repeated and only a small portion of the original query will need to be changed.

Instead, the following class can be used to represent the above query:

class StudentSelect extends SelectBuilder {
	public function select():array {
		return [
	public function from():string {
		return "student";

The __toString method of the above class will produce identical SQL to the original query.

Now, to write another query that returns students of a certain age:

class StudentSelectByAge extends StudentSelect {
	public function where():array {
		return [
			"year(now()) - year(dateOfBirth) = :age",

Limitations of plain SQL

The only tools provided by plain SQL that can be used to write DRY code are views and stored procedures, both of which have their own set of limitations when writing clean and maintainable code.

The solution provided by this library is to break down an SQL query into its different sections, represented by a PHP class which can be extended by other classes, while still retaining the plain SQL that is being represented.

SQL compatibility

This library does not provide any SQL processing capabilities by design. Any driver-specific SQL used will not be compatible with other drivers.