Convert Figma logo to code with AI

sqlkata logoquerybuilder

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird

3,203
510
3,203
148

Top Related Projects

19,674

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

29,871

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

35,247

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

41,609

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

An SQL-friendly ORM for Node.js

Quick Overview

SqlKata is a powerful SQL query builder for .NET. It provides a fluent and intuitive API to construct complex SQL queries, supporting multiple database engines including SQL Server, PostgreSQL, MySQL, and SQLite. SqlKata aims to simplify database interactions while maintaining flexibility and performance.

Pros

  • Supports multiple database engines with a unified API
  • Offers a fluent and expressive syntax for building complex queries
  • Provides strong typing and IntelliSense support
  • Includes features like dynamic queries, subqueries, and joins

Cons

  • Learning curve for developers new to query builders
  • May introduce a slight performance overhead compared to raw SQL
  • Limited support for some database-specific features
  • Requires additional setup and configuration compared to using raw SQL

Code Examples

  1. Basic Select Query:
var query = new Query("users")
    .Select("id", "name", "email")
    .Where("active", true)
    .OrderBy("name");

string sql = compiler.Compile(query).Sql;
  1. Join and Aggregation:
var query = new Query("orders")
    .Join("users", "users.id", "orders.user_id")
    .Select("users.name")
    .SelectRaw("COUNT(*) as order_count")
    .GroupBy("users.name")
    .Having("order_count", ">", 5);

string sql = compiler.Compile(query).Sql;
  1. Subquery and Pagination:
var subQuery = new Query("products")
    .Select("category_id")
    .Where("price", ">", 1000);

var query = new Query("categories")
    .WhereIn("id", subQuery)
    .ForPage(2, 15);

string sql = compiler.Compile(query).Sql;

Getting Started

  1. Install the SqlKata NuGet package:
dotnet add package SqlKata
  1. Create a query compiler for your database:
using SqlKata.Compilers;

var compiler = new SqlServerCompiler(); // Or PostgresCompiler, MySqlCompiler, etc.
  1. Build and execute a query:
using SqlKata;

var query = new Query("users").Where("active", true);
string sql = compiler.Compile(query).Sql;

// Execute the SQL using your preferred database connection method

Competitor Comparisons

19,674

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.

Pros of Knex

  • More mature and widely adopted project with a larger community
  • Supports a broader range of databases, including PostgreSQL, MySQL, SQLite, and Oracle
  • Offers migration and seeding functionality out of the box

Cons of Knex

  • Steeper learning curve due to more complex API
  • Larger bundle size, which may impact performance in some scenarios
  • Less intuitive syntax for complex queries compared to SqlKata

Code Comparison

SqlKata:

var query = new Query("users")
    .Where("age", ">", 18)
    .WhereIn("role", new[] { "admin", "moderator" })
    .OrderByDesc("created_at")
    .Limit(10);

Knex:

const query = knex('users')
  .where('age', '>', 18)
  .whereIn('role', ['admin', 'moderator'])
  .orderBy('created_at', 'desc')
  .limit(10);

Both SqlKata and Knex are powerful query builders, but they cater to different ecosystems. SqlKata is primarily designed for .NET applications, while Knex targets Node.js environments. SqlKata offers a more intuitive and fluent API, making it easier for developers to construct complex queries. On the other hand, Knex provides a more comprehensive set of features, including database migrations and seeding, which can be particularly useful for larger projects or those requiring more advanced database management capabilities.

29,871

Feature-rich ORM for modern Node.js and TypeScript, it supports PostgreSQL (with JSON and JSONB support), MySQL, MariaDB, SQLite, MS SQL Server, Snowflake, Oracle DB (v6), DB2 and DB2 for IBM i.

Pros of Sequelize

  • More comprehensive ORM with support for multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Robust ecosystem with extensive documentation and community support
  • Built-in migration and seeding tools for database management

Cons of Sequelize

  • Steeper learning curve due to its extensive feature set
  • Can be overkill for simple projects or when only basic querying is needed
  • Performance overhead for complex queries compared to raw SQL

Code Comparison

Sequelize:

const users = await User.findAll({
  where: { age: { [Op.gte]: 18 } },
  include: [{ model: Post, where: { status: 'active' } }]
});

SqlKata:

