design-azure-sql-schema

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Design a schema Azure SQL Database will not make you rebuild

设计一套不会让 Azure SQL Database 迫使你重建的 Schema

These are the schema decisions Azure SQL Database punishes later, not at
CREATE TABLE
. Normalisation and naming are not here: they are the same everywhere.
Everything below holds on Azure SQL Database, where
SERVERPROPERTY('EngineEdition')
returns
5
and
Edition
is
SQL Azure
. Open the statements behind each number when a number below disagrees with your engine, and before changing one.
The DDLsucceeds, sometimes with a warning nobody reads
The migrationsucceeds
The failurearrives on a row, a plan or a failover, weeks later, in production
A syntax error costs minutes. Each item here costs a table rebuild, a collation rebuild or a duplicated key.
以下讨论的是 Azure SQL Database 不会在
CREATE TABLE
时报错,却会在日后给你带来代价的 Schema 决策。 规范化和命名不在此讨论范围内,因为它们在任何地方都一样。
以下所有内容均适用于 Azure SQL Database,其中
SERVERPROPERTY('EngineEdition')
返回
5
, 且
Edition
为
SQL Azure
。 如果下文的某个数值与你的引擎不一致,或者在更改某个设置之前,请打开每个数字背后的依据。
DDL成功,有时只伴随一条无人会注意的警告
迁移成功
故障数周后在生产环境中降临于某一行、某个执行计划或一次故障转移
语法错误只需几分钟。这里每一项错误都可能导致重建表、重建排序规则或产生重复键。

1. The index key budget is in bytes, and Unicode spends two per character

1. 索引键预算以字节计算,而 Unicode 每个字符占用两个字节

1700 bytes for a nonclustered index key, 900 for a clustered one, and a composite key spends the sum.
NVARCHAR(n)
costs
2n
bytes, so:
PositionWidest safe Unicode columnWidest safe UTF-8 column
Nonclustered index or unique constraint
NVARCHAR(850)
VARCHAR(1700)
Clustered index or clustered primary key
NVARCHAR(450)
VARCHAR(900)
Anything not in a keyunboundedunbounded
NVARCHAR(450)
is the only length safe in every index position, which is why EF Core narrows an indexed string to it.
Over-shooting is a warning, message 1945 at severity 10. The index exists, the migration reports success, short values insert fine:
text
Warning! The maximum key length for a nonclustered index is 1700 bytes.
The index 'ux_acct_email' has maximum length of 2000 bytes.
For some combination of large values, the insert/update operation will fail.
The failure waits for the first long row, and this one is an error:
text
Msg 1946, Level 16, State 3
Operation failed. The index entry of length 1800 bytes for the index 'ux_acct_email'
exceeds the maximum length of 1700 bytes for nonclustered indexes.
Consequence of being wrong: a write path that has worked for months starts rejecting exactly the rows that matter, and the fix is an
ALTER COLUMN
plus an index rebuild on a live table.
  • INCLUDE
    columns do not count against the budget.
    A covering index can include
    NVARCHAR(MAX)
    .
  • A foreign key column must match the parent's length and collation exactly,
    Msg 1753
    and
    Msg 1757
    , so an oversized parent key propagates to every child.
  • NVARCHAR(MAX)
    ,
    json
    and
    vector
    cannot be key columns at all:
    Msg 1919
    ,
    Msg 1978
    .
