SQL Server front-end (T-SQL)

Statements and functions

The T-SQL statements, functions and system objects that are translated, with how.

Statements#

DDL. CREATE TABLE with IDENTITY(seed, 1) (-> AUTO_INCREMENT, the seed as the table option; an increment other than 1 is refused), PRIMARY KEY [CLUSTERED|NONCLUSTERED], UNIQUE, NOT NULL/NULL, DEFAULT, CHECK, FOREIGN KEY ... REFERENCES ... ON DELETE|UPDATE CASCADE|NO ACTION|SET NULL, named constraints, computed columns AS (expr) [PERSISTED] (the type is derived from the expression); ON [PRIMARY], WITH (...) and the like are read and ignored. ALTER TABLE ADD column/constraint, DROP COLUMN, DROP CONSTRAINT, ALTER COLUMN, NOCHECK/CHECK CONSTRAINT (accepted, no effect). CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED] INDEX (INCLUDE, WITH ignored), DROP INDEX x ON t, DROP TABLE [IF EXISTS] a, b, TRUNCATE TABLE, CREATE VIEW / CREATE OR ALTER VIEW / DROP VIEW, CREATE DATABASE, DROP DATABASE [IF EXISTS], USE. The idiom IF OBJECT_ID(N'dbo.t', N'U') IS NOT NULL DROP TABLE dbo.t works (as an IF over OBJECT_ID). ALTER DATABASE ... SET ... is accepted and does nothing.

Queries. SELECT [DISTINCT] [TOP n | TOP (n) [PERCENT]] (-> LIMIT n; PERCENT counts first; WITH TIES refused), OFFSET n ROWS FETCH NEXT m ROWS ONLY, SELECT ... INTO t | #t, SELECT @v = expr, ... (values of the last row), CTEs (a recursive one is found by its self-reference and written WITH RECURSIVE), UNION [ALL], INTERSECT, EXCEPT (INTERSECT ALL, EXCEPT ALL refused), INNER/LEFT/RIGHT/CROSS JOIN, derived tables, (VALUES ...) AS t(a, b), GROUP BY, HAVING, ORDER BY, subqueries, EXISTS, IN, BETWEEN, CASE, window functions (ROW_NUMBER, RANK, DENSE_RANK, NTILE, LAG, LEAD, FIRST_VALUE, LAST_VALUE, aggregates with OVER). Table hints WITH (NOLOCK) and OPTION (...) are read and ignored.

Arithmetic. a + b is concatenation when an operand is a string and the other is a string or of unknown type (decided from the types of literals, variables, columns and function results); a string and a number add as numbers (as in SQL Server); a date and a number add days. / of two whole numbers is DIV (truncating); with a decimal it is a DECIMAL division with SQL Server's result scale (max(6, s1 + p2 + 1); a whole-number literal counts as decimal(digits,0)). %, &, |, ^, ~ as the engine's. Division and % by zero is error 8134: the divisor is wrapped in a check the engine fails with a two-row subquery error, which is mapped to 8134 (so a real "subquery returned more than one row" error is also shown as 8134: known limit).

LIKE. %, _; a literal pattern with [a-z], [^0-9] classes is translated to a regular expression. LIKE ... ESCAPE works for a literal pattern and for a parameter pattern with a literal escape character (stage 5).

