SQL Server NEXT VALUE FOR with OVER
NEXT VALUE FOR seq OVER (ORDER BY x) hands out sequence values in the requested order; none of the other four engines has a windowed sequence call.
- Kategorie
- Fenster
- Returns
bigint (sequence type)- In this category
- 67 of 79
Syntax
NEXT VALUE FOR dbo.Seq OVER (ORDER BY x)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Not built in | nextval() has no OVER form; call it from a query already sorted by the wanted order |
| MySQL | Not built in | no sequence objects; AUTO_INCREMENT on INSERT ... SELECT ... ORDER BY, or ROW_NUMBER() |
| SQLite | Not built in | no sequence objects; INTEGER PRIMARY KEY on insert, or ROW_NUMBER() |
| Oracle | Not built in | seq.NEXTVAL has no OVER form and is not allowed in a query with ORDER BY; number with ROW_NUMBER first |
Beispiele
SQL Server
SELECT NEXT VALUE FOR dbo.OrderSeq OVER (ORDER BY created_at) AS seq_no,
order_id, created_at
FROM staging_orders;
Gut zu wissen
- OVER takes ORDER BY only ('NEXT VALUE FOR function does not support the PARTITION BY clause'), and NEXT VALUE FOR is refused in views, subqueries, CTEs, derived tables and functions. A top-level SELECT or INSERT ... SELECT is where it works.
- The values are consumed: re-running the query burns numbers. For repeatable numbering, ROW_NUMBER() OVER (ORDER BY x) is free and side-effect free.
- Gaps happen like with any sequence (rollbacks, restarts); never treat NEXT VALUE FOR output as gap-free data.
Questions about NEXT VALUE FOR OVER
When is NEXT VALUE FOR OVER the right tool?
When you must persist real sequence numbers (foreign keys, order numbers) in a bulk load's order: ROW_NUMBER gives the order but cannot hand out durable sequence values.
Why does my NEXT VALUE FOR OVER error in a view or CTE?
SQL Server refuses NEXT VALUE FOR in views, subqueries, CTEs, derived tables and functions (error 11719). Put it in the outer SELECT or in INSERT ... SELECT, or number into a temp table first.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.