非聚集索引键为 1700 字节,聚集索引键为 900 字节;复合键占用两者之和。
NVARCHAR(n)
占用
2n
字节,因此:
位置最宽的安全 Unicode 列最宽的安全 UTF-8 列
非聚集索引或唯一约束
NVARCHAR(850)
VARCHAR(1700)
聚集索引或聚集主键
NVARCHAR(450)
VARCHAR(900)
不包含在键中的列无上限无上限
只有
NVARCHAR(450)
的长度在所有索引位置中都安全,因此 EF Core 会将索引字符串长度收窄到该值。
超出限制只会产生警告,即严重级别 10 的消息 1945。索引仍然存在,迁移报告成功,较短的值也能正常插入:
text
Warning! The maximum key length for a nonclustered index is 1700 bytes.
The index 'ux_acct_email' has maximum length of 2000 bytes.
For some combination of large values, the insert/update operation will fail.
失败会一直等到第一条长记录出现,而下面才是错误:
text
Msg 1946, Level 16, State 3
Operation failed. The index entry of length 1800 bytes for the index 'ux_acct_email'
exceeds the maximum length of 1700 bytes for nonclustered indexes.
**选错的后果是:**一条已经运行数月的写入路径会开始拒绝恰恰是那些重要记录的行,而修复方式是在在线表上执行
ALTER COLUMN
并重建索引。
  • INCLUDE
    列不计入预算。因此,覆盖索引可以包含
    NVARCHAR(MAX)
    。
  • 外键列的长度和排序规则必须与父表键完全一致,否则会报
    Msg 1753
    和
    Msg 1757
    ;因此,父键过长会传导到每个子表。
  • NVARCHAR(MAX)
    、
    json
    和
    vector
    完全不能作为键列:会报
    Msg 1919
    、
    Msg 1978
    。

2. Collation is chosen at CREATE DATABASE, and it decides two things

2. 排序规则在
CREATE DATABASE
时确定,并决定两件事

A new database with no collation stated gets
SQL_Latin1_General_CP1_CI_AS
.
CI
means identifiers are not unique the way the design assumes:
sql
CREATE TABLE dbo.tokens (t NVARCHAR(64) NOT NULL PRIMARY KEY);
INSERT INTO dbo.tokens (t) VALUES (N'aB1x');
INSERT INTO dbo.tokens (t) VALUES (N'Ab1X');
-- Msg 2627, Violation of PRIMARY KEY constraint. The duplicate key value is (Ab1X).
Consequence of being wrong: any column holding a case-significant token, API key, slug or short link code collides at roughly the rate its alphabet implies, as a user-visible insert failure. The fix is per column:
sql
ALTER TABLE dbo.tokens ALTER COLUMN t NVARCHAR(64) COLLATE Latin1_General_CS_AS NOT NULL;
State the collation in
CREATE DATABASE
, or accept the default deliberately.
There is no server collation to inherit, and
ALTER DATABASE ... COLLATE
afterwards re-collates nothing that already exists: it succeeds, changes only what is created next, and leaves you joining across a collation conflict,
Msg 468
. The second half of the default's cost is section 3.
创建新数据库时如果没有指定排序规则,就会使用
SQL_Latin1_General_CP1_CI_AS
。
CI
意味着标识值并不像设计所假设的那样唯一:
sql
CREATE TABLE dbo.tokens (t NVARCHAR(64) NOT NULL PRIMARY KEY);
INSERT INTO dbo.tokens (t) VALUES (N'aB1x');
INSERT INTO dbo.tokens (t) VALUES (N'Ab1X');
-- Msg 2627, Violation of PRIMARY KEY constraint. The duplicate key value is (Ab1X).
**选错的后果是:**任何保存区分大小写的 token、API key、slug 或短链接代码的列,都会大致按其字符集所对应的概率发生碰撞,并以用户可见的插入失败形式暴露出来。 修复方式是按列设置排序规则:
sql
ALTER TABLE dbo.tokens ALTER COLUMN t NVARCHAR(64) COLLATE Latin1_General_CS_AS NOT NULL;
在
CREATE DATABASE
中明确指定排序规则,或者有意识地接受默认值。
没有可继承的服务器排序规则;事后执行
ALTER DATABASE ... COLLATE
不会重新设置任何现有对象的排序规则:该语句会成功,只影响之后创建的对象,并使跨排序规则连接出现冲突,即
Msg 468
。默认排序规则的另一半代价见第 3 节。

3. The implicit conversion that costs the seek

3. 让索引 Seek 退化的隐式转换

