Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Implementation Matters: CTEs In Postgres And SQL Server

$
0
0

In SQL Server, if you write this query:

WithAllPostsAS(SELECT*FROMStackOverflow.dbo.Posts) SELECT* FROMAllPosts WHEREId=1;

SQL Server builds a query plan for the entire operation at once, and passes the WHERE clause filter into the CTE. The resulting query plan is efficient, doing just a single clustered index seek.

In Postgres, CTEs are processed separately first , and subsequent WHERE clauses aren’t applied until later. That means the above query works just fine but performs horribly. You’ll get much better results if you include your filters inside each CTE, like this:

WithAllPostsAS(SELECT*FROMStackOverflow.dbo.PostsWHEREId = 1) SELECT* FROMAllPosts;

That’s less than ideal.


Viewing all articles
Browse latest Browse all 3160

Trending Articles