drizzle-team / drizzle-orm

Headless TypeScript ORM with a head. Runs on Node, Bun and Deno. Lives on the Edge and yes, it's a JavaScript ORM too 😅
https://orm.drizzle.team
Apache License 2.0
24.41k stars 641 forks source link

[FEATURE]: nulls first/last support for order by asc & desc in postgres #1699

Open VaibhavAcharya opened 10 months ago

VaibhavAcharya commented 10 months ago

Describe what you want

currently the asc & desc do not support order of nulls (first/last)

by default in postgres the nulls come first for desc and last for asc orders, which is quite stupid to be honest but anyways,

I needed that so build my own wrappers for it below but I think this should be a inbuild thing

import { type AnyColumn, type SQLWrapper, sql } from "drizzle-orm"

export function asc(column: SQLWrapper | AnyColumn, nullsLast: boolean = true) {
  if (nullsLast) return sql`${column} asc nulls last`

  return sql`${column} asc`
}

export function desc(
  column: SQLWrapper | AnyColumn,
  nullsLast: boolean = true,
) {
  if (nullsLast) return sql`${column} desc nulls last`

  return sql`${column} desc`
}
mauriciabad commented 8 months ago

Thanks!

For mySQL use the following:

import { sql, type AnyColumn, type SQLWrapper } from 'drizzle-orm'

export function ascNullsEnd(column: SQLWrapper | AnyColumn) {
  return sql`ISNULL(${column}), ${column} asc`
}

export function descNullsEnd(column: SQLWrapper | AnyColumn) {
  return sql`ISNULL(${column}), ${column} desc`
}

export function ascNullsStart(column: SQLWrapper | AnyColumn) {
  return sql`NOT ISNULL(${column}), ${column} asc`
}

export function descNullsStart(column: SQLWrapper | AnyColumn) {
  return sql`NOT ISNULL(${column}), ${column} desc`
}
marceloverdijk commented 3 months ago

Same would be useful for SQLite

SQLite considers NULL values to be smaller than any other values for sorting purposes. Hence, NULLs naturally appear at the beginning of an ASC order-by and at the end of a DESC order-by. This can be changed using the "ASC NULLS LAST" or "DESC NULLS FIRST" syntax.

https://www.sqlite.org/lang_select.html#orderby