The common drivers bind a string parameter as Unicode by default. Under the default collation, comparing that parameter to a
VARCHAR
column converts the column, and a converted column cannot be sought. With a unique index on
email
:
ColumnCollationParameterPlanLogical reads
VARCHAR(320)
SQL_Latin1_General_CP1_CI_AS
(the default)
NVARCHAR
Index Scanthe whole index
VARCHAR(320)
Latin1_General_CI_AS
NVARCHAR
Index Seeka few pages
VARCHAR(850)
Latin1_General_100_CI_AS_SC_UTF8
NVARCHAR
Index Seeka few pages
NVARCHAR(320)
any
NVARCHAR
Index Seeka few pages
VARCHAR(320)
the default
VARCHAR
Index Seeka few pages
text
|--Index Scan(OBJECT:([dbo].[users_v].[ux_v]),
     WHERE:(CONVERT_IMPLICIT(nvarchar(320),[dbo].[users_v].[email],0)=[@p]))
Row two seeks because a Windows collation lets the optimizer build a range with
GetRangeThroughConvert
. A SQL collation cannot, and the default is a SQL collation.
Consequence of being wrong: every lookup on that column reads the whole index instead of a few pages, forever, with no error and no warning. Two designs avoid it, and one has to be chosen up front:
  1. NVARCHAR
    for anything a driver will bind a string to.
    Correct, and it costs key bytes.
  2. A UTF-8 collation on
    VARCHAR
    when the data is ASCII-dominant and the key is tight.
    VARCHAR(1700)
    then fits a nonclustered key, and the seek survives because UTF-8 collations are Windows collations. The cost is that
    VARCHAR(n)
    counts bytes.
Do not mix.
VARCHAR
under the default collation plus an application binding Unicode is row one.
常见驱动程序默认将字符串参数绑定为 Unicode。在默认排序规则下,将该参数与
VARCHAR
列比较时,转换发生在列上,而经过转换的列无法执行 Seek。对于
email
上的唯一索引:
列排序规则参数计划逻辑读取
VARCHAR(320)
SQL_Latin1_General_CP1_CI_AS
(默认)
NVARCHAR
Index Scan整个索引
VARCHAR(320)
Latin1_General_CI_AS
NVARCHAR
Index Seek少量页面
VARCHAR(850)
Latin1_General_100_CI_AS_SC_UTF8
NVARCHAR
Index Seek少量页面
NVARCHAR(320)
任意
NVARCHAR
Index Seek少量页面
VARCHAR(320)
默认
VARCHAR
Index Seek少量页面
text
|--Index Scan(OBJECT:([dbo].[users_v].[ux_v]),
     WHERE:(CONVERT_IMPLICIT(nvarchar(320),[dbo].[users_v].[email],0)=[@p]))
第二行之所以能够执行 Seek,是因为 Windows 排序规则允许优化器通过
GetRangeThroughConvert
构建范围。SQL 排序规则不能这样做,而默认排序规则正是 SQL 排序规则。
**选错的后果是:**该列上的每次查找都会永久读取整个索引,而不是少量页面,既没有错误,也没有警告。有两种设计可以避免这一问题,必须提前选定其中一种:
  1. 对于驱动程序会绑定字符串的任何内容,使用
    NVARCHAR
    。
    这种做法正确,但会增加键字节数。
  2. 当数据以 ASCII 为主且键空间较紧时,在
    VARCHAR
    上使用 UTF-8 排序规则。
    此时
    VARCHAR(1700)
    可以放入非聚集键,而且由于 UTF-8 排序规则属于 Windows 排序规则,Seek 仍可保留。代价是
    VARCHAR(n)
    按字节计数。
不要混用。默认排序规则下的
VARCHAR
加上应用程序绑定 Unicode 参数,就是表格中的第一行。

4. Identity gaps are routine here, and the remembered fix does not exist

4. 这里的 IDENTITY 间隙很常见,而记忆中的修复方法并不存在

