Posts

Showing posts with the label window functions

Aggregate Functions

Image
Introduction Aggregate Functions are functions that perform a calculation on a set of values (multiple rows) and return a single value. They are often used with the GROUP BY clause to group data, or combined with OVER to become Window Functions to calculate without losing detailed rows. Postgres natively supports Aggregate Functions which can be divided into the following groups: Basic Aggregate Functions SUM(column) : Calculates the sum of all numeric values in the column (ignores NULL). AVG(column) : Calculates the average value of the column (ignores NULL). COUNT : Counts the number of rows COUNT(*) counts all rows, including rows with NULL values COUNT(column) only counts rows with non-NULL values. MAX(column) : Finds the maximum value in the column, works with numbers, strings and dates. MIN(column) : Finds the minimum value in the column. NULL Handling Functions COALESCE(val1, val2, ..., valN) : Returns the first non- NULL value in the input list. This function is often pair...

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...