Functions. ISNULL, COALESCE, NULLIF, IIF, CHOOSE; GETDATE, SYSDATETIME, GETUTCDATE, SYSUTCDATETIME, CURRENT_TIMESTAMP, DATEADD, DATEDIFF (year, quarter, month, week, day, hour, minute, second, millisecond: counts boundaries as SQL Server does), DATEPART, DATENAME, YEAR, MONTH, DAY, EOMONTH, DATEFROMPARTS; LEN (ignores trailing spaces), DATALENGTH, CHARINDEX, PATINDEX (patterns %x, x%, %x% without inner wildcards), SUBSTRING, LEFT, RIGHT, LTRIM, RTRIM, TRIM, UPPER, LOWER, REPLACE, REPLICATE, REVERSE, STUFF, SPACE, STR, ASCII, CHAR, FORMAT (numeric N, F, D, 0.00, #,##0.00; date patterns yyyy MM dd HH mm ss fff tt ...; a pattern that is not a literal is refused), CONCAT (NULL is empty), CONCAT_WS, STRING_AGG ... WITHIN GROUP, NEWID; ABS, CEILING, FLOOR, ROUND (with the truncate argument), POWER, SQRT, SIGN, SQUARE, EXP, LOG, LOG10, trigonometry, PI, RAND; COUNT, COUNT_BIG, SUM, AVG (of whole numbers: whole), MIN, MAX, STDEV, STDEVP, VAR, VARP; DB_NAME, SCHEMA_NAME, USER_NAME, SUSER_SNAME, HOST_NAME, APP_NAME, OBJECT_ID, SCOPE_IDENTITY, SERVERPROPERTY('ProductVersion' ...), ERROR_NUMBER, ERROR_MESSAGE, ERROR_SEVERITY, ERROR_STATE, ERROR_LINE. Any other function name is error 195.

CAST / CONVERT. CAST(x AS t), CONVERT(t, x [, style]), TRY_CAST, TRY_CONVERT. Decimal to whole number truncates (as T-SQL). Date to text styles 0, 1-7, 10-12, 20, 21, 23, 25, 26, 100-107, 110-112, 120, 121, 126 (style 0 of a datetime is Jan 2 2024 3:04AM); text to date with styles 1, 3, 4, 5, 10, 11, 12 and ISO text. A string literal that is not a number cast to a number is error 245 when the statement is translated. TRY_CAST of text to a number is NULL when the text is not a number (a regular-expression check).

DML. INSERT ... VALUES (...), (...), INSERT ... SELECT, INSERT ... DEFAULT VALUES, INSERT TOP (n) ... SELECT; UPDATE [TOP (n)] t SET a = e, b += 1 [FROM ... JOIN ...] [WHERE] (with a FROM it is the engine's multi-table UPDATE; TOP only without FROM); DELETE [TOP (n)] [FROM] t [FROM ... JOIN ...] [WHERE]; OUTPUT inserted.* / deleted.col [AS x] on INSERT and on a DELETE of one table (-> RETURNING), OUTPUT ... INTO table on INSERT; SET IDENTITY_INSERT t ON|OFF (an explicit value for an identity column with it off is error 544 when the column list names the column). @@ROWCOUNT, @@IDENTITY, SCOPE_IDENTITY() (no difference between them: no triggers), @@ERROR, @@TRANCOUNT, @@VERSION (Raft DB 0.0.1 (T-SQL front-end compatible with SQL Server 2022) - 16.0.1000.6 (X64) ...; the numbers are SQL Server 2022's, see "Identity" in the overview), @@SERVERNAME, @@SPID, @@LANGUAGE, @@MAX_PRECISION, @@TEXTSIZE, @@DATEFIRST (7). SET NOCOUNT, ANSI_NULLS, QUOTED_IDENTIFIER, XACT_ABORT, ARITHABORT, TEXTSIZE, LANGUAGE, LOCK_TIMEOUT, TRANSACTION ISOLATION LEVEL ..., STATISTICS ... and other SET options are accepted and, except NOCOUNT and IDENTITY_INSERT, have no effect (SET ROWCOUNT n with n other than 0 is refused). The engine's transactions are atomic but not isolated (D-series: READ UNCOMMITTED).

Transactions. BEGIN TRAN[SACTION] (nested: counted in @@TRANCOUNT, one engine transaction), COMMIT, ROLLBACK (all), SAVE TRAN x, ROLLBACK TRAN x (to the savepoint). Errors 3902 and 3903 when there is none. DDL inside a transaction is not transactional in the engine.

Control flow and variables (run by the front-end, one statement at a time; see D91): DECLARE @v type [= expr], ..., SET @v = expr (also += ...; the value is converted to the declared type), PRINT, IF/ELSE, WHILE with BREAK/CONTINUE, BEGIN ... END, BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH (errors of class 11 to 19), RETURN [n], RAISERROR (msg, severity, state, args) (%s %d %i %u %%; a severity of 10 or less is a message), THROW [number, message, state] (a bare THROW in CATCH rethrows), EXEC (string), EXEC sp_executesql @stmt, @params, @p = v [OUTPUT] (also as an RPC: parameters are variables for the statement). The statements of a batch run in order and the batch stops at the first error that is not caught (SQL Server continues after some statement-level errors: known difference).

Catalog. INFORMATION_SCHEMA.TABLES, .COLUMNS, .VIEWS, .SCHEMATA, .TABLE_CONSTRAINTS, .KEY_COLUMN_USAGE; sys.tables, sys.columns, sys.all_columns, sys.objects, sys.views, sys.schemas (dbo, guest, INFORMATION_SCHEMA, sys), sys.databases, sys.types (a few). They are derived tables over the engine's own catalog with T-SQL's names and types; object_id is a number made from the table's name.

Stage 2 and stage 3 (D95, D105)#

Stored procedures, functions (scalar, inline and multi-statement table-valued), triggers, cursors (static; keyset and dynamic since stage 7), table variables, MERGE, OUTPUT on UPDATE / DELETE, sequences, FULL JOIN, APPLY, STRING_SPLIT, OPENJSON, PIVOT / UNPIVOT, FOR JSON, TOP ... WITH TIES, LIKE ... ESCAPE, sp_help and the other system procedures, and statement-level errors are described in the SQL Server chapter. Added in stage 3:

Statements. GOTO label / label: (error 133 when the label is missing), WAITFOR DELAY | TIME (a cancel from the client ends it), UPDATE t SET @v = expr [, col = expr] and @v = col = expr (also SET @s = @s + col, which runs row by row), WHERE CURRENT OF cursor, cursor variables (DECLARE @c CURSOR, SET @c = CURSOR FOR ...), INSERT ... EXEC proc, MERGE ... OUTPUT ... INTO table, FOR XML RAW | AUTO | PATH with ELEMENTS, ROOT and TYPE, SET DATEFIRST, SET LANGUAGE, SET FMTONLY.

Functions. JSON_MODIFY, HASHBYTES (MD5, SHA1, SHA2_256), TRANSLATE, TRIM(chars FROM x), PARSENAME, GREATEST, LEAST, DATETRUNC, ISNUMERIC, ISDATE, QUOTENAME, PARSE, TRY_PARSE, DB_ID, OBJECT_NAME, COLUMNPROPERTY, OBJECTPROPERTY, TYPE_NAME, DATABASEPROPERTYEX, IS_MEMBER, DATEDIFF(microsecond) and more.

Catalog. sys.indexes, sys.index_columns, sys.foreign_keys, sys.foreign_key_columns, sys.key_constraints, sys.default_constraints, sys.sequences, sys.partitions, sys.dm_exec_sessions, sys.database_principals and others (some empty), INFORMATION_SCHEMA.ROUTINES, REFERENTIAL_CONSTRAINTS, CONSTRAINT_COLUMN_USAGE, sp_describe_first_result_set, sp_tablecollations_100.

Stage 4 (D111)#

Temporal tables. CREATE TABLE ... (SysStartTime datetime2 GENERATED ALWAYS AS ROW START [HIDDEN] NOT NULL, SysEndTime datetime2 GENERATED ALWAYS AS ROW END [HIDDEN] NOT NULL, PERIOD FOR SYSTEM_TIME (SysStartTime, SysEndTime)) WITH (SYSTEM_VERSIONING = ON [(HISTORY_TABLE = dbo.h, ...)]); ALTER TABLE t ADD ... GENERATED ALWAYS AS ROW START ..., PERIOD FOR SYSTEM_TIME (a, b) (the usual way to make an existing table temporal), ALTER TABLE t SET (SYSTEM_VERSIONING = ON [(HISTORY_TABLE = h)] | OFF), ALTER TABLE t DROP PERIOD FOR SYSTEM_TIME; FROM t FOR SYSTEM_TIME AS OF x | FROM a TO b | BETWEEN a AND b | CONTAINED IN (a, b) | ALL [AS alias]. They are mapped onto the engine's system-versioned tables (D100): the engine keeps the current rows in the table and the old versions in a hidden table, and writes the period columns itself, in UTC, from the start of each statement (as SQL Server does for SysStartTime; the engine's clock is UTC, so GETDATE() is UTC too). The history table is a view of the hidden table (read only: SELECT * FROM dbo.h works; while versioning is off it is a real table with the rows of the history). A HIDDEN period column stays out of SELECT *. The end of the period of a current row is shown as 9999-12-31 23:59:59.9999999, and a comparison with that text (WHERE SysEndTime = '9999-12-31 23:59:59.9999999') finds the current rows. DROP TABLE of a system-versioned table is error 13552 (turn versioning off first); FOR SYSTEM_TIME on another table is error 13544. Turning versioning off rebuilds the table (the engine cannot keep user-named period columns without versioning): its keys and the front-end's own records are kept, foreign keys that point at it and triggers on it are not. Turning versioning on drops and adds the two period columns (the rows get the time of the statement; their column position moves to the end).