Across one engine restart, which is what a planned failover looks like from inside:
ColumnLast value beforeFirst value afterGap
INT IDENTITY
31002999
BIGINT IDENTITY
3100029999
SEQUENCE
, default cache
25149
SEQUENCE ... NO CACHE
23none
INT IDENTITY
with
IDENTITY_CACHE = OFF
34none
Consequence of being wrong: any number a human reads or a regulator counts, an invoice number, a ticket number, an order reference, develops thousand-wide holes, unrecoverably. Nothing errors.
sql
-- The remembered remedy from a non-PaaS engine. Refused here.
DBCC TRACEON (272, -1);   -- container: Msg 40518, DBCC command 'traceon' is not supported
                          -- Azure SQL Database: Msg 2571, no permission to run DBCC TRACEON

-- The lever that works. It survives a restart and costs a log write per value.
ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF;

-- A human-facing number gets its own sequence, and START WITH is not optional:
-- omitted, the first value is -9223372036854775808.
CREATE SEQUENCE dbo.invoice_no AS BIGINT START WITH 1 INCREMENT BY 1 NO CACHE;
A surrogate key may be
IDENTITY
: gaps in a key nobody reads are free, and the cache is why inserts are fast. A number a person reads is not a surrogate key.
在一次引擎重启前后——从数据库内部看,计划内故障转移正是这种情况——情况如下:
列重启前的最后一个值重启后的第一个值间隙
INT IDENTITY
31002999
BIGINT IDENTITY
3100029999
SEQUENCE
,默认缓存
25149
SEQUENCE ... NO CACHE
23无
INT IDENTITY
,且
IDENTITY_CACHE = OFF
34无
**选错的后果是:**任何供人读取或供监管机构统计的数字,例如发票号、工单号或订单参考号,都会产生跨度达上千且无法恢复的空洞。系统不会报任何错误。
sql
-- The remembered remedy from a non-PaaS engine. Refused here.
DBCC TRACEON (272, -1);   -- container: Msg 40518, DBCC command 'traceon' is not supported
                          -- Azure SQL Database: Msg 2571, no permission to run DBCC TRACEON

-- The lever that works. It survives a restart and costs a log write per value.
ALTER DATABASE SCOPED CONFIGURATION SET IDENTITY_CACHE = OFF;

-- A human-facing number gets its own sequence, and START WITH is not optional:
-- omitted, the first value is -9223372036854775808.
CREATE SEQUENCE dbo.invoice_no AS BIGINT START WITH 1 INCREMENT BY 1 NO CACHE;
代理键可以使用
IDENTITY
:没人会读取的键出现间隙没有代价,而缓存正是插入速度较快的原因。供人读取的数字不应使用代理键。

5. A unique index accepts exactly one NULL

5. 唯一索引恰好接受一个 NULL

This one arrives from PostgreSQL habit, where every NULL is distinct.
sql
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code);
INSERT INTO dbo.accounts (code) VALUES (NULL);   -- 1 row
INSERT INTO dbo.accounts (code) VALUES (NULL);
-- Msg 2601, Cannot insert duplicate key row ... The duplicate key value is (<NULL>).
-- Msg 2627 instead, where the constraint is a unique constraint rather than an index.

-- The fix, which accepts many NULL rows:
DROP INDEX ux_code ON dbo.accounts;
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code) WHERE code IS NOT NULL;
Consequence of being wrong: an optional unique field, an external account id, a nullable slug, works for the first row that leaves it empty and rejects the second. A model with two or three optional unique fields is unusable here and correct on other engines. The session creating a filtered index, and every session writing to the table, needs
QUOTED_IDENTIFIER ON
, else
Msg 1934
. Drivers set it; a command line client may not.
这个问题源于 PostgreSQL 的使用习惯:在 PostgreSQL 中,每个 NULL 都被视为彼此不同。
sql
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code);
INSERT INTO dbo.accounts (code) VALUES (NULL);   -- 1 row
INSERT INTO dbo.accounts (code) VALUES (NULL);
-- Msg 2601, Cannot insert duplicate key row ... The duplicate key value is (<NULL>).
-- Msg 2627 instead, where the constraint is a unique constraint rather than an index.

