# Parsing and Compiling of SQL Statements

![`smart`](SQLParseandCompile_aa_005_20220512.png)

-----------------------------------------------------------
After the TiDB server's Protocol Layer receives to the SQL statement sent by the client program, it begins to process the text of the SQL statement. The first thing it does is to asynchronously get the start_ts of the SQL statement from PD, which is the TSO when the SQL statement starts. Afterwards, it will go through the Parse and Compile modules respectively, and finally generate an execution plan to be passed to the Executor module.

1. Asynchronously read the TSO when the current SQL statement starts to execute, i.e. the start_ts information, which is accomplished by the PD Client module.

2. The Parse module uses the lexer and the yacc parser to transform SQL statements into an abstract syntax tree (AST), which is then passed to the Compile module.

3. After the AST is received by the Compile module, it first enters the Preprocess process, which mainly performs pre-processing, statement legality checking and name binding. In addition, after the Preprocess process, a decision will be made:
- If the SQL statement only reads one row of data (PointGet), such as SQL operations with unique index or primary key index as the query condition, then this statement will not be passed to the subsequent Optimize process to generate an execution plan, but will be executed directly to obtain data, thus saving the cost of the optimization process. This optimization is called PointGet.
- If the SQL statement has not been optimized with PointGet, it will enter the Optimize process, which is divided into two parts.
  - (1) Logical optimization, mainly based on the equivalence exchange rules of relational algebra to do some logical transformation.
  - (2) Physical optimization, based on the logical optimization result, combined with statistical information, selects physical operators and the optimal execution path. Regarding the optimization process, logical optimization and physical optimization, we will explain in detail in the TiDB Performance Optimization course.

After the optimization process, the physical execution plan is finally generated. With the physical execution plan, TiDB server can then execute it and access the data in the storage engine.


