SQL Select TS Query Builder

2.0.18 · active · verified Wed Apr 22

sql-select-ts is a modern, database-agnostic SELECT query builder for JavaScript and TypeScript, currently stable at version 2.0.18. It distinguishes itself through its composable API and strong static type checking, making it an excellent choice for projects prioritizing type safety and maintainable SQL generation. The package exhibits a frequent release cadence, with numerous minor updates and bug fixes being published regularly, indicating active development and responsiveness to community feedback. Its core value proposition lies in enabling developers to construct complex SELECT queries programmatically without sacrificing type safety or database portability, moving beyond raw string concatenation or less type-safe alternatives. It focuses specifically on SELECT statements, offering a streamlined API for this common database operation, and is suitable for both Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates building a multi-table SELECT query with aliased columns, aggregates, joins, complex WHERE clauses, grouping, ordering, and pagination, then converts it to a raw SQL string.

import { select, column, table, raw } from 'sql-select-ts';

interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

interface Post {
  id: number;
  userId: number;
  title: string;
}

const users = table<User>('users');
const posts = table<Post>('posts');

// Build a complex SELECT query with joins, conditions, grouping, and ordering
const query = select(
  column(users.id),
  column(users.name).as('userName'),
  column(users.email),
  raw('COUNT(posts.id)').as('postCount')
)
  .from(users)
  .leftJoin(posts)
  .on(column(users.id).eq(column(posts.userId)))
  .where(column(users.createdAt).gt(raw("NOW() - INTERVAL '1 year'")))
  .groupBy(column(users.id), column(users.name), column(users.email))
  .orderBy(column(users.name).asc())
  .limit(10)
  .offset(0);

const queryString = query.toSQL();
console.log(queryString);
/*
Expected output:
SELECT users.id, users.name AS userName, users.email, COUNT(posts.id) AS postCount
FROM users
LEFT JOIN posts ON users.id = posts.userId
WHERE users.createdAt > NOW() - INTERVAL '1 year'
GROUP BY users.id, users.name, users.email
ORDER BY users.name ASC
LIMIT 10 OFFSET 0
*/

view raw JSON →