-- The fix, which accepts many NULL rows:
DROP INDEX ux_code ON dbo.accounts;
CREATE UNIQUE INDEX ux_code ON dbo.accounts (code) WHERE code IS NOT NULL;
**选错的后果是:**可选唯一字段、外部账户 ID 或可空 slug 只会接受第一条留空记录,却会拒绝第二条。包含两三个可选唯一字段的模型在这里不可用,而在其他引擎中却能正常工作。创建筛选索引的会话,以及写入该表的每个会话,都需要启用
QUOTED_IDENTIFIER ON
,否则会出现
Msg 1934
。驱动程序会启用它,但命令行客户端可能不会。

6. Where the json and vector types belong

6.
json
与
vector
类型的适用位置

Both are storage decisions, not key decisions.
json
vector(n)
Index key columnno,
Msg 1978
no,
Msg 1978
Primary keynono,
Msg 1919
INCLUDE
column
yesroute to
vector-search-azure-sql
Compared with
=
no,
Msg 402
against
nvarchar
route to
vector-search-azure-sql
Ceiling2 GB1998 dimensions at
float32
(3996 at
float16
),
Msg 2717
above it
A
json
column is not a filter. Promote anything a query filters on every time into a real column:
sql
ALTER TABLE dbo.doc ADD tenant AS CAST(JSON_VALUE(payload, '$.tenant') AS NVARCHAR(64)) PERSISTED;
CREATE INDEX ix_doc_tenant ON dbo.doc (tenant);
A
vector
column is a payload beside the key, never part of it. A
vector(1536)
occupies 6152 of the 8060 bytes in a row, so keep the table narrow: put the embedding next to an integer key.
两者都是存储决策,而不是键决策。
json
vector(n)
索引键列不支持,
Msg 1978
不支持,
Msg 1978
主键不支持不支持,
Msg 1919
INCLUDE
列
支持转至
vector-search-azure-sql
使用
=
比较
不支持;与
nvarchar
比较时为
Msg 402
转至
vector-search-azure-sql
上限2 GB
float32
下为 1998 维(
float16
下为 3996 维),超过后为
Msg 2717
不能将
json
列直接用作筛选依据。任何每次查询都会用于筛选的内容,都应提升为真实列:
sql
ALTER TABLE dbo.doc ADD tenant AS CAST(JSON_VALUE(payload, '$.tenant') AS NVARCHAR(64)) PERSISTED;
CREATE INDEX ix_doc_tenant ON dbo.doc (tenant);
vector
列是键旁边的载荷,绝不应成为键的一部分。
vector(1536)
会占用一行 8060 字节中的 6152 字节,因此应让表保持窄小:把 embedding 放在整数键旁边。

7. Two boundaries a design cannot cross here

7. 这里的设计无法跨越的两条边界

sql
-- No foreign key reaches another database, even one on the same server.
ALTER TABLE dbo.local_child ADD CONSTRAINT fk_x FOREIGN KEY (parent_id)
  REFERENCES otherdb.dbo.some_parent (id);
-- Msg 40515, Reference to database and/or server name in 'otherdb.dbo.some_parent'
--            is not supported in this version of SQL Server.

-- There is one filegroup, so a partition scheme maps everything to it.
SELECT name, type_desc FROM sys.filegroups;   -- PRIMARY, and nothing else
CREATE PARTITION SCHEME ps AS PARTITION pf ALL TO ([PRIMARY]);
A shared-lookup-database design has no referential integrity here. Partitioning buys manageability, never storage separation.
sql
-- No foreign key reaches another database, even one on the same server.
ALTER TABLE dbo.local_child ADD CONSTRAINT fk_x FOREIGN KEY (parent_id)
  REFERENCES otherdb.dbo.some_parent (id);
-- Msg 40515, Reference to database and/or server name in 'otherdb.dbo.some_parent'
--            is not supported in this version of SQL Server.

-- There is one filegroup, so a partition scheme maps everything to it.
SELECT name, type_desc FROM sys.filegroups;   -- PRIMARY, and nothing else
CREATE PARTITION SCHEME ps AS PARTITION pf ALL TO ([PRIMARY]);
共享查找数据库的设计在这里无法实现引用完整性。分区带来的是可管理性,而不是存储隔离。

