SQL is a declarative language working on sets of rows. There is no IF-THEN-ELSE branching or FOR/WHILE/UNTIL loops typically found in procedural languages. However, SQL is Turing-Complete, and you can achieve similar outcomes in a declarative way.
I'm running the following example on the following table:
Are you worried by a query that seem to read the same table four times? Remember that SQL is declarative. You cannot infer the execution complexity from it. With EXPLAIN you will see exactly what is executed.
I'm calling the prepared statement for each combination of parameters:
Anyway, even if a generic plan is used, only one branch will be executed. The scenario discriminator conditions are evaluated once with a One-Time Filter, which efficiently filters out branches that do not apply. These discarded branches will be clearly indicated as (never executed) in the EXPLAIN ANALYZE output. This strategy guarantees the minimization of unnecessary processing, ensuring that only the pertinent branch is executed based on the provided conditions. In contrast to the estimated cost, the actual execution time is solely influenced by the active branch, while the rest report an actual time=0.000.
postgres=#setplan_cache_modetoforce_generic_plan;postgres=#explain(costson)executedemo_where(true,true);QUERYPLAN----------------------------------------------------------------------------------------------------------------------------------------------SeqScanondemo(cost=0.00..47.00rows=466width=16)Filter:(((a=1)AND(b=1)AND$1AND$2)OR((a=1)AND$1AND(NOT$2))OR((b=1)AND(NOT$1)AND$2)OR((NOT$1)AND(NOT$2)))(2rows)Enter fullscreen modeExit fullscreen mode
Clustering Factor for YugabyteDB Index Scan: correlation between secondary indexes and the primary key
#yugabytedb#distributed#postgres#database
Performance of range queries in B-Tree and LSM indexes
#postgres#database#yugabytedb#sql
Observing CPU/RAM/IO pressure in YugabyteDB with Linux PSI on AlmaLinux8 (Pressure Stall Information)
#yugabytedb#linux#performance
Built on Forem — the open source software that powers DEV and other inclusive communities.