为什么删除 UNIQUE 约束会将我的数据库大小减少到不到一半?

Why did the removal of a UNIQUE constraint reduce the size of my database to less than half?

这是一个重现结果的示例。数据库从 144.4 MB 变为 60.6 MB。

我的 UNIQUE 专栏通常包含几段文字(例如 500 字)。

import sqlite3
import os

db_file = 'databases/test.db'
conn = sqlite3.connect(db_file) # file path
cur = conn.cursor()

# CREATE table
cur.execute('''CREATE TABLE orig_table (
               key TEXT PRIMARY KEY,
               unq TEXT UNIQUE
           )''')
records = []
for i, record in enumerate(range(10000)):
    records.append(('primary' + str(i), 500 * (' unique' + str(i))))
cur.executemany("INSERT INTO orig_table VALUES (?,?)", records)
conn.commit()

print('Original size:', str( round(os.path.getsize(db_file)/1000000,1)) + ' MB')

# Remove UNIQUE constraint
cur.execute('''CREATE TABLE new_table (
               key TEXT PRIMARY KEY,
               unq TEXT
           )''')
cur.execute('''INSERT INTO new_table (key, unq)
               SELECT key, unq FROM orig_table
            ''')
cur.execute('DROP TABLE orig_table')
conn.commit()
conn.execute('VACUUM')
conn.close()

print('Final size:', str( round(os.path.getsize(db_file)/1000000,1)) + ' MB')

UNIQUE 约束使用列的索引来加速对每个新值的唯一性验证。大小差异对应索引的大小。