Check it worked

检查是否生效

Run the DDL through
sqlcmd
with
-m-1
, because message 1945 is severity 10 and
-b
alone does not report severity 10 at all, so a migration that emitted it still exits 0:
-m-1
is an ODBC
sqlcmd
instruction
, meaning the 18.x build from
mssql-tools18
or the Microsoft command line utilities. go-sqlcmd 1.x, the build
brew install sqlcmd
and
winget install sqlcmd
install, prints no
Msg
header on a severity 10 message at any
-m
value, so on that build the
grep
below finds no message 1945 to report. Query
sys.messages
or run the statement through the ODBC build when the number matters.
bash
export SQLCMDPASSWORD='<password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
  -i schema.sql -o schema.out
grep -nE 'Warning!|^Msg ' schema.out
Expect no output from
grep
. A
Warning!
line naming a key length is message 1945 and predicts
Msg 1946
on a production insert.
Then audit the schema the engine actually has, as
schema-audit.sql
:
sql
-- 1. Index keys over budget. Expect zero rows.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, i.type_desc,
       SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END) AS key_bytes,
       CASE WHEN i.type = 1 THEN 900 ELSE 1700 END AS budget
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
                            AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.type IN (1, 2) AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, i.type, i.type_desc
HAVING SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END)
       > CASE WHEN i.type = 1 THEN 900 ELSE 1700 END;

-- 2. Unique indexes over a nullable column with no filter: one NULL row each. Expect zero.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, c.name AS column_name
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
                            AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.is_unique = 1 AND i.has_filter = 0 AND c.is_nullable = 1;

-- 3. VARCHAR or CHAR key columns on a SQL collation: the lost seek. Expect zero rows.
SELECT DISTINCT OBJECT_NAME(c.object_id) AS table_name, c.name AS col, c.collation_name
FROM sys.columns AS c
JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
                            AND ic.is_included_column = 0
JOIN sys.types AS t ON t.user_type_id = c.user_type_id
WHERE t.name IN ('varchar', 'char') AND c.collation_name LIKE 'SQL[_]%';

-- 4. Sequences left on the type minimum because START WITH was omitted. Expect zero rows.
SELECT name, CAST(start_value AS BIGINT) AS start_value
FROM sys.sequences WHERE CAST(start_value AS BIGINT) < 0;

-- 5. The two settings the design assumed. Read them, do not assume them.
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS db_collation,
       (SELECT value FROM sys.database_scoped_configurations
        WHERE name = 'IDENTITY_CACHE') AS identity_cache;
bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -W \
  -i schema-audit.sql -o schema-audit.out
Checks 1 to 4 return no rows in a clean schema. Check 5 is the one you read rather than pass:
identity_cache
of
0
means gaps are off,
1
means an
INT IDENTITY
will jump by about a thousand across the next reconfiguration.
Last, confirm the seek survived on one real lookup:
sql
SET STATISTICS IO ON;
DECLARE @p NVARCHAR(320) = N'u9999@example.com';
SELECT id FROM dbo.users WHERE email = @p;
SET STATISTICS IO OFF;
Expect single-digit logical reads that do not grow with the table. Reads that grow with the table are the implicit conversion in section 3, not a cold cache.
通过
sqlcmd
的
-m-1
运行 DDL,因为消息 1945 的严重级别为 10,而单独使用
-b
根本不会报告严重级别 10 的消息,因此即使迁移输出了该消息,仍会以状态码 0 退出:
-m-1
是 ODBC 版
sqlcmd
的指令,也就是
mssql-tools18
中的 18.x 构建版本或 Microsoft 命令行实用工具所附带的版本。
go-sqlcmd 1.x、
brew install sqlcmd
安装的构建版本和
winget install sqlcmd
安装的构建版本,在任何
-m
值下都不会为严重级别 10 的消息打印
Msg
标头,因此使用这些构建版本时,下面的
grep
找不到可供报告的消息 1945。如果消息编号很重要,请查询
sys.messages
,或通过 ODBC 构建版本运行该语句。
bash
export SQLCMDPASSWORD='<password>'
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -b -m-1 \
  -i schema.sql -o schema.out
