嵌套视图执行顺序:示例中视图执行逻辑与过滤机制问询
Great question! Let's unpack how SQL handles nested views using your example.
First, let's clarify a key point: regular views (non-materialized) aren't pre-executed or stored as physical data. They're essentially just saved query definitions. When you query a view that references another view, the database engine doesn't run the inner view first and then feed its results into the outer view. Instead, it merges the definitions of both views into a single, combined query plan.
Applying this to your code example
Your views are defined as:
create or replace view QueryView2 as Select column1 ... columnx from SomeIrrelevantView a left join QueryView1 b on a.Id= b.Id where [conditions]; Create or replace view QueryView1 as select column1 ... columny from Table1;
When you run a query against QueryView2, the database will rewrite the logic to look like this under the hood:
Select column1 ... columnx from SomeIrrelevantView a left join (select column1 ... columny from Table1) b on a.Id= b.Id where [conditions];
Your specific questions answered
- Which view runs first? There's no strict "order of execution" for the views themselves. The database's query optimizer will evaluate the combined query and choose the most efficient way to retrieve data—this might involve accessing
Table1andSomeIrrelevantViewin whatever order makes sense based on indexes, data size, and filter conditions. - Will QueryView1 return all Table1 records first, then filter? Almost certainly not. Modern SQL optimizers use a technique called predicate pushdown: they'll push the
where [conditions]fromQueryView2down to the underlyingTable1query whenever possible. This means only the records fromTable1that match the filtered conditions (and join criteria) will be retrieved, not the entire table.
The only exception here would be if you're using materialized views (which store pre-computed results), but your example uses regular views, so this doesn't apply.
内容的提问来源于stack exchange,提问作者arianit ax

