Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

go-sqlbuilder

> 数据库
Open source

A flexible and powerful SQL string builder library plus a zero-config ORM.

1.7K stars0 likes2 views
WebsiteGitHub

About

A flexible and powerful SQL string builder library plus a zero-config ORM.

SQL builder for Go

  • Install
  • Usage
    • Basic usage
    • Pre-defined SQL builders
    • Build WHERE clause
    • Share WHERE clause among builders
    • Build ORDER BY clause
    • Build SQL for different systems
    • Using Struct as a light weight ORM
    • Nested SQL
    • Nested JOIN
    • Use sql.Named in a builder
    • Argument modifiers
    • Freestyle builder
    • Clone builders
    • Using special syntax to build SQL
    • Interpolate args in the sql
  • License

The sqlbuilder package offers a comprehensive suite of SQL string concatenation utilities. It is designed to facilitate the construction of SQL statements compatible with Go's standard library sql.DB and sql.Stmt interfaces, focusing on optimizing the performance of SQL statement creation and minimizing memory usage.

The primary objective of this package's design was to craft a SQL construction library that operates independently of specific database drivers and business logic. It is tailored to accommodate the diverse needs of enterprise environments, including the use of custom database drivers, adherence to specialized operational standards, integration into heterogeneous systems, and handling of non-standard SQL in intricate scenarios. Following its open-source release, the package has undergone extensive testing within a large-scale enterprise context, successfully managing the workload of hundreds of millions of orders daily and nearly ten million transactions daily, thus highlighting its robust performance and scalability.

This package is not restricted to any particular database driver and does not automatically establish connections with any database systems. It does not presuppose the execution of the generated SQL, making it versatile for a broad spectrum of application scenarios that involve the construction of SQL-like statements. It is equally well-suited for further development aimed at creating more business-specific database interaction packages, ORMs, and similar tools.

Install

Install this package by executing the following command:

bash
go get github.com/huandu/go-sqlbuilder

Usage

Basic usage

We can rapidly construct SQL statements using this package.

go
sql := sqlbuilder.Select("id", "name").From("demo.user").
    Where("status = 1").Limit(10).
    String()

fmt.Println(sql)

// Output:
// SELECT id, name FROM demo.user WHERE status = 1 LIMIT 10

In common scenarios, it is necessary to escape all user inputs. To achieve this, initialize a builder at the outset.

go
sb := sqlbuilder.NewSelectBuilder()

sb.Select("id", "name", sb.As("COUNT(*)", "c"))
sb.From("user")
sb.Where(sb.In("status", 1, 2, 5))

sql, args := sb.Build()
fmt.Println(sql)
fmt.Println(args)

// Output:
// SELECT id, name, COUNT(*) AS c FROM user WHERE status IN (?, ?, ?)
// [1 2 5]

Pre-defined SQL builders

This package includes the following pre-defined builders. API documentation and usage examples are available in the godoc online documentation.

  • Struct: Factory for creating builders based on struct definitions.
  • CreateTableBuilder: Builder for CREATE TABLE.
  • SelectBuilder: Builder for SELECT.
  • InsertBuilder: Builder for INSERT.
  • UpdateBuilder: Builder for UPDATE.
  • DeleteBuilder: Builder for DELETE.
  • UnionBuilder: Builder for UNION and UNION ALL.
  • CTEBuilder: Builder for Common Table Expression (CTE), e.g. WITH name (col1, col2) AS (SELECT ...).
  • Buildf: Freestyle builder employing fmt.Sprintf-like syntax.
  • Build: Advanced freestyle builder utilizing special syntax as defined in Args#Compile.
  • BuildNamed: Advanced freestyle builder that uses ${key} to reference values by key in a map.

A unique method, SQL(sql string), is implemented across all statement builders, enabling the insertion of any arbitrary SQL segment into a builder during SQL construction. This feature is particularly beneficial for crafting SQL statements that incorporate non-standard syntax required by OLTP or OLAP systems.

go
// Build a SQL to create a HIVE table.
sql := sqlbuilder.CreateTable("users").
    SQL("PARTITION BY (year)").
    SQL("AS").
    SQL(
        sqlbuilder.Select("columns[0] id", "columns[1] name", "columns[2] year").
            From("`all-users.csv`").
            String(),
    ).
    String()

