Posts

Showing posts with the label cte

Window Function

Image
Introduction When using GROUP BY to aggregate duplicate data rows, relevant individual data rows are lost. Window Function is used to overcome this limitation. It helps perform aggregation calculations on a set of related rows while preserving the original data rows without collapsing them. Window Function executes after WHERE, GROUP BY and HAVING clauses, but before DISTINCT and ORDER BY in the main statement. Therefore, you cannot place a Window Function directly inside the WHERE clause. If you want to filter data based on the result of a Window Function , you must use a temporary table such as a CTE or Subquery . How to Use To construct a Window Function , combine a Function and a Clause as follows: SELECT FUNCTION () OVER ( PARTITION BY col1 ORDER BY col2 ROWS / RANGE BETWEEN < START > AND < END > ) AS col_name FROM table_name; Function : The function placed before the OVER keyword, such as SUM(), AVG(), ROW_NUMBER(...

SQL order of execution

Image
Introduction In SQL in general and PostgreSQL in particular, the order of writing keywords in code (Lexical Order) is completely different from the order in which the Database Engine actually executes the statement ( Logical Execution Order ). A query with full command structures like this will be parsed and executed by the Optimizer in a strict logical order from root (data source) to top (displayed results). [ WITH [ RECURSIVE ] cte_name AS (...) ] SELECT [ DISTINCT [ ON (...)] ] columns FROM source_table [ TABLESAMPLE ... ] [ JOIN_clauses ] [ WHERE raw_filter_conditions ] [ GROUP BY { column | ROLLUP | CUBE | GROUPING SETS } ] [ HAVING group_filter_conditions ] [ WINDOW window_name AS (...) ] [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] other_select_statement ] [ ORDER BY sort_order ] [ LIMIT limit_count ] [ OFFSET offset_count ] [ FOR UPDATE / FOR SHARE [ SKIP LOCKED ] ]; Below is the execution order from the first step to the last step...