var query = new Query("users")
    .Where("age", ">=", 18)
    .Join("posts", "users.id", "posts.user_id")
    .Where("posts.status", "active");

Summary

Sequelize is a full-featured ORM with broad database support and robust tooling, making it suitable for complex projects. However, it may be overwhelming for simpler use cases. SqlKata, on the other hand, focuses on query building and offers a more lightweight approach, which can be beneficial for projects requiring fine-tuned control over SQL generation without the overhead of a full ORM.

35,247

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.

Pros of TypeORM

  • Supports multiple databases (MySQL, PostgreSQL, SQLite, etc.)
  • Provides powerful ORM features with decorators and entity relationships
  • Active development and large community support

Cons of TypeORM

  • Steeper learning curve due to its extensive feature set
  • Can be overkill for simple projects or small applications
  • Performance overhead in some scenarios due to ORM abstraction

Code Comparison

TypeORM:

@Entity()
class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;
}

const users = await repository.find({ where: { name: "John" } });

SqlKata:

var query = new Query("users").Where("name", "John");
var users = db.Get<User>(query);

TypeORM offers a more declarative approach with decorators and built-in ORM features, while SqlKata provides a fluent API for query building. TypeORM is better suited for complex applications with intricate data relationships, whereas SqlKata is more lightweight and focused on query building.

TypeORM excels in scenarios requiring advanced ORM capabilities and cross-database support, making it ideal for large-scale applications. SqlKata, on the other hand, is more suitable for projects that need a simple, performant query builder without the overhead of a full ORM system.

41,609

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • More comprehensive ORM with auto-generated migrations and type-safe database access
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, SQL Server)
  • Offers a powerful schema modeling language and intuitive API

Cons of Prisma

  • Steeper learning curve due to its unique approach and schema definition language
  • Less flexibility for complex custom queries compared to raw SQL or query builders

Code Comparison

Prisma:

const users = await prisma.user.findMany({
  where: { age: { gte: 18 } },
  select: { name: true, email: true }
})

QueryBuilder:

var users = new Query("users")
    .Where("age", ">=", 18)
    .Select("name", "email")
    .Get();

Key Differences

  • Prisma uses a schema-first approach, while QueryBuilder is more code-first
  • Prisma generates type-safe client code, QueryBuilder relies on manual type definitions
  • Prisma offers more advanced features like relations and nested queries out of the box

Use Cases

  • Prisma: Ideal for large-scale applications with complex data models and TypeScript projects
  • QueryBuilder: Better suited for simpler database operations and projects requiring more SQL-like syntax

A simple Node.js ORM for PostgreSQL, MySQL and SQLite3 built on top of Knex.js

Pros of Bookshelf

  • More comprehensive ORM with model relationships and data validation
  • Supports multiple databases (PostgreSQL, MySQL, SQLite3)
  • Active community and well-established ecosystem

Cons of Bookshelf

  • Steeper learning curve due to more complex API
  • Heavier and potentially slower for simple queries
  • Less flexible for raw SQL queries compared to QueryBuilder

Code Comparison

Bookshelf:

const User = bookshelf.Model.extend({
  tableName: 'users',
  posts() {
    return this.hasMany(Post);
  }
});

User.where('name', 'John').fetch({withRelated: ['posts']});

QueryBuilder:

var query = new Query("users")
    .Where("name", "John")
    .Join("posts", "users.id", "posts.user_id")
    .Select("users.*", "posts.*");

var result = db.Execute(query);

QueryBuilder offers a more straightforward approach for building SQL queries, while Bookshelf provides a higher-level abstraction with ORM features. QueryBuilder is more lightweight and flexible for raw SQL operations, whereas Bookshelf excels in managing complex data relationships and validations across multiple database systems.

An SQL-friendly ORM for Node.js

Pros of Objection.js

  • Built specifically for Node.js, offering seamless integration with JavaScript/TypeScript projects
  • Provides powerful ORM features, including model relationships and eager loading
  • Supports JSON schema validation for data integrity

Cons of Objection.js

  • Limited to PostgreSQL, MySQL, and SQLite databases
  • Steeper learning curve due to its extensive feature set
  • May introduce performance overhead for complex queries

Code Comparison

Objection.js:

const users = await User.query()
  .where('age', '>', 18)
  .orderBy('name')
  .limit(10);