fmt.Println(sql)

// Output:
// CREATE TABLE users PARTITION BY (year) AS SELECT columns[0] id, columns[1] name, columns[2] year FROM `all-users.csv`

Below are several utility methods designed to address special cases.

  • Flatten enables the recursive conversion of an array-like variable into a flat slice of []interface{}. For example, invoking Flatten([]interface{"foo", []int{2, 3}}) yields []interface{}{"foo", 2, 3}. This method is compatible with builder methods such as In, NotIn, Values, etc., facilitating the conversion of a typed array into []interface{} or the merging of inputs.
  • List operates similarly to Flatten, with the exception that its return value is specifically intended for use as builder arguments. For example, Buildf("my_func(%v)", List([]int{1, 2, 3})).Build() generates SQL my_func(?, ?, ?) with arguments []interface{}{1, 2, 3}.
  • Raw designates a string as a "raw string" within arguments. For instance, Buildf("SELECT %v", Raw("NOW()")).Build() results in SQL SELECT NOW().

For detailed instructions on utilizing these builders, consult the examples provided on GoDoc.

Build WHERE clause

WHERE clause is the most important part of a SQL. We can use Where method to add one or more conditions to a builder.

To simplify the construction of WHERE clauses, a utility type named Cond is provided for condition building. All builders that support WHERE clauses possess an anonymous Cond field, enabling the invocation of Cond methods on these builders.

go
sb := sqlbuilder.Select("id").From("user")
sb.Where(
    sb.In("status", 1, 2, 5),
    sb.Or(
        sb.Equal("name", "foo"),
        sb.Like("email", "foo@%"),
    ),
)

sql, args := sb.Build()
fmt.Println(sql)
fmt.Println(args)

// Output:
// SELECT id FROM user WHERE status IN (?, ?, ?) AND (name = ? OR email LIKE ?)
// [1 2 5 foo foo@%]

There are many methods for building conditions.

  • Cond.Equal/Cond.E/Cond.EQ: field = value.
  • Cond.NotEqual/Cond.NE/Cond.NEQ: field <> value.
  • Cond.GreaterThan/Cond.G/Cond.GT: field > value.
  • Cond.GreaterEqualThan/Cond.GE/Cond.GTE: field >= value.
  • Cond.LessThan/Cond.L/Cond.LT: field < value.
  • Cond.LessEqualThan/Cond.LE/Cond.LTE: field <= value.
  • Cond.In: field IN (value1, value2, ...).
  • Cond.NotIn: field NOT IN (value1, value2, ...).
  • Cond.Like: field LIKE value.
  • Cond.ILike: field ILIKE value.
  • Cond.NotLike: field NOT LIKE value.
  • Cond.NotILike: field NOT ILIKE value.
  • Cond.Between: field BETWEEN lower AND upper.
  • Cond.NotBetween: field NOT BETWEEN lower AND upper.
  • Cond.IsNull: field IS NULL.
  • Cond.IsNotNull: field IS NOT NULL.
  • Cond.Exists: EXISTS (subquery).
  • Cond.NotExists: NOT EXISTS (subquery).
  • Cond.Not: NOT expr.
  • Cond.Any: field op ANY (value1, value2, ...).
  • Cond.All: field op ALL (value1, value2, ...).
  • Cond.Some: field op SOME (value1, value2, ...).
  • Cond.IsDistinctFrom field IS DISTINCT FROM value.
  • Cond.IsNotDistinctFrom field IS NOT DISTINCT FROM value.
  • Cond.Var: A placeholder for any value.

There are also some methods to combine conditions.

  • Cond.And: Combine conditions with AND operator.
  • Cond.Or: Combine conditions with OR operator.

Share WHERE clause among builders

Due to the importance of the WHERE statement in SQL, we often need to continuously append conditions and even share some common WHERE conditions among different builders. Therefore, we abstract the WHERE statement into a WhereClause struct, which can be used to create reusable WHERE conditions.

The following example illustrates how to transfer a WHERE clause from

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Godatabasegohiveqllightweight

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库