Table-valued parameters and types. CREATE TYPE dbo.t AS TABLE (columns, constraints), CREATE TYPE dbo.t FROM base [NULL | NOT NULL] (an alias type: used for columns, parameters and variables as its base type; its nullability is not enforced), DROP TYPE [IF EXISTS], DECLARE @t dbo.t, a procedure parameter @p dbo.t READONLY and EXEC proc @p = @t, and the wire type 0xF3 that SqlClient (SqlDbType.Structured, TypeName) and mssql-jdbc (setStructured, SQLServerDataTable) send: to a stored procedure, and to a text statement (sp_executesql with @t dbo.t READONLY; the statement sees a table variable @t). An empty table-valued parameter works. CREATE SYNONYM [schema.]name FOR [db.][schema.]object and DROP SYNONYM [IF EXISTS] (a synonym for a table or view; tables only in the statements that read and write tables). Definitions are in the front-end's hidden table and are read by a session when it connects, after it changes one and when it runs USE; a type or synonym made by another session is seen after reconnecting.

sql_variant. The column type, CAST(x AS sql_variant), DECLARE @v sql_variant, a SqlDbType.Variant / microsoft.sql.Types.SQL_VARIANT parameter, results (GetValue gives Int32, String, Decimal, ... as SQL Server does; NULL travels as a zero length) and SQL_VARIANT_PROPERTY(v, 'BaseType' | 'Precision' | 'Scale' | 'MaxLength' | 'TotalBytes' | 'Collation'). The engine has no such type: a variant is kept as text with the name of its base type in front (int<SOH>42). Values are compared as that text, so ORDER BY and = on a variant column do not follow SQL Server's rule for mixed base types, and an INSERT ... SELECT from a variant column into another variant column keeps the text as it is.