QueryBuilder:

var users = new Query("users")
    .Where("age", ">", 18)
    .OrderBy("name")
    .Limit(10)
    .Get();

Both libraries offer fluent interfaces for building SQL queries, but Objection.js is more JavaScript-centric and integrates with Node.js ecosystems, while QueryBuilder is designed for .NET environments. Objection.js provides ORM capabilities, whereas QueryBuilder focuses primarily on query construction. The syntax is similar, but Objection.js leverages async/await patterns typical in JavaScript.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

SqlKata Query Builder

Twitter

Follow and Upvote SqlKata on Product Hunt to encourage the development of this project

SqlKata - Dynamic Sql query builder for dotnet | Product Hunt

https://private-user-images.githubusercontent.com/2517523/408899411-1f9ff89b-ed17-4d02-ae2f-afc1c66a5932.mp4

🚀 Introduction

SqlKata Query Builder is a powerful SQL query builder written in C#. It is secure, framework-agnostic, and inspired by top query builders like Laravel Query Builder and Knex.

✨ Key Features

  • Expressive API: Clean and intuitive syntax similar to SQL.
  • Database Agnostic: Work with multiple databases using a unified API.
  • Complex Queries: Supports nested conditions, subqueries, conditional statements, and more.
  • Execution Support: Use the SqlKata.Execution package to execute queries with Dapper.

Installation

$ dotnet add package SqlKata
$ dotnet add package SqlKata.Execution # (optional) If you want the execution support

Quick Examples

Setup Connection

var connection = new SqlConnection("...");
var compiler = new SqlCompiler();
var db = new QueryFactory(connection, compiler);

QueryFactory is provided by the SqlKata.Execution package.

Retrieve all records

var books = db.Query("Books").Get();

Retrieve published books only

var books = db.Query("Books").WhereTrue("IsPublished").Get();

Retrieve one book

var introToSql = db.Query("Books").Where("Id", 145).Where("Lang", "en").First();

Retrieve recent books: last 10

var recent = db.Query("Books").OrderByDesc("PublishedAt").Limit(10).Get();

Include Author information

var books = db.Query("Books")
    .Include(db.Query("Authors")) // Assumes that the Books table has an `AuthorId` column
    .Get();

This will include the property "Author" on each "Book":

[{
    "Id": 1,
    "PublishedAt": "2019-01-01",
    "AuthorId": 2,
    "Author": { // <-- included property
        "Id": 2,
        "...": ""
    }
}]

Join with authors table

var books = db.Query("Books")
    .Join("Authors", "Authors.Id", "Books.AuthorId")
    .Select("Books.*", "Authors.Name as AuthorName")
    .Get();

foreach(var book in books)
{
    Console.WriteLine($"{book.Title}: {book.AuthorName}");
}

Conditional queries

var isFriday = DateTime.Today.DayOfWeek == DayOfWeek.Friday;

var books = db.Query("Books")
    .When(isFriday, q => q.WhereIn("Category", new [] {"OpenSource", "MachineLearning"}))
    .Get();

Pagination

var page1 = db.Query("Books").Paginate(10);

foreach(var book in page1.List)
{
    Console.WriteLine(book.Name);
}

...

var page2 = page1.Next();

Insert

int affected = db.Query("Users").Insert(new {
    Name = "Jane",
    CountryId = 1
});

Update

int affected = db.Query("Users").Where("Id", 1).Update(new {
    Name = "Jane",
    CountryId = 1
});

Delete

int affected = db.Query("Users").Where("Id", 1).Delete();

FAQ

How to know when a new release or a feature is available?

I announce updates on my Twitter Account, and you can subscribe to our newsletters from the website https://sqlkata.com.

The database that I want is not supported. Why?

It's impossible to support all available database vendors, which is why we focus on the major ones. We encourage you to create your own compiler for your database.

Do you accept new compilers?

Unfortunately, no. The reason is that this would add overhead for the project contributors. We prefer to improve the quality of the existing compilers instead.

How can I support the project?

  • ⭐ Star the project here on GitHub, and share it with your friends.
  • 🐱‍💻 Follow and upvote it on Product Hunt: SqlKata - Dynamic Sql query builder for dotnet | Product Hunt
  • 💰 You can also donate to support the project financially on open collection.