grep -nE 'Warning!|^Msg ' schema.out
期望
grep
没有任何输出。指出键长度超限的
Warning!
行就是消息 1945,它预示着生产环境中的插入操作将出现
Msg 1946
。
然后通过
schema-audit.sql
审计引擎实际拥有的 Schema:
sql
-- 1. Index keys over budget. Expect zero rows.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, i.type_desc,
       SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END) AS key_bytes,
       CASE WHEN i.type = 1 THEN 900 ELSE 1700 END AS budget
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
                            AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.type IN (1, 2) AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, i.type, i.type_desc
HAVING SUM(CASE WHEN c.max_length = -1 THEN 0 ELSE c.max_length END)
       > CASE WHEN i.type = 1 THEN 900 ELSE 1700 END;

-- 2. Unique indexes over a nullable column with no filter: one NULL row each. Expect zero.
SELECT OBJECT_NAME(i.object_id) AS table_name, i.name AS index_name, c.name AS column_name
FROM sys.indexes AS i
JOIN sys.index_columns AS ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
                            AND ic.is_included_column = 0
JOIN sys.columns AS c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.is_unique = 1 AND i.has_filter = 0 AND c.is_nullable = 1;

-- 3. VARCHAR or CHAR key columns on a SQL collation: the lost seek. Expect zero rows.
SELECT DISTINCT OBJECT_NAME(c.object_id) AS table_name, c.name AS col, c.collation_name
FROM sys.columns AS c
JOIN sys.index_columns AS ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
                            AND ic.is_included_column = 0
JOIN sys.types AS t ON t.user_type_id = c.user_type_id
WHERE t.name IN ('varchar', 'char') AND c.collation_name LIKE 'SQL[_]%';

-- 4. Sequences left on the type minimum because START WITH was omitted. Expect zero rows.
SELECT name, CAST(start_value AS BIGINT) AS start_value
FROM sys.sequences WHERE CAST(start_value AS BIGINT) < 0;

-- 5. The two settings the design assumed. Read them, do not assume them.
SELECT DATABASEPROPERTYEX(DB_NAME(), 'Collation') AS db_collation,
       (SELECT value FROM sys.database_scoped_configurations
        WHERE name = 'IDENTITY_CACHE') AS identity_cache;
bash
sqlcmd -S <server-name>.database.windows.net,1433 -d <database> -U <user> -C -W \
  -i schema-audit.sql -o schema-audit.out
在干净的 Schema 中,检查 1 至 4 应不返回任何行。检查 5 不是用来判断通过与否,而是需要阅读:
identity_cache
为
0
表示间隙已关闭;为
1
表示
INT IDENTITY
会在下一次重新配置时跃升约一千。
最后,在一个真实查找上确认 Seek 仍然有效:
sql
SET STATISTICS IO ON;
DECLARE @p NVARCHAR(320) = N'u9999@example.com';
SELECT id FROM dbo.users WHERE email = @p;
SET STATISTICS IO OFF;
预期逻辑读取次数为个位数,且不随表的大小增长。读取量随表增长是第 3 节所述的隐式转换导致的,而不是冷缓存造成的。

Do not