Smaller items. SET ROWCOUNT n (a SELECT without TOP, INSERT ... SELECT, UPDATE, DELETE; SET ROWCOUNT 0 ends it; also SET ROWCOUNT @n); x op ANY | SOME | ALL (subquery); INTERSECT ALL and EXCEPT ALL are error 156 Syntax is wrong next to the keyword 'ALL'. (SQL Server has neither); INSERT | UPDATE | DELETE TOP (n) PERCENT (the rows are counted first and the percent rounded up; error 1031 outside 0 to 100; WITH TIES is refused); BULK INSERT t FROM 'file' [WITH (FIELDTERMINATOR, ROWTERMINATOR, FIRSTROW, FORMAT = 'CSV', FIELDQUOTE)] reads a server-side file, which is refused (error 4861 Bulk load failed: unable to open the file "x". OS error code 5(Access is denied.).) unless the program was started with --import-dir DIR (MssqlHandler::with_import_dir) and the file is inside that folder (a path that leaves it is the same error 4861, a file that is not there is error 4860); FOR XML EXPLICIT stays refused with the usual text.

Full-text basics. CREATE FULLTEXT CATALOG / DROP FULLTEXT CATALOG / ALTER FULLTEXT ... are accepted and do nothing; CREATE FULLTEXT INDEX ON t (cols) KEY INDEX pk ... records the table and columns (error 9959 for a second one), DROP FULLTEXT INDEX ON t; CONTAINS(col | *, 'condition') and FREETEXT(col | *, 'text') become MATCH (cols) AGAINST (... IN BOOLEAN MODE) (D93). A condition is words, "phrases", "prefix*" joined by AND, OR, AND NOT (or &, |, &!); a condition that mixes AND and OR, NEAR, FORMSOF, ISABOUT, weights, parentheses and a column list (a, b) are refused. A table without a full-text index is error 7601. The words are the engine's (InnoDB's parser: at least three characters, minus its stop words), not SQL Server's word breakers, stemming and thesaurus; FREETEXT does not stem or use the thesaurus. Since D137 CREATE FULLTEXT INDEX also makes a Raft DB full-text index of each text column (raftdb-text, kept by the server next to the rows) and DROP FULLTEXT INDEX drops it: CONTAINS / FREETEXT over one column look up the words they need in it (a rare word on 60,000 rows: 58.9 ms scanning, 3.5 ms with the index), and the engine's score still decides every row, so the answers are the same with and without it (checked with randomized texts and queries; NEAR, FORMSOF, several columns are evaluated).

Protocol (crate raftdb-tds). Type 0xF3 is read into Value::Table (TableValue: the type's name, the columns and the rows; an upper limit of 1024 columns and 10 million rows), and type 0x62 (sql_variant) is read and written (variant.rs). MARS is not done: the login answer says MARS is off, SqlClient with MultipleActiveResultSets=True connects and then refuses the second command while a reader is open with its own text, There is already an open DataReader associated with this Command which must be closed first. (checked against this program). Doing it needs the SMP session layer ([MS-SMP]: SYN / ACK / FIN / DATA frames with sequence numbers and flow-control windows) and a connection loop that reads frames while an answer is being sent (a client that has a reader open and sends the next request does not read), and result sets that can be sent in pieces; today a request is read, run and answered one at a time on one thread, and an answer is built whole before it is sent.

Clients. Temporal tables, sql_variant, the types and the full-text basics work in process and through sqlcmd; mssql-jdbc 13.6.2 (setStructured to a procedure, a sql_variant parameter and column, FOR SYSTEM_TIME) and System.Data.SqlClient (Structured parameters to a procedure and a text statement, an empty one, Variant, hidden period columns) work too.

Not done in stage 4 (done in stage 6, see "Stage 6"): geometry / geography, varchar code pages other than 1252, collation-aware comparison, MARS.