Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/querying/raw-queries.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -541,6 +542,39 @@ These functions are supported by the following dialects:

<UuidSupportTable />

### `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:

<DialectTableFilter>

| PostgreSQL | MariaDB | MySQL | MSSQL | SQLite | Snowflake | db2 | ibmi | Oracle |
| ---------- | -------- | -------- | -------- | --------------------------------------------------------------- | ---------- | -------- | -------- | --------------------- |
| `RANDOM()` | `RAND()` | `RAND()` | `RAND()` | `((RANDOM() + 9223372036854775808.0) / 18446744073709551616.0)` | `RANDOM()` | `RAND()` | `RAND()` | `DBMS_RANDOM.VALUE()` |

</DialectTableFilter>

:::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
Expand Down
Loading