diff --git a/docs/querying/raw-queries.mdx b/docs/querying/raw-queries.mdx index f39e60ed1..f766dcbb9 100644 --- a/docs/querying/raw-queries.mdx +++ b/docs/querying/raw-queries.mdx @@ -4,6 +4,7 @@ title: Raw SQL (literals) --- import UuidSupportTable from '../_fragments/_uuid-support-table.mdx'; +import { DialectTableFilter } from '@site/src/components/dialect-table-filter.tsx'; 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. 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: +### `sql.random` + +`sql.random` generates a random float between 0 and 1, using the dialect-specific function to do so. + +```ts +await sequelize.query(sql`INSERT INTO lottery (ticket) VALUES (${sql.random()})`); +``` + +The SQL generated by `sql.random()` varies by dialect: + + + +| PostgreSQL | MariaDB | MySQL | MSSQL | SQLite | Snowflake | db2 | ibmi | Oracle | +| ---------- | -------- | -------- | -------- | --------------------------------------------------------------- | ---------- | -------- | -------- | --------------------- | +| `RANDOM()` | `RAND()` | `RAND()` | `RAND()` | `((RANDOM() + 9223372036854775808.0) / 18446744073709551616.0)` | `RANDOM()` | `RAND()` | `RAND()` | `DBMS_RANDOM.VALUE()` | + + + +:::note About SQLite + +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. + +If you want to use the native `RANDOM()` function in SQLite, you can use [`sql`](#writing-raw-sql). + +::: + +:::note About MSSQL + +Using `sql.random()` in an `ORDER BY` clause is a common way to get random ordering, +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. + +::: + ### `sql.col` :::caution