不要

  • Do not read message 1945 as informational. It is the only notice given, and severity 10 means neither
    sqlcmd -b
    nor most drivers raise it.
  • Do not size a key column in characters. The limit is bytes, and Unicode doubles it.
  • Do not use
    VARCHAR
    under the default collation for anything an application looks up by value.
  • Do not add
    LOWER()
    or
    UPPER()
    around a column to fix a collation problem. That costs the index too, and it is
    t-sql-correctness
    .
  • Do not reach for trace flag 272. It is rejected, with
    Msg 40518
    on the container and
    Msg 2571
    (no permission, even as
    dbo
    ) on Azure SQL Database. The lever is
    IDENTITY_CACHE = OFF
    .
  • Do not put an invoice or ticket number, or anything an auditor reads, on a bare
    IDENTITY
    .
  • Do not create a
    SEQUENCE
    without
    START WITH
    .
  • Do not give a model two or three optional unique columns and expect PostgreSQL NULL semantics.
  • Do not store a value in a
    json
    document and then filter on it. Promote it.
  • Do not add a clustered index only because you believe this engine demands one. A heap can be created and takes rows.
  • 不要把消息 1945 当作纯信息提示。它是唯一的通知,而严重级别 10 意味着
    sqlcmd -b
    和大多数驱动程序都不会报告该消息。
  • 不要以字符数确定键列大小。限制以字节为单位,而 Unicode 会将字节数翻倍。
  • 不要在默认排序规则下,将
    VARCHAR
    用于任何需要按值查找的内容。
  • 不要在列外包裹
    LOWER()
    或
    UPPER()
    来解决排序规则问题。这同样会使索引无法使用,属于
    t-sql-correctness
    的范畴。
  • 不要使用跟踪标志 272。它会被拒绝:容器中会报
    Msg 40518
    ,在 Azure SQL Database 中则会报
    Msg 2571
    ,即使以
    dbo
    身份运行也没有权限。可用的控制项是
    IDENTITY_CACHE = OFF
    。
  • 不要将发票号、工单号或任何供审计人员读取的数字放在普通的
    IDENTITY
    上。
  • 不要创建缺少
    START WITH
    的
    SEQUENCE
    。
  • 不要设计包含两三个可选唯一列的模型,却期望获得 PostgreSQL 的 NULL 语义。
  • 不要把值存储在
    json
    文档中后再对其进行筛选。应将其提升为独立列。
  • 不要仅仅因为认为此引擎要求聚集索引就添加聚集索引。堆表也可以创建,并且能够容纳数据行。

References

参考资料

  • Open the statements behind each number when you need the statement behind a number above, the two query plans, or the setup to run them.
  • Read Maximum capacity specifications before designing a wide composite key.
  • Read Collation and Unicode support before choosing a database collation: SQL against Windows collations, and UTF-8.
  • Read json data type before putting a document in a column, for the index restrictions and the size limits.
  • Read Database scoped configurations before setting
    IDENTITY_CACHE
    , and T-SQL differences when a statement is refused with 40510, 40515, 40517, 40518 or 2571.
  • ef-core-azure-sql
    and
    sqlalchemy-azure-sql
    : how each mapper reaches these lengths and the default it lands on. The other mapper skills are listed in
    skill.spec.jsonc
    .
  • t-sql-correctness
    for query-level correctness,
    t-sql-json-and-openjson
    for querying a document column,
    vector-search-azure-sql
    for the vector type and its indexing.
  • schema-migrations-safely
    and
    sql-database-projects
    for applying a change to a live database, and
    provision-azure-sql-db
    for creating the database and naming its collation.
  • 当你需要了解上述某个数字背后的依据、两个查询计划或运行它们的设置时,请打开每个数字背后的依据。
  • 在设计宽复合键之前,请阅读最大容量规范。
  • 在选择数据库排序规则之前,请阅读排序规则和 Unicode 支持:SQL 与 Windows 排序规则,以及 UTF-8。
  • 在把文档放入列之前,请阅读 json 数据类型,了解索引限制和大小上限。
  • 在设置
    IDENTITY_CACHE
    之前,请阅读数据库范围配置;当语句因 40510、40515、40517、40518 或 2571 被拒绝时,请阅读 T-SQL 差异。
  • ef-core-azure-sql
    和
    sqlalchemy-azure-sql
    :了解每个 mapper 如何达到这些长度限制,以及最终采用的默认值。其他 mapper skill 列于
    skill.spec.jsonc
    。
  • t-sql-correctness
    用于查询层面的正确性,
    t-sql-json-and-openjson
    用于查询文档列,
    vector-search-azure-sql
    用于 vector 类型及其索引。
  • schema-migrations-safely
    和
    sql-database-projects
    用于把变更应用到在线数据库,
    provision-azure-sql-db
    用于创建数据库并指定其排序规则。