SQLite 语句前面可以添加关键字 EXPLAIN 或短语 EXPLAIN QUERY PLAN,用于描述表的详细信息。

任一修改都会导致 SQLite 语句表现为查询,并返回有关在省略 EXPLAIN 或 EXPLAIN QUERY PLAN 关键字时 SQLite 语句如何操作的信息。

  • EXPLAIN 和 EXPLAIN 的输出EXPLAIN QUERY PLAN 仅用于交互式分析和调试。
  • 输出格式的详细信息可能会因 SQLite 的一个版本而异。
  • 应用程序不应使用 EXPLAIN或 EXPLAIN QUERY PLAN,因为它们的确切行为是可变的并且仅部分记录。

语法

在 SQLite 中使用 EXPLAIN 语句的语法如下:

EXPLAIN [SQLite Query] 

EXPLAIN QUERY PLAN 的语法如下:

EXPLAIN QUERY PLAN [SQLite Query] 

示例:

考虑一个名为 Employee 的数据库表,其中以下记录:

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

现在,让我们检查一下 EXPLAIN with SELECT 语句的结果:

sqlite> EXPLAIN SELECT * FROM Employee; 

这将产生如下所示的结果:

addr  opcode         p1    p2    p3    p4             p5  comment      
----  -------------  ----  ----  ----  -------------  --  -------------
0     Init           0     11    0                    0   Start at 11
1     OpenRead       0     2     0     5              0   root=2 iDb=0; Employee
2     Rewind         0     10    0                    0   
3     Column         0     0     1                    0   r[1]=Employee.EmpID
4     Column         0     1     2                    0   r[2]=Employee.Name
5     Column         0     2     3                    0   r[3]=Employee.City
6     Column         0     3     4                    0   r[4]=Employee.Age
7     Column         0     4     5                    0   r[5]=Employee.Salary
8     ResultRow      1     5     0                    0   output=r[1..5]
9     Next           0     3     0                    1   
10    Halt           0     0     0                    0   
11    Transaction    0     0     4     0              1   usesStmtJournal=0
12    Goto           0     1     0                    0 

现在,让我们检查以下带有 SELECT 语句的 EXPLAIN QUERY PLAN:

sqlite> EXPLAIN QUERY PLAN SELECT * FROM Employee WHERE Salary >= 2800; 

以下代码的结果将是:

QUERY PLAN
`--SCAN Employee