Fluent SQL

Fluent SQL Builder

Fluent SQL lets you write C# code that generates SQL in a way that looks like SQL. If you know SQL, you should be able to use this library.

The code

var selectStatement =
    Select.All("ID", "Name", "LastUpdated")
        .From("Customer")
        .Where("LastUpdated".IsGreaterThan(new DateTime(2024, 9, 1)));

will generate the SQL

SELECT [ID], [Name], [LastUpdated]
FROM [Customer]
WHERE [LastUpdated] > '2024-09-01 00:00:00';

There isn’t a whole lot of extra syntax to learn. Code completion will guide you. The C# code will never be as terse as SQL, but there’s almost no boilerplate.

Why shouldn’t you use Fluent SQL Builder?

The Fluent SQL Builder is a tool to build SQL statements in a structured way. It is not intended to replace views or stored procedures, or parameterised SQL, or your ORM. It is intended to replace SQL code that is built up using string concatenation.

“String concatenation” + “?”

Building SQL queries and statements using string concatenation can be unsafe. It can be prone to SQL injection if you’re not careful. It can be hard to read, which makes it hard to spot bugs. It’s very easy to construct incorrect or invalid SQL. But sometimes you need dynamic SQL and building queries on the fly is the right thing to do. Fluent SQL is a tool designed to make building dynamic SQL queries faster and safer.

Building SQL with string concatenation means you have to count brackets and quotes. The code is full of visual clutter that makes it hard to read. There’s nothing to prevent the code from generating nonsense SQL that will never work and those errors won’t be discovered until runtime, when they’re harder to find and more difficult to fix.

Use Fluent SQL instead!

Fluent SQL is easy to read and hard to get wrong. Errors are caught by the compiler. They don’t sit there waiting to blow up when the code is run. Not only are runtime bugs more costly to fix, runtime errors often occur somewhere other than where the original bug was introduced, making diagnosing the bug a frustrating experience. Fluent SQL makes writing good code easier.

If you know how to write a SQL query, you should be able to use Fluent SQL without reading the manual. But here’s the manual anyway…