Skip to content

Commit 312cb99

Browse files
authored
Document sql.random (#836)
1 parent 1371ae9 commit 312cb99

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

docs/querying/raw-queries.mdx

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ title: Raw SQL (literals)
44
---
55

66
import UuidSupportTable from '../_fragments/_uuid-support-table.mdx';
7+
import { DialectTableFilter } from '@site/src/components/dialect-table-filter.tsx';
78

89
We believe that ORMs are inherently leaky abstractions. They are a compromise between the flexibility of SQL and the convenience of an object-oriented programming language.
910
As such, it does not make sense to try to provide a 100% complete abstraction over SQL (which could easily be more difficult to read than the SQL itself).
@@ -541,6 +542,39 @@ These functions are supported by the following dialects:
541542

542543
<UuidSupportTable />
543544

545+
### `sql.random`
546+
547+
`sql.random` generates a random float between 0 and 1, using the dialect-specific function to do so.
548+
549+
```ts
550+
await sequelize.query(sql`INSERT INTO lottery (ticket) VALUES (${sql.random()})`);
551+
```
552+
553+
The SQL generated by `sql.random()` varies by dialect:
554+
555+
<DialectTableFilter>
556+
557+
| PostgreSQL | MariaDB | MySQL | MSSQL | SQLite | Snowflake | db2 | ibmi | Oracle |
558+
| ---------- | -------- | -------- | -------- | --------------------------------------------------------------- | ---------- | -------- | -------- | --------------------- |
559+
| `RANDOM()` | `RAND()` | `RAND()` | `RAND()` | `((RANDOM() + 9223372036854775808.0) / 18446744073709551616.0)` | `RANDOM()` | `RAND()` | `RAND()` | `DBMS_RANDOM.VALUE()` |
560+
561+
</DialectTableFilter>
562+
563+
:::note About SQLite
564+
565+
SQLite's native `RANDOM()` function returns a random integer in the range of a 64-bit signed integer. Sequelize normalizes this to a float between 0 and 1.
566+
567+
If you want to use the native `RANDOM()` function in SQLite, you can use [`sql`](#writing-raw-sql).
568+
569+
:::
570+
571+
:::note About MSSQL
572+
573+
Using `sql.random()` in an `ORDER BY` clause is a common way to get random ordering,
574+
however in MSSQL, it is better to use `NEWID()` for this purpose, as `RAND()` is evaluated only once per query, and will not give you random ordering.
575+
576+
:::
577+
544578
### `sql.col`
545579

546580
:::caution

0 commit comments

Comments
 (0)