Summary for the Impatient
A one-line UDF in a join condition, dateOr99(c.expiration_date) > cs.max_year (NULL becomes 9999-01-01), against the same condition written out as IS NULL OR >, at up to 8,000 rows a side (PG18 and SQL Server also at 80,000 and 800,000). No form of the UDF scaled unless its result was precomputed in an index, not even SQL Server's inlined one:
- SQL Server (Azure SQL Database, compatibility level 170): without inlining, 26 s, quadratic, on one thread. Written out: index seeks, linear, 125 ms; 11 s at 800,000 rows a side. Inlining (SQL Server 2019+): 32x faster, still quadratic. At 80,000 rows a side, 64 s. Inlining plus an indexed computed column: 29 ms, linear, query unchanged; 2.3 s at 800,000.
- PG18 (PG17 the same): written out is no faster than an inlined SQL function; both check every pair, quadratic. PL/pgSQL is never inlined and is 4.5x slower than that. What scales: an expression index on the function (declared IMMUTABLE), 13 ms at 8,000 rows a side and 1.6 s at 800,000. A
UNION ALLsplit is as fast up to 8,000, then checks every pair at 80,000: 13 s. - MySQL 8.0.39: every form tried is quadratic, a functional index and a
UNION ALLsplit included. Written out is 7.6x faster than the stored function. - PG18 equality joins: a PL/pgSQL function left at the default VOLATILE on both sides of
=forces a nested loop: 3.3 s, against 1.9 ms written inline (2,000 rows a side). Declaring it IMMUTABLE, when it is, fixes it.
Single runs on ExoBench's dev server.
The function that never expired
Back in 2017 I was working at a Fortune 500 fintech company and I noticed something curious, every financial instrument needed an expiration date. To make the massive queries we ran easier, there was a UDF, dateOr99(EXPIRATION_DATE), that translated a NULL expiration date into an expiry of 9999-01-01.
It went into join conditions over energy futures, like this one:
JOIN ... AND dateOr99(contract.EXPIRATION_DATE) > contract_sheet.max_year
The same kind of condition turned up in several joins, across contract_sheet, contracts_validated, contracts_repriced and a few more.
As the number of listed futures grew linearly, performance fell off much faster than that, and everyone was wondering why.
At some point someone just tried replacing the UDF with contract.EXPIRATION_DATE is null OR contract.EXPIRATION_DATE > contract_sheet.max_year, and made the same change in all the other places. Everything was fast again.
Only then did we finally look at the query plans. dateOr99(contract.EXPIRATION_DATE) had caused nested loop joins, and we were rudely introduced to the concept of sargability (i.e. query introspectability).
Ironically, just two years later, SQL Server 2019 introduced scalar UDF inlining, which would have solved all of our problems.
That was my rude awakening to the dangers of UDFs, and ever since then I've been obsessed with understanding how they work and when they fail.
The original queries and schema are long gone, but I could rebuild the shape of that join and run it on SQL Server, PostgreSQL and MySQL, to see what each of them does with a function like dateOr99. Also, I wanted to test that line about SQL Server 2019. Would inlining really have solved all of our problems?
Rebuilding it
About nine years later, I started with two questions. When did SQL Server's inlining arrive, and which UDFs does it cover? Microsoft's docs answered that (the inlining appendix). Does a UDF in a join condition force a nested loop? A round of small probes said it depends on the engine and on the shape of the condition.
Then I rebuilt the join and ran it with ExoBench, which built the tables fresh at each size and handed back each plan with its timing. contracts holds N contracts on 8 different energy products (I'm talking ticker symbols like CL - Shenzhen Co, HH - Henry Hub, etc...), indexed on (product, expiration_date). Let's say three per product never expire, and the rest expire one per product per day. contract_sheet has a line per contract, each with a product and its own max_year, which despite the name holds a date, later than every listed expiration and different on every line. The query counts the contracts on each line's product that outlive its max_year:
SELECT COUNT(*) AS outliving
FROM contract_sheet cs
JOIN contracts c ON c.product = cs.product
AND dateOr99(c.expiration_date) > cs.max_year
On SQL Server the UDF needs to be qualified so it looks like ${SCHEMA}.dateOr99 (see the method appendix). Only the 3 contracts per product that never expire outlive a contract-line, so the answer is 3N, and every version on every engine needs to return it. I ran it at four sizes, from 1,000 to 8,000 sheet lines. Each line meets every contract on its product, N times N/8 pairs, 8 million at the largest size.
Here's dateOr99 in each engine's dialect:
-- SQL Server; the version without inlining adds WITH INLINE = OFF after RETURNS DATE
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;
-- PostgreSQL, as a SQL function and as PL/pgSQL
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
-- MySQL; one version adds DETERMINISTIC
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE NO SQL RETURN COALESCE(d, '9999-01-01');
At first I decided to try something easy, give everything the same expiration. Postgres and SQL Server noticed that because 8,000 lines were asking just 8 questions, one per product. SQL Server collapsed the sheet to one row per product before the join and ran the UDF with inlining off in 55 ms. PG18 cached the lookup for the inlined SQL version. PG18's PL/pgSQL version got no such discount, and neither did MySQL's stored function. In real life this doesn't happen but it's a good baseline for 'optimistic' cases.
That brought the story back. After two more pilots, one main run measured every version of the join at all four sizes. From the runs behind the cards below:
SQL Server, the UDF with inlining off, 8,000 sheet lines: a little under half a minute.
The same join with the condition written by hand: an eighth of a second.
SQL Server without inlining
The SQL Server here is Azure SQL Database, which runs the SQL Server engine at compatibility level 170, the level of SQL Server 2025.
Two stand-ins play a SQL Server without inlining on it. One is dateOr99 declared WITH INLINE = OFF, which keeps it from ever being inlined, the way every scalar UDF ran before SQL Server 2019. The other is the inlinable function under the QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_140 hint, which compiles the query the way SQL Server 2017 would. Both call the UDF for every pair on one thread, and in the main run they took about the same time up to 4,000 lines. So the cards show the first, and the hint's calls are in the SQL Server appendix.
The before and after from the story:
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE WITH INLINE = OFF AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 337 ms | At 1,000 sheet lines SQL Server hashes the sheet on product, probes it with every contract, and calls dateOr99 in the Probe Residual for each contract and sheet line on the same product, on database 09222264. The plan is serial, Non-Parallel Reason TSQLUserDefinedFunctionsNotParallelizable, and takes 337 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.249585 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.249585 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=337 CPUms=337)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=1000 IO=0 CPU=0.23725 SubtreeCost=0.248985 AvgRowSize=9) (actual Rows=3000 Executions=1 Elapsedms=337 CPUms=337)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_36a087da_a2d5_4896_b537_b6f48a84b969].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1344kB Output=1344kB Used=512kB
-> Clustered Index Scan [PK__contract__F5AE5F6261C80082] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=1000 RowsRead=1000 IO=0.00386574 CPU=0.001257 SubtreeCost=0.00512274 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=4 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1344kB MaxUsed=512kB Required=1024kB Desired=1344kB Requested=1344kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=12ms CPU=6ms Memory=360kB CachedPlanSize=48kB
CPU Time: 337 ms
Execution Time: 337 ms | 47.24s |
| 2K | 1.5s | At 2,000 lines SQL Server runs the same Hash Match and the call takes 1,464 ms, more than four times as long as at half the size. CPU is 1,345 ms, and the plan prints its first waits, SOS_SCHEDULER_YIELD and RESOURCE_GOVERNOR_IDLE.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.874901 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.874901 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=1464 CPUms=1345)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=2000 IO=0 CPU=0.855321 SubtreeCost=0.873701 AvgRowSize=9) (actual Rows=6000 Executions=1 Elapsedms=1464 CPUms=1345)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_02f8bddc_5d67_4f57_99a3_183d59a544cc].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1632kB Output=1632kB Used=512kB
-> Clustered Index Scan [PK__contract__F5AE5F6298858B22] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=2000 RowsRead=2000 IO=0.00534722 CPU=0.002357 SubtreeCost=0.00770422 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 4 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1632kB MaxUsed=512kB Required=1024kB Desired=1632kB Requested=1632kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=119 WaitCount=336
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=100 WaitCount=12
Compile: Time=12ms CPU=7ms Memory=368kB CachedPlanSize=48kB
CPU Time: 1345 ms
Execution Time: 1464 ms | 2.03s |
| 4K | 6.6s | At 4,000 lines the same serial SQL Server plan takes 6,607 ms, four and a half times as long as at half the size. CPU is 5,559 ms of it, and the SOS_SCHEDULER_YIELD waits come to 1,052 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=3.32125 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=3.32125 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=6607 CPUms=5559)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=4000 IO=0 CPU=3.28718 SubtreeCost=3.31885 AvgRowSize=9) (actual Rows=12000 Executions=1 Elapsedms=6606 CPUms=5559)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_fa2faf46_b35e_4f8e_8cb2_0bf9faf9f4ba].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1184kB Output=1184kB Used=400kB
-> Clustered Index Scan [PK__contract__F5AE5F622C54F392] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=4000 RowsRead=4000 IO=0.00831019 CPU=0.004557 SubtreeCost=0.0128672 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 4 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1184kB MaxUsed=400kB Required=1024kB Desired=1184kB Requested=1184kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=1052 WaitCount=1388
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=986 WaitCount=148
Compile: Time=15ms CPU=9ms Memory=352kB CachedPlanSize=48kB
CPU Time: 5559 ms
Execution Time: 6607 ms | 7.14s |
| 8K | 26.2s | At 8,000 lines SQL Server takes 26,221 ms, about four times as long as at half the size; every doubling here has roughly quadrupled the time, which follows the pairs of sheet line and contract, not the lines. CPU is 21,769 ms, and the SOS_SCHEDULER_YIELD waits reach 4,469 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=12.9961 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=12.9961 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=26221 CPUms=21769)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=8000 IO=0 CPU=12.9338 SubtreeCost=12.9913 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=26220 CPUms=21768)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_b6781704_4a7e_4721_8dc0_5eafcedb427e].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=2368kB Output=2368kB Used=632kB
-> Clustered Index Scan [PK__contract__F5AE5F62D8EAA6B7] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 3 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=8000 RowsRead=8000 IO=0.0134954 CPU=0.008957 SubtreeCost=0.0224524 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=10 CPUms=10)
Node Id: 4 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=17 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=2368kB MaxUsed=632kB Required=1024kB Desired=2368kB Requested=2368kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=4469 WaitCount=5432
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=4226 WaitCount=684
Compile: Time=19ms CPU=13ms Memory=336kB CachedPlanSize=48kB
CPU Time: 21769 ms
Execution Time: 26221 ms | 26.82s |
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 15 ms | At 1,000 sheet lines SQL Server turns IS NULL OR > into index seeks: for each sheet line a Merge Interval builds two ranges, the NULL dates and the dates past max_year, and the Index Seek on contracts_product_expiration runs 2,000 times. The plan runs on one thread in 15 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.175735 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1017],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.175735 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=15 CPUms=15)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1017
Defined Values: Expr1017 = Count(*)
-> Nested Loops (Inner Join) (est Rows=1000 IO=0 CPU=0.00418 SubtreeCost=0.175134 AvgRowSize=9) (actual Rows=3000 Executions=1 Elapsedms=15 CPUms=15)
Node Id: 2 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F620BB0661F] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.16435 AvgRowSize=9) (actual Rows=3000 Executions=1000 Elapsedms=14 CPUms=14)
Node Id: 4 Mode: Row Table Cardinality: 1000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=1000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=2000 Executions=1000 Elapsedms=9 CPUms=9)
Node Id: 5 Mode: Row
Element: MergeInterval
I/O: EndOfScans=1000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=2000 Executions=1000 Rebinds=1000 Elapsedms=9 CPUms=9)
Node Id: 6 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1000
Memory Grant: Input=1024kB Output=1024kB Used=16kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 7 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=2000 Executions=1000 Elapsedms=0 CPUms=0)
Node Id: 8 Mode: Row
I/O: EndOfScans=1000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 9 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=1000 Executions=1000 Elapsedms=0 CPUms=0)
Node Id: 10 Mode: Row
I/O: EndOfScans=1000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 11 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=1000 Executions=1000 Elapsedms=0 CPUms=0)
Node Id: 12 Mode: Row
I/O: EndOfScans=1000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.16435 AvgRowSize=9) (actual Rows=3000 RowsRead=3000 Executions=2000 Elapsedms=4 CPUms=4)
Node Id: 13 Mode: Row Table Cardinality: 1000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=2000 LogicalReads=4000 EndOfScans=2000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xB8E80EDE479B3C86
Degree Of Parallelism: 1
Memory Grant: Granted=1024kB MaxUsed=16kB Required=16kB Desired=24kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=13ms CPU=6ms Memory=352kB CachedPlanSize=48kB
CPU Time: 15 ms
Execution Time: 15 ms | 0.83s |
| 2K | 32 ms | At 2,000 lines the SQL Server plan is unchanged, still two seeks per sheet line, and the time roughly doubles to 32 ms. Each line's seeks find only the three contracts on its product that never expire.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.348928 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1017],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.348928 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=32 CPUms=32)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1017
Defined Values: Expr1017 = Count(*)
-> Nested Loops (Inner Join) (est Rows=2000 IO=0 CPU=0.00836 SubtreeCost=0.347727 AvgRowSize=9) (actual Rows=6000 Executions=1 Elapsedms=32 CPUms=32)
Node Id: 2 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F622D08A9E5] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 3 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=1999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.3287 AvgRowSize=9) (actual Rows=6000 Executions=2000 Elapsedms=29 CPUms=29)
Node Id: 4 Mode: Row Table Cardinality: 2000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=2000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=4000 Executions=2000 Elapsedms=19 CPUms=19)
Node Id: 5 Mode: Row
Element: MergeInterval
I/O: EndOfScans=2000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=4000 Executions=2000 Rebinds=2000 Elapsedms=18 CPUms=18)
Node Id: 6 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=2000
Memory Grant: Input=1024kB Output=1024kB Used=16kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 7 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=4000 Executions=2000 Elapsedms=1 CPUms=1)
Node Id: 8 Mode: Row
I/O: EndOfScans=2000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 9 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=2000 Executions=2000 Elapsedms=0 CPUms=0)
Node Id: 10 Mode: Row
I/O: EndOfScans=2000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 11 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=2000 Executions=2000 Elapsedms=0 CPUms=0)
Node Id: 12 Mode: Row
I/O: EndOfScans=2000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=1999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.3287 AvgRowSize=9) (actual Rows=6000 RowsRead=6000 Executions=4000 Elapsedms=8 CPUms=8)
Node Id: 13 Mode: Row Table Cardinality: 2000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=4000 LogicalReads=8000 EndOfScans=4000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x0D0183CC03267619
Degree Of Parallelism: 1
Memory Grant: Granted=1024kB MaxUsed=16kB Required=16kB Desired=24kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=1 WaitCount=4000
Compile: Time=14ms CPU=7ms Memory=352kB CachedPlanSize=48kB
CPU Time: 32 ms
Execution Time: 32 ms | 0.56s |
| 4K | 64 ms | At 4,000 lines SQL Server's seeks double again, to 8,000, and so does the time, 64 ms. The work per sheet line is fixed, so the time grows in step with the sheet.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.695314 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1017],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=0.695314 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=64 CPUms=64)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1017
Defined Values: Expr1017 = Count(*)
-> Nested Loops (Inner Join) (est Rows=4000 IO=0 CPU=0.01672 SubtreeCost=0.692913 AvgRowSize=9) (actual Rows=12000 Executions=1 Elapsedms=63 CPUms=63)
Node Id: 2 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F622BBD5151] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 3 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=3999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.6574 AvgRowSize=9) (actual Rows=12000 Executions=4000 Elapsedms=58 CPUms=58)
Node Id: 4 Mode: Row Table Cardinality: 4000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=4000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=8000 Executions=4000 Elapsedms=38 CPUms=38)
Node Id: 5 Mode: Row
Element: MergeInterval
I/O: EndOfScans=4000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=8000 Executions=4000 Rebinds=4000 Elapsedms=36 CPUms=36)
Node Id: 6 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=4000
Memory Grant: Input=1024kB Output=1024kB Used=16kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 7 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=8000 Executions=4000 Elapsedms=3 CPUms=3)
Node Id: 8 Mode: Row
I/O: EndOfScans=4000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 9 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=4000 Executions=4000 Elapsedms=0 CPUms=0)
Node Id: 10 Mode: Row
I/O: EndOfScans=4000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 11 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=4000 Executions=4000 Elapsedms=0 CPUms=0)
Node Id: 12 Mode: Row
I/O: EndOfScans=4000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=3999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.6574 AvgRowSize=9) (actual Rows=12000 RowsRead=12000 Executions=8000 Elapsedms=16 CPUms=16)
Node Id: 13 Mode: Row Table Cardinality: 4000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=8000 LogicalReads=16000 EndOfScans=8000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x10535863E724DB72
Degree Of Parallelism: 1
Memory Grant: Granted=1024kB MaxUsed=16kB Required=16kB Desired=24kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=2 WaitCount=8000
Wait Stats: MEMORY_ALLOCATION_EXT WaitTimeMs=1 WaitCount=4010
Compile: Time=17ms CPU=10ms Memory=328kB CachedPlanSize=48kB
CPU Time: 64 ms
Execution Time: 64 ms | 0.63s |
| 8K | 125 ms | At 8,000 lines SQL Server's Index Seek runs 16,000 times, two per sheet line, and the call takes 125 ms. Each doubling of the lines has about doubled the time: the hand-written condition grows with the lines, not with the pairs.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=1.38496 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1017],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=1.38496 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=125 CPUms=125)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1017
Defined Values: Expr1017 = Count(*)
-> Nested Loops (Inner Join) (est Rows=8000 IO=0 CPU=0.03344 SubtreeCost=1.38016 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=124 CPUms=124)
Node Id: 2 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F620927E6AB] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 3 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 Executions=8000 Elapsedms=114 CPUms=114)
Node Id: 4 Mode: Row Table Cardinality: 8000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=8000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Elapsedms=75 CPUms=75)
Node Id: 5 Mode: Row
Element: MergeInterval
I/O: EndOfScans=8000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Rebinds=8000 Elapsedms=70 CPUms=70)
Node Id: 6 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=8000
Memory Grant: Input=1024kB Output=1024kB Used=16kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 7 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Elapsedms=6 CPUms=6)
Node Id: 8 Mode: Row
I/O: EndOfScans=8000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 9 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=1 CPUms=1)
Node Id: 10 Mode: Row
I/O: EndOfScans=8000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 11 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=0 CPUms=0)
Node Id: 12 Mode: Row
I/O: EndOfScans=8000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 RowsRead=24000 Executions=16000 Elapsedms=33 CPUms=33)
Node Id: 13 Mode: Row Table Cardinality: 8000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=16000 LogicalReads=32000 EndOfScans=16000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xD9B0002F448588AE
Degree Of Parallelism: 1
Memory Grant: Granted=1024kB MaxUsed=16kB Required=16kB Desired=24kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=4 WaitCount=16000
Wait Stats: MEMORY_ALLOCATION_EXT WaitTimeMs=2 WaitCount=8011
Compile: Time=23ms CPU=16ms Memory=320kB CachedPlanSize=48kB
CPU Time: 125 ms
Execution Time: 125 ms | 0.76s |
The hand-written condition again, in a later call that went to 800,000 sheet lines:
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 192 ms | At 8,000 sheet lines SQL Server runs the main run's plan on one thread: a Merge Interval builds two ranges per sheet line, and the Index Seek on contracts_product_expiration runs 16,000 times. The call takes 192 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=1.38496 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1017],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=1.38496 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=192 CPUms=187)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1017
Defined Values: Expr1017 = Count(*)
-> Nested Loops (Inner Join) (est Rows=8000 IO=0 CPU=0.03344 SubtreeCost=1.38016 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=191 CPUms=186)
Node Id: 2 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F62C625880D] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=5 CPUms=5)
Node Id: 3 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 Executions=8000 Elapsedms=177 CPUms=172)
Node Id: 4 Mode: Row Table Cardinality: 8000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=8000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Elapsedms=117 CPUms=112)
Node Id: 5 Mode: Row
Element: MergeInterval
I/O: EndOfScans=8000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Rebinds=8000 Elapsedms=111 CPUms=106)
Node Id: 6 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=8000
Memory Grant: Input=1024kB Output=1024kB Used=16kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 7 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=16000 Executions=8000 Elapsedms=6 CPUms=6)
Node Id: 8 Mode: Row
I/O: EndOfScans=8000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 9 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=1 CPUms=1)
Node Id: 10 Mode: Row
I/O: EndOfScans=8000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 11 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=0 CPUms=0)
Node Id: 12 Mode: Row
I/O: EndOfScans=8000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 RowsRead=24000 Executions=16000 Elapsedms=53 CPUms=53)
Node Id: 13 Mode: Row Table Cardinality: 8000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=16000 LogicalReads=32000 EndOfScans=16000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xF8BD18934E587259
Degree Of Parallelism: 1
Memory Grant: Granted=1024kB MaxUsed=16kB Required=16kB Desired=24kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=6 WaitCount=16000
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=5 WaitCount=47
Wait Stats: MEMORY_ALLOCATION_EXT WaitTimeMs=4 WaitCount=8011
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=4 WaitCount=1
Compile: Time=28ms CPU=22ms Memory=320kB CachedPlanSize=48kB
CPU Time: 187 ms
Execution Time: 192 ms | 1.05s |
| 80K | 1s | At 80,000 lines SQL Server keeps two seeks per sheet line, 160,000 in all, and splits them across 4 threads, so the call takes 1,018 ms of Execution Time while its CPU Time adds up to 3,883 ms.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=13.624 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1004],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0000017 SubtreeCost=13.624 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=1017 CPUms=0)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1004
Defined Values: globalagg1004 = SUM([partialagg1003])
-> Parallelism (Gather Streams) (est Rows=2 IO=0 CPU=0.0285021 SubtreeCost=13.624 AvgRowSize=15) (actual Rows=4 Executions=1 Elapsedms=1017 CPUms=0)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: partialagg1003
-> Stream Aggregate (Aggregate) (est Rows=2 IO=0 CPU=0.0240005 SubtreeCost=13.5955 AvgRowSize=15) (actual Rows=4 Executions=4 Elapsedms=1016 CPUms=3879 Threads=4)
Node Id: 4 Mode: Row
I/O: EndOfScans=4
Output List: partialagg1003
Defined Values: partialagg1003 = Count(*)
-> Nested Loops (Inner Join) (est Rows=80000 IO=0 CPU=0.1672 SubtreeCost=13.5715 AvgRowSize=9) (actual Rows=240000 Executions=4 Elapsedms=1009 CPUms=3852 Threads=4)
Node Id: 5 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=4
-> Clustered Index Scan [PK__contract__F5AE5F625E053921] on contract_sheet cs (est Rows=80000 RowsRead=80000 IO=0.237199 CPU=0.0440785 SubtreeCost=0.281278 AvgRowSize=12) (actual Rows=80000 RowsRead=80000 Executions=4 Elapsedms=31 CPUms=120 Threads=4)
Node Id: 6 Mode: Row Table Cardinality: 80000 Storage: RowStore
I/O: Scans=5 LogicalReads=952 EndOfScans=4
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=79999 IO=0.003125 CPU=0.0001581 SubtreeCost=13.123 AvgRowSize=9) (actual Rows=240000 Executions=80000 Elapsedms=947 CPUms=3597 Threads=4)
Node Id: 7 Mode: Row Table Cardinality: 80000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=80000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=160000 Executions=80000 Elapsedms=594 CPUms=2274 Threads=4)
Node Id: 8 Mode: Row
Element: MergeInterval
I/O: EndOfScans=80000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=160000 Executions=80000 Rebinds=80000 Elapsedms=564 CPUms=2153 Threads=4)
Node Id: 9 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=80000
Memory Grant: Input=928kB Output=928kB Used=64kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 10 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=160000 Executions=80000 Elapsedms=29 CPUms=106 Threads=4)
Node Id: 11 Mode: Row
I/O: EndOfScans=80000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 12 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=80000 Executions=80000 Elapsedms=4 CPUms=13 Threads=4)
Node Id: 13 Mode: Row
I/O: EndOfScans=80000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 14 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=80000 Executions=80000 Elapsedms=3 CPUms=10 Threads=4)
Node Id: 15 Mode: Row
I/O: EndOfScans=80000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=79999 IO=0.003125 CPU=0.0001581 SubtreeCost=13.123 AvgRowSize=9) (actual Rows=240000 RowsRead=240000 Executions=160000 Elapsedms=349 CPUms=1207 Threads=4)
Node Id: 16 Mode: Row Table Cardinality: 80000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=160000 LogicalReads=380000 EndOfScans=160000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xAE20DC6ED791FB5A
Degree Of Parallelism: 4 Used Threads: 4
Memory Grant: Granted=1024kB MaxUsed=136kB Required=136kB Desired=168kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: CXSYNC_PORT WaitTimeMs=1040 WaitCount=5
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=169 WaitCount=945
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=142 WaitCount=20
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=124 WaitCount=160009
Wait Stats: MEMORY_ALLOCATION_EXT WaitTimeMs=83 WaitCount=80046
Compile: Time=351ms CPU=212ms Memory=344kB CachedPlanSize=56kB
CPU Time: 3883 ms
Execution Time: 1018 ms | 2.81s |
| 800K | 10.7s | At 800,000 lines the plan is unchanged: 1,600,000 seeks on 4 threads find 2,400,000 matches, the three contracts per sheet line that never expire, and the call takes 10,745 ms, with 36,490 ms of CPU Time. The seeks grow with the lines, not with the pairs.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=135.856 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1004],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0000017 SubtreeCost=135.856 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=10745 CPUms=0)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1004
Defined Values: globalagg1004 = SUM([partialagg1003])
-> Parallelism (Gather Streams) (est Rows=2 IO=0 CPU=0.0285021 SubtreeCost=135.856 AvgRowSize=15) (actual Rows=4 Executions=1 Elapsedms=10745 CPUms=0)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: partialagg1003
-> Stream Aggregate (Aggregate) (est Rows=2 IO=0 CPU=0.240001 SubtreeCost=135.827 AvgRowSize=15) (actual Rows=4 Executions=4 Elapsedms=10741 CPUms=36487 Threads=4)
Node Id: 4 Mode: Row
I/O: EndOfScans=4
Output List: partialagg1003
Defined Values: partialagg1003 = Count(*)
-> Nested Loops (Inner Join) (est Rows=800000 IO=0 CPU=1.672 SubtreeCost=135.587 AvgRowSize=9) (actual Rows=2400000 Executions=4 Elapsedms=10680 CPUms=36246 Threads=4)
Node Id: 5 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=4
-> Clustered Index Scan [PK__contract__F5AE5F6271AC8AC9] on contract_sheet cs (est Rows=800000 RowsRead=800000 IO=2.34535 CPU=0.440078 SubtreeCost=2.78543 AvgRowSize=12) (actual Rows=800000 RowsRead=800000 Executions=4 Elapsedms=293 CPUms=1111 Threads=4)
Node Id: 6 Mode: Row Table Cardinality: 800000 Storage: RowStore
I/O: Scans=5 LogicalReads=3257 EndOfScans=4
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=799999 Rewinds=0.00144649 IO=0.003125 CPU=0.0001581 SubtreeCost=131.13 AvgRowSize=9) (actual Rows=2400000 Executions=800000 Elapsedms=10069 CPUms=33905 Threads=4)
Node Id: 7 Mode: Row Table Cardinality: 800000
Outer References: Expr1011, Expr1012, Expr1013
I/O: EndOfScans=800000
-> Merge Interval (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=1600000 Executions=800000 Elapsedms=5803 CPUms=20664 Threads=4)
Node Id: 8 Mode: Row
Element: MergeInterval
I/O: EndOfScans=800000
Output List: Expr1011, Expr1012, Expr1013
-> Sort (TopN Sort) (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=1600000 Executions=800000 Rebinds=800000 Elapsedms=5512 CPUms=19540 Threads=4)
Node Id: 9 Mode: Row
Top: 2
Order By: Expr1014 DESC, Expr1015, Expr1011, Expr1016 DESC
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=800000
Memory Grant: Input=928kB Output=928kB Used=64kB
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
-> Compute Scalar (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 10 Mode: Row
Output List: Expr1011, Expr1012, Expr1013, Expr1014, Expr1015, Expr1016
Defined Values: Expr1014 = ((4)&[Expr1013]) = (4) AND NULL = [Expr1011]; Expr1015 = (4)&[Expr1013]; Expr1016 = (16)&[Expr1013]
-> Concatenation (est Rows=2 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=1600000 Executions=800000 Elapsedms=254 CPUms=976 Threads=4)
Node Id: 11 Mode: Row
I/O: EndOfScans=800000
Output List: Expr1011, Expr1012, Expr1013
Defined Values: Expr1011, Expr1006, Expr1009; Expr1012, Expr1007, Expr1010; Expr1013, Expr1005, Expr1008
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 12 Mode: Row
Output List: Expr1006, Expr1007, Expr1005
Defined Values: Expr1006 = NULL; Expr1007 = NULL; Expr1005 = (60)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=800000 Executions=800000 Elapsedms=35 CPUms=130 Threads=4)
Node Id: 13 Mode: Row
I/O: EndOfScans=800000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17)
Node Id: 14 Mode: Row
Output List: Expr1009, Expr1010, Expr1008
Defined Values: Expr1009 = [contract_sheet].[max_year] as [cs].[max_year]; Expr1010 = NULL; Expr1008 = (6)
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=800000 Executions=800000 Elapsedms=30 CPUms=115 Threads=4)
Node Id: 15 Mode: Row
I/O: EndOfScans=800000
-> Index Seek [contracts_product_expiration] on contracts c (est Rows=1 RowsRead=1 Rebinds=799999 Rewinds=0.00144649 IO=0.003125 CPU=0.0001581 SubtreeCost=131.13 AvgRowSize=9) (actual Rows=2400000 RowsRead=2400000 Executions=1600000 Elapsedms=3964 CPUms=12181 Threads=4)
Node Id: 16 Mode: Row Table Cardinality: 800000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
I/O: Scans=1600000 LogicalReads=5400000 EndOfScans=1600000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xD3C852912294111D
Degree Of Parallelism: 4 Used Threads: 4
Memory Grant: Granted=1024kB MaxUsed=136kB Required=136kB Desired=168kB Requested=1024kB GrantWaitTime=0ms Feedback: No: First Execution
Statistics Used: [_WA_Sys_00000003_29971E47] on contract_sheet (sampled 36.181%)
Statistics Used: [_WA_Sys_00000003_27AED5D5] on contracts (sampled 34.642%)
Statistics Used: [PK__contract__3213E83F01A6CC29] on contracts (sampled 34.642%)
Statistics Used: [contracts_product_expiration] on contracts (sampled 36.717%)
Statistics Used: [_WA_Sys_00000002_29971E47] on contract_sheet (sampled 36.181%)
Wait Stats: CXSYNC_PORT WaitTimeMs=13297 WaitCount=5
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=3968 WaitCount=9007
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=3238 WaitCount=531
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=1217 WaitCount=1600009
Wait Stats: MEMORY_ALLOCATION_EXT WaitTimeMs=878 WaitCount=877282
Wait Stats: PAGELATCH_SH WaitTimeMs=10 WaitCount=9
Wait Stats: SLEEP_MEMORYPOOL_ALLOCATEPAGES WaitTimeMs=4 WaitCount=1
Compile: Time=888ms CPU=23ms Memory=480kB CachedPlanSize=56kB
CPU Time: 36490 ms
Execution Time: 10745 ms | 22.87s |
At 8,000 lines on SQL Server that's 26 seconds against 125 ms. About 210 times, but the two calls ran in different runs, and on this serverless database the same call has moved by up to about twice between runs, so read it as a few hundred times.
Without inlining we're talking ~21 seconds!
--- SQL Server, dateOr99 WITH INLINE = OFF, 8,000 sheet lines, 26 seconds ---
Hash Match (Inner Join)
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: ... AND [...].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
-> Clustered Index Scan on contract_sheet cs
-> Index Scan on contracts c
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Remove the UDF and write the condition out by hand and it's 209x faster!
--- SQL Server, IS NULL OR > written by hand, 8,000 sheet lines, 125 ms ---
Nested Loops (Inner Join)
-> Clustered Index Scan on contract_sheet cs
-> Nested Loops (Inner Join)
-> Merge Interval
-> Index Seek [contracts_product_expiration] on contracts c (... Executions=16000 ...)
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration_date [Expr1011]; End LT c.expiration_date [Expr1012]
The UDF version hashes the sheet on product and checks the date in the hash join's residual, which runs for every contract that matches a line's product, calling dateOr99 each time. The last line is why it ran on one thread; in Microsoft's words, "SQL Server doesn't allow intra-query parallelism in queries that invoke UDFs."
The hand-written version is a nested loop. Merge Interval turns IS NULL OR > into two ranges per sheet line, one for the NULLs and one past max_year, and each range is one seek that reads only the contracts inside it, which is the Executions=16000.
That's sargability, the word from the story. A condition is sargable when the engine can search an index with it, because the column stands bare on one side of the comparison; Microsoft calls it "a Search ARGumentable predicate that can use an index to speed up the execution of the query". c.expiration_date > cs.max_year is sargable. dateOr99(c.expiration_date) > cs.max_year isn't: the index holds expiration dates, not what dateOr99 makes of them.
My memory says the slow plans were nested loops. On today's engine the slow plan is the hash join and the fix is the nested loop, so whatever the 2017 plans looked like, what costs here is how many pairs the date check runs on: 8 million at 8,000 lines, against two seeks per line.
That cost outruns the listings. Each doubling of the sheet made the UDF version take four times as long and the hand-written one twice as long, so the gap between them doubles too.
In the later call the hand-written condition took 1.0 seconds at 80,000 lines, still two seeks per line. At 800,000 lines it took 11 seconds. From that size on, SQL Server split the seeks across four threads, so the first tenfold step took about five times as long and the second about ten.
Would SQL Server 2019 have solved all of our problems?
Scalar UDF inlining is SQL Server's own fix for slow scalar UDFs: the engine replaces the call with the function's body, as an expression the optimizer can see. It shipped with SQL Server 2019 and reached Azure SQL Database in September 2021. It needs compatibility level 150 or higher and a function that passes a long list of requirements, which Microsoft kept extending in cumulative updates. dateOr99, a single RETURN, passes (the list and the dates are in the inlining appendix).
Inlined, the UDF query took 815 ms on SQL Server at 8,000 lines (its card is in the SQL Server appendix), that's 32x faster than the regular UDF but still 8x slower than writing it out by hand.
Notice that it still takes four times as long each time the contract-lines are doubled? Here's the relevant part of the plan:
--- SQL Server, dateOr99 inlined, 8,000 sheet lines, 815 ms ---
Hash Match (Inner Join)
Probe Residual: ... AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
-> Hash Match (Aggregate) (... actual Rows=7984 ...)
-> Compute Scalar
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Clustered Index Scan on contract_sheet cs
Now let's see what happens when we try to index it!
ALTER TABLE contracts ADD expiration99 AS ISNULL(expiration_date, DATEFROMPARTS(9999, 1, 1)) PERSISTED;
CREATE INDEX contracts_product_expiration99 ON contracts (product, expiration99);
The query still calls dateOr99. On SQL Server it took 29 ms at 8,000 lines, four times faster than the hand-written condition, and its time doubles with the lines:
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;
ALTER TABLE contracts ADD expiration99 AS ISNULL(expiration_date, DATEFROMPARTS(9999, 1, 1)) PERSISTED;
CREATE INDEX contracts_product_expiration99 ON contracts (product, expiration99);
UPDATE STATISTICS contracts;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 3 ms | At 1,000 sheet lines the query asks SQL Server for dateOr99(c.expiration_date) > cs.max_year, and the plan answers it with an Index Seek on contracts_product_expiration99, the index on the computed column expiration99: one seek per sheet line, 3 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.175835 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1009],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.175835 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1009
Defined Values: Expr1009 = Count(*)
-> Nested Loops (Inner Join) (est Rows=1000 IO=0 CPU=0.00418 SubtreeCost=0.175134 AvgRowSize=9) (actual Rows=3000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 3 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F6264044646] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.16435 AvgRowSize=9) (actual Rows=3000 Executions=1000 Elapsedms=2 CPUms=2)
Node Id: 5 Mode: Row Table Cardinality: 1000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=1000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=1000 Executions=1000 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row
I/O: EndOfScans=1000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=1000 Executions=1000 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row
I/O: EndOfScans=1000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.16435 AvgRowSize=9) (actual Rows=3000 RowsRead=3000 Executions=1000 Elapsedms=1 CPUms=1)
Node Id: 8 Mode: Row Table Cardinality: 1000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=1000 LogicalReads=2000 EndOfScans=1000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x930B6F92F78B4377
Degree Of Parallelism: 1
Memory Grant: Granted=0kB MaxUsed=0kB
Compile: Time=14ms CPU=8ms Memory=456kB CachedPlanSize=40kB
extra: 1
CPU Time: 3 ms
Execution Time: 3 ms | 0.63s |
| 2K | 7 ms | At 2,000 lines SQL Server runs the same Nested Loops with one seek per sheet line, now 2,000 of them, and the time is 7 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.349128 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1009],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.349128 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=7 CPUms=7)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1009
Defined Values: Expr1009 = Count(*)
-> Nested Loops (Inner Join) (est Rows=2000 IO=0 CPU=0.00836 SubtreeCost=0.347727 AvgRowSize=9) (actual Rows=6000 Executions=1 Elapsedms=7 CPUms=7)
Node Id: 3 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F62762E9F73] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=1999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.3287 AvgRowSize=9) (actual Rows=6000 Executions=2000 Elapsedms=5 CPUms=5)
Node Id: 5 Mode: Row Table Cardinality: 2000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=2000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=2000 Executions=2000 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row
I/O: EndOfScans=2000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=2000 Executions=2000 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row
I/O: EndOfScans=2000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=1999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.3287 AvgRowSize=9) (actual Rows=6000 RowsRead=6000 Executions=2000 Elapsedms=3 CPUms=3)
Node Id: 8 Mode: Row Table Cardinality: 2000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=2000 LogicalReads=4000 EndOfScans=2000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xDFB9FE9062AA9E83
Degree Of Parallelism: 1
Memory Grant: Granted=0kB MaxUsed=0kB
Compile: Time=14ms CPU=8ms Memory=448kB CachedPlanSize=40kB
extra: 1
CPU Time: 7 ms
Execution Time: 7 ms | 0.63s |
| 4K | 14 ms | At 4,000 lines SQL Server computes each line's seek range from its cs.max_year in a Compute Scalar, runs the seek 4,000 times, and doubles its time to 14 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.695714 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1009],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=0.695714 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=14 CPUms=14)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1009
Defined Values: Expr1009 = Count(*)
-> Nested Loops (Inner Join) (est Rows=4000 IO=0 CPU=0.01672 SubtreeCost=0.692913 AvgRowSize=9) (actual Rows=12000 Executions=1 Elapsedms=14 CPUms=14)
Node Id: 3 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F6200E1E4EB] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 4 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=3999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.6574 AvgRowSize=9) (actual Rows=12000 Executions=4000 Elapsedms=11 CPUms=11)
Node Id: 5 Mode: Row Table Cardinality: 4000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=4000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=4000 Executions=4000 Elapsedms=1 CPUms=1)
Node Id: 6 Mode: Row
I/O: EndOfScans=4000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=4000 Executions=4000 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row
I/O: EndOfScans=4000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=3999 IO=0.003125 CPU=0.0001581 SubtreeCost=0.6574 AvgRowSize=9) (actual Rows=12000 RowsRead=12000 Executions=4000 Elapsedms=7 CPUms=7)
Node Id: 8 Mode: Row Table Cardinality: 4000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=4000 LogicalReads=8000 EndOfScans=4000
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x94A4F35628AF2470
Degree Of Parallelism: 1
Memory Grant: Granted=0kB MaxUsed=0kB
Compile: Time=18ms CPU=11ms Memory=416kB CachedPlanSize=40kB
extra: 1
CPU Time: 14 ms
Execution Time: 14 ms | 0.75s |
| 8K | 29 ms | At 8,000 lines SQL Server's Index Seek runs 8,000 times, once per sheet line, and the call takes 29 ms. The query text never changed: it still calls dateOr99, and the plan seeks the computed column instead.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=1.38576 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1009],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=1.38576 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=29 CPUms=29)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1009
Defined Values: Expr1009 = Count(*)
-> Nested Loops (Inner Join) (est Rows=8000 IO=0 CPU=0.03344 SubtreeCost=1.38016 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=28 CPUms=28)
Node Id: 3 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F62E7DEC827] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 4 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 Executions=8000 Elapsedms=23 CPUms=23)
Node Id: 5 Mode: Row Table Cardinality: 8000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=8000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=8000 Executions=8000 Elapsedms=3 CPUms=3)
Node Id: 6 Mode: Row
I/O: EndOfScans=8000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row
I/O: EndOfScans=8000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 RowsRead=24000 Executions=8000 Elapsedms=15 CPUms=15)
Node Id: 8 Mode: Row Table Cardinality: 8000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=8000 LogicalReads=16000 EndOfScans=8000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x2B4B2A039B04D2E7
Degree Of Parallelism: 1
Memory Grant: Granted=0kB MaxUsed=0kB
Compile: Time=22ms CPU=17ms Memory=416kB CachedPlanSize=40kB
extra: 1
CPU Time: 29 ms
Execution Time: 29 ms | 0.74s |
Now let's try to 10x the precomputed column rows and see what happens.
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;
ALTER TABLE contracts ADD expiration99 AS ISNULL(expiration_date, DATEFROMPARTS(9999, 1, 1)) PERSISTED;
CREATE INDEX contracts_product_expiration99 ON contracts (product, expiration99);
UPDATE STATISTICS contracts;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 30 ms | At 8,000 sheet lines SQL Server runs the main run's plan on one thread: the Index Seek on contracts_product_expiration99 runs 8,000 times, once per sheet line, and the call takes 30 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=1.38576 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1009],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=1.38576 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=30 CPUms=30)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1009
Defined Values: Expr1009 = Count(*)
-> Nested Loops (Inner Join) (est Rows=8000 IO=0 CPU=0.03344 SubtreeCost=1.38016 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=29 CPUms=29)
Node Id: 3 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=1
-> Clustered Index Scan [PK__contract__F5AE5F625E552214] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 4 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 Executions=8000 Elapsedms=24 CPUms=24)
Node Id: 5 Mode: Row Table Cardinality: 8000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=8000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=8000 Executions=8000 Elapsedms=3 CPUms=3)
Node Id: 6 Mode: Row
I/O: EndOfScans=8000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=8000 Executions=8000 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row
I/O: EndOfScans=8000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=7999 IO=0.003125 CPU=0.0001581 SubtreeCost=1.31167 AvgRowSize=9) (actual Rows=24000 RowsRead=24000 Executions=8000 Elapsedms=17 CPUms=17)
Node Id: 8 Mode: Row Table Cardinality: 8000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=8000 LogicalReads=16000 EndOfScans=8000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x5812142D3F603867
Degree Of Parallelism: 1
Memory Grant: Granted=0kB MaxUsed=0kB
Compile: Time=22ms CPU=16ms Memory=416kB CachedPlanSize=40kB
extra: 1
CPU Time: 30 ms
Execution Time: 30 ms | 0.82s |
| 80K | 150 ms | At 80,000 lines SQL Server still seeks the computed column's index once per sheet line, 80,000 times, now on 4 threads: 150 ms of Execution Time and 599 ms of CPU Time.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=13.628 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0000017 SubtreeCost=13.628 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=150 CPUms=0)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1005
Defined Values: globalagg1005 = SUM([partialagg1004])
-> Parallelism (Gather Streams) (est Rows=2 IO=0 CPU=0.0285021 SubtreeCost=13.628 AvgRowSize=15) (actual Rows=4 Executions=1 Elapsedms=150 CPUms=0)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: partialagg1004
-> Stream Aggregate (Aggregate) (est Rows=2 IO=0 CPU=0.0240005 SubtreeCost=13.5995 AvgRowSize=15) (actual Rows=4 Executions=4 Elapsedms=150 CPUms=597 Threads=4)
Node Id: 4 Mode: Row
I/O: EndOfScans=4
Output List: partialagg1004
Defined Values: partialagg1004 = Count(*)
-> Nested Loops (Inner Join) (est Rows=80000 IO=0 CPU=0.1672 SubtreeCost=13.5715 AvgRowSize=9) (actual Rows=240000 Executions=4 Elapsedms=145 CPUms=577 Threads=4)
Node Id: 6 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=4
-> Clustered Index Scan [PK__contract__F5AE5F62C9EFE249] on contract_sheet cs (est Rows=80000 RowsRead=80000 IO=0.237199 CPU=0.0440785 SubtreeCost=0.281278 AvgRowSize=12) (actual Rows=80000 RowsRead=80000 Executions=4 Elapsedms=13 CPUms=50 Threads=4)
Node Id: 7 Mode: Row Table Cardinality: 80000 Storage: RowStore
I/O: Scans=5 LogicalReads=952 EndOfScans=4
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=79999 IO=0.003125 CPU=0.0001581 SubtreeCost=13.123 AvgRowSize=9) (actual Rows=240000 Executions=80000 Elapsedms=122 CPUms=487 Threads=4)
Node Id: 8 Mode: Row Table Cardinality: 80000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=80000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=80000 Executions=80000 Elapsedms=13 CPUms=50 Threads=4)
Node Id: 9 Mode: Row
I/O: EndOfScans=80000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=80000 Executions=80000 Elapsedms=1 CPUms=4 Threads=4)
Node Id: 10 Mode: Row
I/O: EndOfScans=80000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=79999 IO=0.003125 CPU=0.0001581 SubtreeCost=13.123 AvgRowSize=9) (actual Rows=240000 RowsRead=240000 Executions=80000 Elapsedms=96 CPUms=382 Threads=4)
Node Id: 11 Mode: Row Table Cardinality: 80000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=80000 LogicalReads=190000 EndOfScans=80000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xE4474F8FFCA0D728
Degree Of Parallelism: 4 Used Threads: 4
Memory Grant: Granted=72kB MaxUsed=72kB Required=72kB Desired=72kB Requested=72kB GrantWaitTime=0ms
Wait Stats: CXSYNC_PORT WaitTimeMs=153 WaitCount=5
Compile: Time=211ms CPU=121ms Memory=440kB CachedPlanSize=40kB
extra: 1
CPU Time: 599 ms
Execution Time: 150 ms | 2.11s |
| 800K | 2.3s | At 800,000 lines the Index Seek runs 800,000 times on 4 threads and returns 2,400,000 matches, three per sheet line. The call takes 2,328 ms, with 5,384 ms of CPU Time.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=135.896 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0000017 SubtreeCost=135.896 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=2328 CPUms=0)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1005
Defined Values: globalagg1005 = SUM([partialagg1004])
-> Parallelism (Gather Streams) (est Rows=2 IO=0 CPU=0.0285021 SubtreeCost=135.896 AvgRowSize=15) (actual Rows=4 Executions=1 Elapsedms=2328 CPUms=0)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: partialagg1004
-> Stream Aggregate (Aggregate) (est Rows=2 IO=0 CPU=0.240001 SubtreeCost=135.867 AvgRowSize=15) (actual Rows=4 Executions=4 Elapsedms=2327 CPUms=5382 Threads=4)
Node Id: 4 Mode: Row
I/O: EndOfScans=4
Output List: partialagg1004
Defined Values: partialagg1004 = Count(*)
-> Nested Loops (Inner Join) (est Rows=800000 IO=0 CPU=1.672 SubtreeCost=135.587 AvgRowSize=9) (actual Rows=2400000 Executions=4 Elapsedms=2288 CPUms=5220 Threads=4)
Node Id: 6 Mode: Row
Outer References: cs.product, cs.max_year
I/O: EndOfScans=4
-> Clustered Index Scan [PK__contract__F5AE5F62C039A501] on contract_sheet cs (est Rows=800000 RowsRead=800000 IO=2.34535 CPU=0.440078 SubtreeCost=2.78543 AvgRowSize=12) (actual Rows=800000 RowsRead=800000 Executions=4 Elapsedms=105 CPUms=390 Threads=4)
Node Id: 7 Mode: Row Table Cardinality: 800000 Storage: RowStore
I/O: Scans=5 LogicalReads=3272 EndOfScans=4
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Nested Loops (Inner Join) (est Rows=1 RowsRead=1 Rebinds=799999 Rewinds=0.0012714 IO=0.003125 CPU=0.0001581 SubtreeCost=131.13 AvgRowSize=9) (actual Rows=2400000 Executions=800000 Elapsedms=2070 CPUms=4466 Threads=4)
Node Id: 8 Mode: Row Table Cardinality: 800000
Outer References: Expr1007, Expr1008, Expr1006
I/O: EndOfScans=800000
-> Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=17) (actual Rows=800000 Executions=800000 Elapsedms=130 CPUms=462 Threads=4)
Node Id: 9 Mode: Row
I/O: EndOfScans=800000
Output List: Expr1007, Expr1008, Expr1006
Defined Values: Expr1007, Expr1008, Expr1006 = GetRangeThroughConvert([contract_sheet].[max_year] as [cs].[max_year],NULL,(6))
-> Constant Scan (est Rows=1 IO=0 CPU=0 SubtreeCost=0 AvgRowSize=0) (actual Rows=800000 Executions=800000 Elapsedms=28 CPUms=76 Threads=4)
Node Id: 10 Mode: Row
I/O: EndOfScans=800000
-> Index Seek [contracts_product_expiration99] on contracts c (est Rows=1 RowsRead=1 Rebinds=799999 Rewinds=0.0012714 IO=0.003125 CPU=0.0001581 SubtreeCost=131.13 AvgRowSize=9) (actual Rows=2400000 RowsRead=2400000 Executions=800000 Elapsedms=1791 CPUms=3549 Threads=4)
Node Id: 11 Mode: Row Table Cardinality: 800000 Storage: RowStore Ordered: FORWARD
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
I/O: Scans=800000 LogicalReads=2700000 EndOfScans=800000
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0xD3D3FF6E7F6B5244
Degree Of Parallelism: 4 Used Threads: 4
Memory Grant: Granted=72kB MaxUsed=72kB Required=72kB Desired=72kB Requested=72kB GrantWaitTime=0ms
Statistics Used: [_WA_Sys_00000003_42ECDBF6] on contract_sheet (sampled 36.086%)
Statistics Used: [_WA_Sys_00000003_41049384] on contracts (sampled 12.405%)
Statistics Used: [contracts_product_expiration99] on contracts (sampled 11.807%)
Statistics Used: [_WA_Sys_00000004_41049384] on contracts (sampled 10.316%)
Statistics Used: [_WA_Sys_00000002_42ECDBF6] on contract_sheet (sampled 36.086%)
Statistics Used: [contracts_product_expiration] on contracts (sampled 11.807%)
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=3666 WaitCount=1331
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=3573 WaitCount=415
Wait Stats: CXSYNC_PORT WaitTimeMs=2597 WaitCount=5
Compile: Time=590ms CPU=20ms Memory=632kB CachedPlanSize=48kB
extra: 1
CPU Time: 5384 ms
Execution Time: 2328 ms | 23.79s |
Surprise! The UDF now beats direct inlining by around 5x performance.
Expand the > SQL section in the above card and you'll see we're using the original query.
Here's the relevant part of the plan:
--- SQL Server, dateOr99 inlined, with the indexed computed column, 8,000 sheet lines, 29 ms ---
Nested Loops (Inner Join)
-> Clustered Index Scan on contract_sheet cs
-> Nested Loops (Inner Join)
-> Index Seek [contracts_product_expiration99] on contracts c (... Executions=8000 ...)
Seek Predicates: Prefix EQ c.product = [contract_sheet].[product] as [cs].[product]; Start GT c.expiration99 [Expr1007]; End LT c.expiration99 [Expr1008]
Inlined, dateOr99 becomes an isnull(...) computed once per contract, and SQL Server groups the contracts by product and date before the join. The comparison with max_year still sits in the hash join's residual, checked for every sheet line against about a thousand values on its product. Inlining took out the calls but left the pairs.
With the computed column, SQL Server matches the inlined expression to expiration99 and seeks its index once per line. Microsoft's docs mention that kind of matching only in passing, and I found nothing on an inlined UDF, so the plan is my evidence.
So inlining alone would have bought us time on the 10x magnitude but performance degradation is still quadratic so if you really want the UDF to scale you need to index it.
Here's SQL Server out to 80,000 lines, from later calls. Inlined, the UDF took 64 seconds at 80,000 lines, on one thread with the same hash join. That's 101 times its 630 ms at 8,000 lines in the same call (its card is in the SQL Server appendix). At 800,000 lines ExoBench stopped it after 106 seconds, unfinished. The hand-written condition and the computed column took about five times as long at 80,000 lines as at 8,000, on 4 threads:
The same fix on PostgreSQL 18
Okay, we're all sure the cure for a slow is to write it out by hand... right!? How about on PostgreSQL? Let's run the same SQL and see what happens.
Here's PG18 with the hand-written condition, from the main run:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)CREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 7 ms | At 1,000 sheet lines PG18 hashes the contracts on product and runs the whole OR as a Join Filter on every sheet line and contract that share a product. It removes 122,000 of those pairs and keeps 3,000, in 7.017 ms.QUERY PLAN
Aggregate (cost=1874.92..1874.93 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=12
-> Hash Join (cost=28.50..1765.75 rows=43667 width=0) (actual rows=3000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 122000
Buffers: shared hit=12
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
Buffers: shared hit=6
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
Planning:
Buffers: shared hit=108
Planning Time: 0.266 ms
Execution Time: 7.017 ms | 0.81s |
| 2K | 27.2 ms | At 2,000 lines PG18 runs the same Hash Join with the OR in the Join Filter, now removing 494,000 pairs, and the call takes 27.206 ms, close to four times as long as at half the size.QUERY PLAN
Aggregate (cost=7393.67..7393.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=22
-> Hash Join (cost=56.00..6967.00 rows=170667 width=0) (actual rows=6000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 494000
Buffers: shared hit=22
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
Buffers: shared hit=11
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
Planning:
Buffers: shared hit=108
Planning Time: 0.273 ms
Execution Time: 27.206 ms | 0.85s |
| 4K | 107.2 ms | At 4,000 lines PG18's Join Filter removes 1,988,000 pairs and the call takes 107.233 ms: twice the sheet lines, four times the pairs, and about four times the time.QUERY PLAN
Aggregate (cost=29370.67..29370.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=44
-> Hash Join (cost=112.00..27684.00 rows=674667 width=0) (actual rows=12000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 1988000
Buffers: shared hit=44
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
Buffers: shared hit=22
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
Planning:
Buffers: shared hit=108
Planning Time: 0.270 ms
Execution Time: 107.233 ms | 0.94s |
| 8K | 428.3 ms | At 8,000 lines PG18's Join Filter removes 7,976,000 pairs and the call takes 428.283 ms. The plan reads contracts with a Seq Scan and tests the hand-written condition on every pair.QUERY PLAN
Aggregate (cost=117074.67..117074.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=88
-> Hash Join (cost=224.00..110368.00 rows=2682667 width=0) (actual rows=24000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 7976000
Buffers: shared hit=88
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
Buffers: shared hit=44
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
Planning:
Buffers: shared hit=108
Planning Time: 0.285 ms
Execution Time: 428.283 ms | 1.31s |
Surprise! We've got quadratic degradation getting 428ms at 8,000 contract-lines, and four times as long each time the lines double: the curve the fix was supposed to get rid of, from a query with no UDF at all. Not a fun baseline!
--- PG18, dateOr99 as a LANGUAGE sql function (inlined), 8,000 sheet lines, 409 ms ---
Aggregate
-> Hash Join (... actual rows=24000.00 ...)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 7976000
PG18 ran three versions of the join on one plan. At the same size on PG18, dateOr99 as PL/pgSQL took 1.9 seconds. Here's dateOr99 as a one-line SQL function against the hand-written condition, trimmed:
--- PG18, IS NULL OR > written by hand, 8,000 sheet lines, 428 ms ---
Aggregate
-> Hash Join (... actual rows=24000.00 ...)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 7976000
Same hash join on product, same rows thrown away, one plan filtering on the inlined COALESCE and the other on the OR, and the rows kept plus the rows removed add up to all 8 million pairs. The PL/pgSQL plan is the same again with a call to dateor99() in the filter (both cards are in the PostgreSQL appendix).
So on PG18, against the inlined SQL function, the fix from the story does nothing: the two stayed within 5% of each other at every size. Against PL/pgSQL it saves a call on every pair and runs 4.5 times faster. Either way it keeps the pairs, and it doesn't scale.
At ten times the lines it's a hundred times the pairs: 800 million at 80,000 sheet lines, where PG18 took 14 seconds. The time grew 33 times, not a hundred, because at 80,000 lines PG18 ran the hash join in three processes, the query's own process and 2 parallel workers, and the three split the pairs between them. Three processes for 14 seconds is 42 seconds of work, about a hundred times the 425 ms the same call took at 8,000 lines:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)CREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 425.2 ms | At 8,000 sheet lines PG18 runs the same Hash Join as in the main run, in one process: its Join Filter removes 7,976,000 pairs and the call takes 425.220 ms.QUERY PLAN
Aggregate (cost=117074.67..117074.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=88
-> Hash Join (cost=224.00..110368.00 rows=2682667 width=0) (actual rows=24000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 7976000
Buffers: shared hit=88
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
Buffers: shared hit=44
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
Planning:
Buffers: shared hit=108
Planning Time: 0.259 ms
Execution Time: 425.220 ms | 1.31s |
| 80K | 14s | At 80,000 lines PG18 runs the join in parallel, Workers Launched: 2, so with the leader the Hash Join runs 3 times (loops=3), each hashing all 80,000 sheet lines and reading a share of the contracts. Its Join Filter removes 266,586,667 pairs per loop, and the call takes 13,998.132 ms.QUERY PLAN
Finalize Aggregate (cost=4872450.01..4872450.02 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=1342 read=220
-> Gather (cost=4872449.80..4872450.01 rows=2 width=8) (actual rows=3.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=1342 read=220
-> Partial Aggregate (cost=4871449.80..4871449.81 rows=1 width=8) (actual rows=1.00 loops=3)
Buffers: shared hit=1342 read=220
-> Hash Join (cost=2233.29..4593421.64 rows=111211262 width=0) (actual rows=80000.00 loops=3)
Hash Cond: (c.product = cs.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 266586667
Buffers: shared hit=1342 read=220
-> Parallel Index Only Scan using contracts_product_expiration on contracts c (cost=0.29..1617.63 rows=33333 width=7) (actual rows=26666.67 loops=3)
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=3 read=220
-> Hash (cost=1233.00..1233.00 rows=80000 width=7) (actual rows=80000.00 loops=3)
Buckets: 131072 Batches: 1 Memory Usage: 4149kB
Buffers: shared hit=1339
-> Seq Scan on contract_sheet cs (cost=0.00..1233.00 rows=80000 width=7) (actual rows=80000.00 loops=3)
Buffers: shared hit=1339
Planning:
Buffers: shared hit=108
Planning Time: 0.291 ms
Execution Time: 13998.132 ms | 15.26s |
At 800,000 lines, 80 billion pairs, PG18's plan was again a parallel hash join on product with the OR in its Join Filter. I asked only for the plan: at the 80,000-line rate, running it would take over 20 minutes.
Two rules in PostgreSQL's planner explain these plans (the source appendix has the code). It inlines a LANGUAGE sql function whose body is one plain expression, even at the default VOLATILE, its label for a function that may return something different on every call, but it never inlines PL/pgSQL. Only an equality can be a hash or merge key, so c.product = cs.product becomes the hash key and the date comparison, in all three forms, stays a filter. Why PG18 didn't turn the OR into two index searches, as SQL Server did, the plan doesn't say; it shows the choice and not the reason.
PG17 ran these three the same way, plan for plan (PG17 has its own appendix).
What does scale on PostgreSQL
Two changes turned PG18's date check into an index search. The first was already in the second pilot, an index on the function's result:
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql IMMUTABLE AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
CREATE INDEX contracts_product_expiration99 ON contracts (product, dateOr99(expiration_date));
The query is unchanged. The function is declared IMMUTABLE, PostgreSQL's label for same input, same output, forever. An index needs that from any function PostgreSQL can't inline, like PL/pgSQL; this SQL one gets inlined, so the check looks at its body instead (the source appendix shows where), and I didn't try it without the label. On PG18 it took 13 ms at 8,000 lines, about 30 times faster than the hand-written condition, and its time doubles with the lines:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql IMMUTABLE AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
CREATE INDEX contracts_product_expiration99 ON contracts (product, dateOr99(expiration_date));
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 1.7 ms | At 1,000 sheet lines PG18 inlines dateOr99 into its COALESCE, matches it to the expression index, and puts the date test in the Index Cond: a Nested Loop that searches contracts_product_expiration99 once per sheet line, in 1.663 ms.QUERY PLAN
Aggregate (cost=1699.17..1699.18 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=3002 read=4
-> Nested Loop (cost=0.28..1595.00 rows=41667 width=0) (actual rows=3000.00 loops=1)
Buffers: shared hit=3002 read=4
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..1.16 rows=42 width=7) (actual rows=3.00 loops=1000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 1000
Buffers: shared hit=2996 read=4
Planning:
Buffers: shared hit=143
Planning Time: 0.283 ms
Execution Time: 1.663 ms | 0.87s |
| 2K | 3.4 ms | At 2,000 lines PG18's Nested Loop makes 2,000 index searches, each returning the 3 contracts that never expire, in 3.421 ms.QUERY PLAN
Aggregate (cost=6058.67..6058.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=6004 read=7
-> Nested Loop (cost=0.28..5642.00 rows=166667 width=0) (actual rows=6000.00 loops=1)
Buffers: shared hit=6004 read=7
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..1.98 rows=83 width=7) (actual rows=3.00 loops=2000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 2000
Buffers: shared hit=5993 read=7
Planning:
Buffers: shared hit=143
Planning Time: 0.310 ms
Execution Time: 3.421 ms | 0.79s |
| 4K | 6.7 ms | At 4,000 lines PG18's time doubles with the lines, to 6.668 ms: one index search per sheet line, and nothing checked pair by pair.QUERY PLAN
Aggregate (cost=23028.67..23028.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=12013 read=9
-> Nested Loop (cost=0.28..21362.00 rows=666667 width=0) (actual rows=12000.00 loops=1)
Buffers: shared hit=12013 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..3.66 rows=167 width=7) (actual rows=3.00 loops=4000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 4000
Buffers: shared hit=11991 read=9
Planning:
Buffers: shared hit=143
Planning Time: 0.346 ms
Execution Time: 6.668 ms | 0.89s |
| 8K | 13.4 ms | At 8,000 lines PG18's Nested Loop runs 8,000 index searches in 13.387 ms. The function is still in the query, but the index turns its date test into a search instead of a check on every pair.QUERY PLAN
Aggregate (cost=89242.67..89242.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24035 read=9
-> Nested Loop (cost=0.28..82576.00 rows=2666667 width=0) (actual rows=24000.00 loops=1)
Buffers: shared hit=24035 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..6.98 rows=333 width=7) (actual rows=3.00 loops=8000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 8000
Buffers: shared hit=23991 read=9
Planning:
Buffers: shared hit=143
Planning Time: 0.346 ms
Execution Time: 13.387 ms | 0.89s |
--- PG18, dateOr99 IMMUTABLE with an index on its result, 8,000 sheet lines, 13 ms ---
Aggregate
-> Nested Loop
-> Seq Scan on contract_sheet cs
-> Index Scan using contracts_product_expiration99 on contracts c (... loops=8000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
The date condition is inside the Index Cond, so each sheet line gets one index search, which comes back with just the three contracts that never expire. PostgreSQL simplifies the index's expression the same way as the query's, and both arrive as the same COALESCE.
The second change came two pilots later: a UNION ALL of two counts, one with IS NULL and one with > max_year, so each half is a plain condition on the index's second column. On PG18 it took 13 ms at 8,000 lines and also doubled with the lines (its card is in the PostgreSQL appendix). PG17 matched PG18 on the index, and the split ran on PG18 only.
The split's doubling held only up to 8,000 lines. At 80,000 it took 13 seconds on PG18, nearly a thousand times as long for ten times the lines. PG18 stopped searching the index for the > max_year half and hashed it on product instead, in three processes like the hand-written condition, with expiration_date > max_year as the Join Filter on all 800 million pairs:
EXPLAIN (ANALYZE, TIMING OFF) SELECT sum(n) AS outliving FROM (SELECT count(*) AS n FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date IS NULL UNION ALL SELECT count(*) FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date > cs.max_year) tCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 13.4 ms | At 8,000 sheet lines PG18 plans the split as in the main run: the > half searches contracts_product_expiration 8,000 times in a Nested Loop and finds nothing, the IS NULL half answers 7,992 of its lookups from a Memoize cache, and the call takes 13.387 ms.QUERY PLAN
Aggregate (cost=89653.89..89653.90 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=24104 read=9
-> Append (cost=587.18..89653.88 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=24104 read=9
-> Aggregate (cost=587.18..587.19 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=60 read=9
-> Nested Loop (cost=0.29..527.18 rows=24000 width=0) (actual rows=24000.00 loops=1)
Buffers: shared hit=60 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=3) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Memoize (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=8000)
Cache Key: cs.product
Cache Mode: logical
Hits: 7992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=16 read=9
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.28..0.35 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=16 read=9
-> Aggregate (cost=89066.67..89066.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24044
-> Nested Loop (cost=0.28..82400.00 rows=2666667 width=0) (actual rows=0.00 loops=1)
Buffers: shared hit=24044
-> Seq Scan on contract_sheet cs_1 (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.28..6.95 rows=333 width=7) (actual rows=0.00 loops=8000)
Index Cond: ((product = cs_1.product) AND (expiration_date > cs_1.max_year))
Heap Fetches: 0
Index Searches: 8000
Buffers: shared hit=24000
Planning:
Buffers: shared hit=148
Planning Time: 0.340 ms
Execution Time: 13.387 ms | 0.93s |
| 80K | 13.1s | At 80,000 lines PG18 stops searching the index for the > half. It hashes the sheet on product in a parallel Hash Join, Workers Launched: 2, and its Join Filter, expiration_date > max_year, removes 266,666,667 pairs in each of its 3 loops and keeps none. The IS NULL half still takes 79,992 cache hits, and the call takes 13,140.531 ms.QUERY PLAN
Aggregate (cost=4885278.78..4885278.79 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=1800 read=220
-> Append (cost=5911.30..4885278.77 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=1800 read=220
-> Aggregate (cost=5911.30..5911.31 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=449 read=9
-> Nested Loop (cost=0.30..5236.26 rows=270015 width=0) (actual rows=240000.00 loops=1)
Buffers: shared hit=449 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..1233.00 rows=80000 width=3) (actual rows=80000.00 loops=1)
Buffers: shared hit=433
-> Memoize (cost=0.30..0.37 rows=3 width=3) (actual rows=3.00 loops=80000)
Cache Key: cs.product
Cache Mode: logical
Hits: 79992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=16 read=9
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=16 read=9
-> Finalize Aggregate (cost=4879367.44..4879367.45 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=1351 read=211
-> Gather (cost=4879367.22..4879367.43 rows=2 width=8) (actual rows=3.00 loops=1)
Workers Planned: 2
Workers Launched: 2
Buffers: shared hit=1351 read=211
-> Partial Aggregate (cost=4878367.22..4878367.23 rows=1 width=8) (actual rows=1.00 loops=3)
Buffers: shared hit=1351 read=211
-> Hash Join (cost=2233.29..4600574.25 rows=111117189 width=0) (actual rows=0.00 loops=3)
Hash Cond: (c_1.product = cs_1.product)
Join Filter: (c_1.expiration_date > cs_1.max_year)
Rows Removed by Join Filter: 266666667
Buffers: shared hit=1351 read=211
-> Parallel Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.29..1617.63 rows=33333 width=7) (actual rows=26666.67 loops=3)
Heap Fetches: 0
Index Searches: 1
Buffers: shared hit=12 read=211
-> Hash (cost=1233.00..1233.00 rows=80000 width=7) (actual rows=80000.00 loops=3)
Buckets: 131072 Batches: 1 Memory Usage: 4149kB
Buffers: shared hit=1339
-> Seq Scan on contract_sheet cs_1 (cost=0.00..1233.00 rows=80000 width=7) (actual rows=80000.00 loops=3)
Buffers: shared hit=1339
Planning:
Buffers: shared hit=148
Planning Time: 0.382 ms
Execution Time: 13140.531 ms | 14.35s |
A call that also ran the split at 800,000 lines timed out after 330 seconds without a result. Here's PG18 on one chart, every version that ran at 80,000 lines:
Only the index stayed in milliseconds. It also ran at 800,000 lines, in 1.6 seconds on PG18, still one index search per sheet line (its card is in the PostgreSQL appendix).
MySQL: nothing I tried
On MySQL 8.0.39 the hand-written condition, with no function anywhere, still checks every pair:
EXPLAIN ANALYZE SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)SET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL, INDEX contracts_product_expiration (product, expiration_date));
INSERT INTO contracts (id, product, expiration_date)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN i <= 24 THEN NULL ELSE DATE_ADD('2026-01-02', INTERVAL (i - 1) DIV 8 DAY) END
FROM s;
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'), DATE_ADD('2026-01-02', INTERVAL (${N} DIV 8 + i) DAY)
FROM s;
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE NO SQL RETURN COALESCE(d, '9999-01-01');
ANALYZE TABLE contracts, contract_sheet;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 39 ms | At 1,000 sheet lines MySQL looks each line's product up in contracts_product_expiration, gets 125 contracts back, and checks the OR on each of them in a Filter. The root line reports 37.1 ms.EXPLAIN
-> Aggregate: count(0) (cost=17911 rows=1) (actual time=37.1..37.1 rows=1 loops=1)
-> Nested loop inner join (cost=12911 rows=49996) (actual time=0.0381..37 rows=3000 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0161..0.21 rows=1000 loops=1)
-> Filter: ((c.expiration_date is null) or (c.expiration_date > cs.max_year)) (cost=0.315 rows=50) (actual time=0.0131..0.0365 rows=3 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.315 rows=125) (actual time=0.0129..0.0273 rows=125 loops=1000)
| 0.28s |
| 2K | 152 ms | At 2,000 lines MySQL's lookups return 250 contracts each and the Filter keeps the 3 that never expire, so the work per line has doubled with the lines. The root line reports 149 ms.EXPLAIN
-> Aggregate: count(0) (cost=70943 rows=1) (actual time=149..149 rows=1 loops=1)
-> Nested loop inner join (cost=50944 rows=199985) (actual time=0.0383..148 rows=6000 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.0162..0.424 rows=2000 loops=1)
-> Filter: ((c.expiration_date is null) or (c.expiration_date > cs.max_year)) (cost=0.376 rows=100) (actual time=0.014..0.0737 rows=3 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.376 rows=250) (actual time=0.0139..0.056 rows=250 loops=2000)
| 0.41s |
| 4K | 560 ms | At 4,000 lines MySQL makes one lookup per sheet line and hands 500 contracts from each to the Filter. The root line reports 557 ms, close to four times as long as at half the size.EXPLAIN
-> Aggregate: count(0) (cost=282369 rows=1) (actual time=557..557 rows=1 loops=1)
-> Nested loop inner join (cost=202375 rows=799940) (actual time=0.0436..557 rows=12000 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.0163..0.823 rows=4000 loops=1)
-> Filter: ((c.expiration_date is null) or (c.expiration_date > cs.max_year)) (cost=0.498 rows=200) (actual time=0.0135..0.139 rows=3 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.498 rows=500) (actual time=0.0133..0.105 rows=500 loops=4000)
| 0.88s |
| 8K | 2.2s | At 8,000 lines MySQL's Filter checks the OR on all 1,000 contracts of a line's product, for every sheet line. The root line reports 2,159 ms: no function left to call, and still a check on every pair.EXPLAIN
-> Aggregate: count(0) (cost=1.13e+6 rows=1) (actual time=2159..2159 rows=1 loops=1)
-> Nested loop inner join (cost=806699 rows=3.2e+6) (actual time=0.0384..2158 rows=24000 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.016..1.48 rows=8000 loops=1)
-> Filter: ((c.expiration_date is null) or (c.expiration_date > cs.max_year)) (cost=0.742 rows=400) (actual time=0.0132..0.269 rows=3 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.742 rows=1000) (actual time=0.013..0.203 rows=1000 loops=8000)
| 2.54s |
2.2 seconds at 8,000 lines on MySQL 8.0.39, and four times as long each time the lines double.
The stored function took 16 seconds on MySQL 8.0.39, 7.6 times as long, so writing it out saved the calls, but not the pairs.
Declaring it DETERMINISTIC didn't help either: 16 seconds on MySQL 8.0.39. MySQL doesn't check that promise, and a deterministic function of a column still runs again whenever the column's value changes, which here is on every pair. MySQL took the promise and still ran the filter that calls it on all 8 million pairs.
In the next two pilots I tried two more forms. A MySQL functional index can't contain a stored function, so I indexed the COALESCE written out and joined on the same expression: 2.1 seconds on MySQL 8.0.39, and the plan never touched the new index. Then came the UNION ALL split that worked on PG18 up to 8,000 lines, and its plan shows why every form took about four times as long per doubling:
--- MySQL 8.0.39, UNION ALL split, 8,000 sheet lines, 2.1 seconds ---
-> Union all materialize
-> Aggregate: count(0) (... actual time=28.8..28.8 ...)
-> Nested loop inner join
-> Table scan on cs
-> Filter: (c.expiration_date is null)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product, expiration_date=NULL)
-> Aggregate: count(0) (... actual time=2047..2047 ...)
-> Nested loop inner join
-> Table scan on cs
-> Filter: (c.expiration_date > cs.max_year)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product)
The IS NULL half is an index lookup on product and NULL, and it's quick. The > half looks up by product alone and filters every contract that comes back. MySQL's index lookup inside a join only takes = and <=>, a range on the index's second column needs a constant, and cs.max_year is a column of the other table. MySQL can also check a range row by row, but only when it has "no good index to use", and the lookup on product is one.
So nothing I tried got the > comparison off the pairwise check on MySQL 8.0.39. I didn't try a LATERAL join or a correlated subquery, so this is where my list ends, not where MySQL's options do. I really wanted a MySQL fix for this join, but I don't have one (the other four calls are in the MySQL appendix).
Where the nested loops were
The other question from the start, whether a function in a join forces a nested loop, needed a join with an = in it:
SELECT count(*) AS matched
FROM crm a
JOIN billing b ON norm_email(a.email) = norm_email(b.email);
The two email lists differ only in case and spaces, and norm_email() matches them with lower(trim()) on both sides. With a function on each side, one case forced a nested loop: PostgreSQL, with norm_email() in PL/pgSQL and left at the default VOLATILE. Here it is on PG18:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS matched FROM crm a JOIN billing b ON norm_email(a.email) = norm_email(b.email)CREATE TABLE crm (id int PRIMARY KEY, email text NOT NULL);
CREATE TABLE billing (id int PRIMARY KEY, email text NOT NULL);
INSERT INTO crm SELECT i, 'user' || i || '@example.com' FROM generate_series(1, ${M}) i;
INSERT INTO billing SELECT i, ' USER' || i || '@Example.COM ' FROM generate_series(1, ${M}) i;
CREATE FUNCTION norm_email(e text) RETURNS text LANGUAGE plpgsql AS $$ BEGIN RETURN lower(trim(e)); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 235.2 ms | At 500 rows a side PG18 won't hash or merge on norm_email(a.email) = norm_email(b.email), since the function is VOLATILE. It runs a Nested Loop over a Materialize of billing and calls the function in the Join Filter for every pair, in 235.219 ms.QUERY PLAN
Aggregate (cost=128772.38..128772.39 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24
-> Nested Loop (cost=0.00..128769.25 rows=1250 width=0) (actual rows=500.00 loops=1)
Join Filter: (norm_email(a.email) = norm_email(b.email))
Rows Removed by Join Filter: 249500
Buffers: shared hit=24
-> Seq Scan on crm a (cost=0.00..9.00 rows=500 width=19) (actual rows=500.00 loops=1)
Buffers: shared hit=4
-> Materialize (cost=0.00..11.50 rows=500 width=22) (actual rows=500.00 loops=500)
Storage: Memory Maximum Storage: 40kB
Buffers: shared hit=4
-> Seq Scan on billing b (cost=0.00..9.00 rows=500 width=22) (actual rows=500.00 loops=1)
Buffers: shared hit=4
Planning:
Buffers: shared hit=72
Planning Time: 0.216 ms
Execution Time: 235.219 ms | 1.04s |
| 1K | 832 ms | At 1,000 rows a side PG18's Join Filter removes 999,000 pairs on the same Nested Loop, and the call takes 831.983 ms, about three and a half times as long as at half the rows.QUERY PLAN
Aggregate (cost=515050.00..515050.01 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=31
-> Nested Loop (cost=0.00..515037.50 rows=5000 width=0) (actual rows=1000.00 loops=1)
Join Filter: (norm_email(a.email) = norm_email(b.email))
Rows Removed by Join Filter: 999000
Buffers: shared hit=31
-> Seq Scan on crm a (cost=0.00..17.00 rows=1000 width=19) (actual rows=1000.00 loops=1)
Buffers: shared hit=7
-> Materialize (cost=0.00..23.00 rows=1000 width=22) (actual rows=1000.00 loops=1000)
Storage: Memory Maximum Storage: 63kB
Buffers: shared hit=8
-> Seq Scan on billing b (cost=0.00..18.00 rows=1000 width=22) (actual rows=1000.00 loops=1)
Buffers: shared hit=8
Planning:
Buffers: shared hit=72
Planning Time: 0.221 ms
Execution Time: 831.983 ms | 1.57s |
| 2K | 3.3s | At 2,000 rows a side PG18's Join Filter removes 3,998,000 pairs and keeps the 2,000 matches. The call takes 3,258.880 ms: two function calls on every pair, and the pairs grow with the square of the rows.QUERY PLAN
Aggregate (cost=2060124.00..2060124.01 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=45
-> Nested Loop (cost=0.00..2060074.00 rows=20000 width=0) (actual rows=2000.00 loops=1)
Join Filter: (norm_email(a.email) = norm_email(b.email))
Rows Removed by Join Filter: 3998000
Buffers: shared hit=45
-> Seq Scan on crm a (cost=0.00..34.00 rows=2000 width=20) (actual rows=2000.00 loops=1)
Buffers: shared hit=14
-> Materialize (cost=0.00..45.00 rows=2000 width=23) (actual rows=2000.00 loops=2000)
Storage: Memory Maximum Storage: 110kB
Buffers: shared hit=15
-> Seq Scan on billing b (cost=0.00..35.00 rows=2000 width=23) (actual rows=2000.00 loops=1)
Buffers: shared hit=15
Planning:
Buffers: shared hit=72
Planning Time: 0.210 ms
Execution Time: 3258.880 ms | 3.97s |
3.3 seconds on PG18 at 2,000 rows a side. Written inline, the same join took 1.9 ms on PG18, about 1,750 times faster.
Two other versions took a few milliseconds too: a LANGUAGE sql version, which PG18 inlined, and the PL/pgSQL function declared IMMUTABLE. The default against IMMUTABLE:
--- PG18, PL/pgSQL norm_email() at the default VOLATILE, 2,000 rows a side, 3.3 seconds ---
Aggregate
-> Nested Loop
Join Filter: (norm_email(a.email) = norm_email(b.email))
Rows Removed by Join Filter: 3998000
--- PG18, the same function declared IMMUTABLE, 2,000 rows a side, 3.2 ms ---
Aggregate
-> Merge Join
Merge Cond: ((norm_email(a.email)) = (norm_email(b.email)))
The same equality is a filter on every pair in the first plan and a merge key in the second. PostgreSQL won't hash or merge on a clause with a volatile function in it, one that may return something different on every call. PL/pgSQL is VOLATILE unless declared otherwise, so with no index to use, the only plan left compares every row with every row. SQL Server hashed the same join on the function's results even with inlining off, and MySQL 8.0.39 hash-joined its NOT DETERMINISTIC stored function.
So the nested loops from my story did turn up, on another engine and in another kind of join. The first probes found one more way to get every pair checked: a function of a column from each table, like emails_match(a.email, b.email), which PG17, SQL Server and MySQL 8.0.39 all ran against every pair (the equality-join appendix has the probes' numbers and the other six calls).
Confessions of Performance Engineering
A rebuild, not the original. The 2017 queries and schema are gone, and this is the join's shape as I remember it, with made-up contracts.
Small sheets. Most cards stop at 8,000 lines, 8 million pairs. Two of PG18's and SQL Server's inlined UDF check 800 million pairs at 80,000 lines, and three cards run to 800,000 lines: PG18's index, and SQL Server's hand-written condition and computed column. Every call behind the cards finished; a call of the UNION ALL split at 800,000 lines timed out, SQL Server's inlined UDF at 800,000 lines was stopped after 106 seconds, and neither has a card. Real sheets are bigger, and the curves only get steeper.
Single runs. Every size ran once. Where an identical call ran in two runs, PG17's and PG18's times stayed within 14% and MySQL 8.0.39's within 8%.
SQL Server moved more. Dev's serverless SQL Server ran these calls on two databases. In the main run, the inlining-off version ran its three smaller sizes on one and its 8,000 lines on the other, so I ran it again, all four sizes in one call on one database. With the same plan on the same database, the repeat ran up to about twice as fast as the main run. So the inlining-off curve is that one call, and its ratios to the main run's calls are ranges, not precise numbers (the SQL Server appendix has the main run's own calls).
Capturing the plan costs something. ExoBench captures SQL Server's actual plan, and Microsoft's query profiling documentation puts that capture, SET STATISTICS XML, on its standard profiling infrastructure, the costlier kind, so every SQL Server time here carries that overhead.
Stand-ins, not an old server. WITH INLINE = OFF and the level 140 hint show what no inlining costs on today's engine, not what our 2017 server did.
Dev, not prod. The dev database I read the settings of is serverless with up to 4 vCores; the other one may differ, and so may prod.
So, would inlining have solved all of our problems?
No. Inlining made the UDF tens of times faster and left it on the same curve, four times as long every time the listings doubled. No form of the UDF scaled on any of the three engines unless its result was precomputed in an index: the indexed computed column on SQL Server, faster than the hand-written fix and with every query left as it was, and the index on the function's result on PG18. MySQL 8.0.39 can't put a stored function in an index, and nothing I tried there scaled. Precomputing has its own price: the index stores the function's result for every row and keeps it current as rows are inserted and updated.
The hand-written fix only scales on one of the three engines:
| Engine | IS NULL OR > by hand | What scaled with the lines |
|---|---|---|
| SQL Server (Azure SQL Database, level 170) | two seeks per line, twice as long per doubling | the hand-written condition, or inlining plus an indexed computed column |
| PG18 | every pair, four times as long per doubling | an index on the function's result (a UNION ALL split only up to 8,000 lines) |
| MySQL 8.0.39 | every pair, four times as long per doubling | nothing I tried |
PG17 matched PG18 wherever it ran. On PostgreSQL, a PL/pgSQL function that really is immutable should say so before it goes into an equality join.
dateOr99 never panned out. The fix we found for it doesn't age well... or at all!
Moral of the story: never use UDFs!
Appendix: SQL Server's other calls
Every call here but the last ran in the main run, on the same tables and query as the SQL Server cards in the body.
Inlining off, as called in the main run. The same arguments as the body's inlining-off card at its three smaller sizes, with the same plan on the same database, 09222264. It took up to about twice as long, the run-to-run variance from the confessions:
| Sheet lines | Main run | The body's card (repeat run) | Main run over repeat |
|---|---|---|---|
| 1,000 | 734 ms | 337 ms | 2.18 |
| 2,000 | 2.8 s | 1.5 s | 1.91 |
| 4,000 | 11 s | 6.6 s | 1.71 |
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE WITH INLINE = OFF AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 734 ms | At 1,000 sheet lines the main run's SQL Server call hashes the sheet on product and calls dateOr99 in the Probe Residual for each contract and sheet line on the same product, on one thread. The call takes 734 ms, and its CPU Time is 734 ms too.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.249585 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.249585 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=734 CPUms=734)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=1000 IO=0 CPU=0.23725 SubtreeCost=0.248985 AvgRowSize=9) (actual Rows=3000 Executions=1 Elapsedms=734 CPUms=734)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_1777688c_ecf9_411f_b5a6_5b07cb366a3d].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1344kB Output=1344kB Used=512kB
-> Clustered Index Scan [PK__contract__F5AE5F621895834E] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=1000 RowsRead=1000 IO=0.00386574 CPU=0.001257 SubtreeCost=0.00512274 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=4 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1344kB MaxUsed=512kB Required=1024kB Desired=1344kB Requested=1344kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=18ms CPU=11ms Memory=360kB CachedPlanSize=48kB
CPU Time: 734 ms
Execution Time: 734 ms | 1.31s |
| 2K | 2.8s | At 2,000 lines the SQL Server plan is unchanged, Query Plan Hash 0x232EC548D07F2395, and the call takes 2,797 ms, close to four times as long as at half the size. CPU is 2,792 ms, nearly all of it.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.874901 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.874901 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=2797 CPUms=2792)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=2000 IO=0 CPU=0.855321 SubtreeCost=0.873701 AvgRowSize=9) (actual Rows=6000 Executions=1 Elapsedms=2796 CPUms=2792)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_83c0f675_bd84_46fe_a55d_951431f93045].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1632kB Output=1632kB Used=512kB
-> Clustered Index Scan [PK__contract__F5AE5F62100557EB] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=2000 RowsRead=2000 IO=0.00534722 CPU=0.002357 SubtreeCost=0.00770422 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 4 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1632kB MaxUsed=512kB Required=1024kB Desired=1632kB Requested=1632kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=6 WaitCount=697
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=4 WaitCount=1
Compile: Time=17ms CPU=10ms Memory=368kB CachedPlanSize=48kB
CPU Time: 2792 ms
Execution Time: 2797 ms | 3.52s |
| 4K | 11.3s | At 4,000 lines SQL Server takes 11,327 ms with 11,306 ms of CPU, still on one thread, about four times as long as at half the size again.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=3.32125 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=3.32125 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=11327 CPUms=11306)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=4000 IO=0 CPU=3.28718 SubtreeCost=3.31885 AvgRowSize=9) (actual Rows=12000 Executions=1 Elapsedms=11327 CPUms=11305)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_7be90678_ba0f_4abe_8e5f_842664334c14].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1184kB Output=1184kB Used=400kB
-> Clustered Index Scan [PK__contract__F5AE5F62EA35FF62] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 3 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=4000 RowsRead=4000 IO=0.00831019 CPU=0.004557 SubtreeCost=0.0128672 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 4 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1184kB MaxUsed=400kB Required=1024kB Desired=1184kB Requested=1184kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=29 WaitCount=2822
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=16 WaitCount=4
Compile: Time=26ms CPU=19ms Memory=352kB CachedPlanSize=48kB
CPU Time: 11306 ms
Execution Time: 11327 ms | 11.93s |
Its 8,000-line call, made on its own, landed on the other database, c9ebddf4, which its plan names. The plan is the same again, at 28 seconds:
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE WITH INLINE = OFF AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 28s | At 8,000 sheet lines SQL Server runs the same serial Hash Match, with dateOr99 in the Probe Residual for every contract and sheet line on the same product, on database c9ebddf4. The call takes 27,964 ms, 27,943 ms of it on the CPU, and counts 24,000 contracts.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=12.9961 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=12.9961 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=27964 CPUms=27943)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Hash Match (Inner Join) (est Rows=8000 IO=0 CPU=12.9338 SubtreeCost=12.9913 AvgRowSize=9) (actual Rows=24000 Executions=1 Elapsedms=27963 CPUms=27942)
Node Id: 2 Mode: Row
Hash Keys Build: cs.product
Hash Keys Probe: c.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_96640bb0_c2e0_470c_8761_c17e0e7dc8ba].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=2368kB Output=2368kB Used=632kB
-> Clustered Index Scan [PK__contract__F5AE5F62A5D59878] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 3 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=8000 RowsRead=8000 IO=0.0134954 CPU=0.008957 SubtreeCost=0.0224524 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=9 CPUms=9)
Node Id: 4 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=17 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x232EC548D07F2395
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=2368kB MaxUsed=632kB Required=1024kB Desired=2368kB Requested=2368kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=40 WaitCount=6979
Compile: Time=27ms CPU=17ms Memory=336kB CachedPlanSize=48kB
CPU Time: 27943 ms
Execution Time: 27964 ms | 28.67s |
The compatibility level 140 hint, the SQL Server 2017 optimizer, which doesn't inline the function: a merge join with dateOr99 in its residual. The merge join's RowsRead counts the pairs. It went from 806 ms to 12 seconds across its three sizes.
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_year OPTION (USE HINT('QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_140'))CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 806 ms | At 1,000 sheet lines the hinted SQL Server plan sorts the sheet and merge-joins it to contracts on product, with dateOr99 in the Merge Join's Residual on every pair it reads, 125,007 rows. It runs on one thread, with the cardinality estimator the plan calls CE model 140, in 806 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.183096 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.183096 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=806 CPUms=806)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Merge Join (Inner Join) (est Rows=1000 IO=0.000313 CPU=0.14354 SubtreeCost=0.182496 AvgRowSize=9) (actual Rows=3000 RowsRead=125007 Executions=1 Elapsedms=806 CPUms=806)
Node Id: 2 Mode: Row
Many To Many: true
Outer Side Join Columns: c.product
Inner Side Join Columns: cs.product
Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_ae55653b_5c20_465a_916d_8d2b8e7e7334].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
I/O: Scans=8 LogicalReads=4015 EndOfScans=1
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=1000 RowsRead=1000 IO=0.00386574 CPU=0.001257 SubtreeCost=0.00512274 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 3 Mode: Row Table Cardinality: 1000 Storage: RowStore Ordered: FORWARD
I/O: Scans=1 LogicalReads=4 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Sort (est Rows=1000 IO=0.0112613 CPU=0.0156466 SubtreeCost=0.0335121 AvgRowSize=12) (actual Rows=1000 Executions=1 Rebinds=1 Elapsedms=1 CPUms=1)
Node Id: 4 Mode: Row
Order By: cs.product
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1024kB Output=640kB Used=48kB
Output List: cs.product, cs.max_year
-> Clustered Index Scan [PK__contract__F5AE5F621CB7EA6A] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 5 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 140
Query Plan Hash: 0x1FC20ADCF93848D6
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1024kB MaxUsed=48kB Required=512kB Desired=624kB Requested=1024kB GrantWaitTime=0ms
Compile: Time=17ms CPU=10ms Memory=368kB CachedPlanSize=32kB
CPU Time: 806 ms
Execution Time: 806 ms | 1.49s |
| 2K | 3.1s | At 2,000 lines SQL Server's Merge Join reads 500,007 rows, four times as many as at half the size. The call takes 3,097 ms, with 3,088 ms of CPU.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.596947 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.596947 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=3097 CPUms=3088)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Merge Join (Inner Join) (est Rows=2000 IO=0.000313 CPU=0.53148 SubtreeCost=0.595747 AvgRowSize=9) (actual Rows=6000 RowsRead=500007 Executions=1 Elapsedms=3097 CPUms=3088)
Node Id: 2 Mode: Row
Many To Many: true
Outer Side Join Columns: c.product
Inner Side Join Columns: cs.product
Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_bee8108c_8489_487c_9c27_4e594cf74b39].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
I/O: Scans=8 LogicalReads=8015 EndOfScans=1
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=2000 RowsRead=2000 IO=0.00534722 CPU=0.002357 SubtreeCost=0.00770422 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 3 Mode: Row Table Cardinality: 2000 Storage: RowStore Ordered: FORWARD
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Sort (est Rows=2000 IO=0.0112613 CPU=0.0343133 SubtreeCost=0.0562417 AvgRowSize=12) (actual Rows=2000 Executions=1 Rebinds=1 Elapsedms=2 CPUms=2)
Node Id: 4 Mode: Row
Order By: cs.product
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1024kB Output=640kB Used=96kB
Output List: cs.product, cs.max_year
-> Clustered Index Scan [PK__contract__F5AE5F62B8875F88] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 5 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 140
Query Plan Hash: 0xFADA370EB4975BA2
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1024kB MaxUsed=96kB Required=512kB Desired=720kB Requested=1024kB GrantWaitTime=0ms
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=11 WaitCount=770
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=9 WaitCount=2
Compile: Time=18ms CPU=11ms Memory=360kB CachedPlanSize=32kB
CPU Time: 3088 ms
Execution Time: 3097 ms | 3.80s |
| 4K | 12.2s | At 4,000 lines SQL Server's Merge Join reads 2,000,007 rows and the call takes 12,242 ms. The UDF still runs for every pair the join reads, on one thread.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=2.17777 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=2.17777 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=12241 CPUms=12237)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Merge Join (Inner Join) (est Rows=4000 IO=0.000313 CPU=2.05736 SubtreeCost=2.17537 AvgRowSize=9) (actual Rows=12000 RowsRead=2000007 Executions=1 Elapsedms=12241 CPUms=12236)
Node Id: 2 Mode: Row
Many To Many: true
Outer Side Join Columns: c.product
Inner Side Join Columns: cs.product
Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_50d7789a_019b_4587_a8a0_a2412349ac48].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
I/O: Scans=8 LogicalReads=20047 EndOfScans=1
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=4000 RowsRead=4000 IO=0.00831019 CPU=0.004557 SubtreeCost=0.0128672 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 3 Mode: Row Table Cardinality: 4000 Storage: RowStore Ordered: FORWARD
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Sort (est Rows=4000 IO=0.0112613 CPU=0.0747665 SubtreeCost=0.104821 AvgRowSize=12) (actual Rows=4000 Executions=1 Rebinds=1 Elapsedms=5 CPUms=5)
Node Id: 4 Mode: Row
Order By: cs.product
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1024kB Output=640kB Used=192kB
Output List: cs.product, cs.max_year
-> Clustered Index Scan [PK__contract__F5AE5F626389EA14] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 5 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL, CE model 140
Query Plan Hash: 0x47471F79C9E04A18
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1024kB MaxUsed=192kB Required=512kB Desired=928kB Requested=1024kB GrantWaitTime=0ms
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=12 WaitCount=3053
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=3 WaitCount=1
Compile: Time=22ms CPU=15ms Memory=344kB CachedPlanSize=32kB
CPU Time: 12237 ms
Execution Time: 12242 ms | 12.87s |
At 8,000 lines, in a call of its own, it took 48 seconds:
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_year OPTION (USE HINT('QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_140'))CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 47.8s | At 8,000 sheet lines the hinted SQL Server plan merge-joins on product and reads 8,000,007 rows in the Merge Join, calling dateOr99 in the Residual for each pair. The call takes 47,788 ms on one thread, 47,714 ms of it on the CPU.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=8.52937 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1005],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=8.52937 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=47788 CPUms=47714)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = Count(*)
-> Merge Join (Inner Join) (est Rows=8000 IO=0.000313 CPU=8.10912 SubtreeCost=8.52457 AvgRowSize=9) (actual Rows=24000 RowsRead=8000007 Executions=1 Elapsedms=47787 CPUms=47713)
Node Id: 2 Mode: Row
Many To Many: true
Outer Side Join Columns: c.product
Inner Side Join Columns: cs.product
Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [bench-azure-sql-slot-09222264-1b70-424f-bef0-3482de1f1672].[exo_temp_fb5220dc_45ff_45b1_951c_7c694de51091].[dateOr99]([contracts].[expiration_date] as [c].[expiration_date])>[contract_sheet].[max_year] as [cs].[max_year]
I/O: Scans=8 LogicalReads=48087 EndOfScans=1
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=8000 RowsRead=8000 IO=0.0134954 CPU=0.008957 SubtreeCost=0.0224524 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=7 CPUms=7)
Node Id: 3 Mode: Row Table Cardinality: 8000 Storage: RowStore Ordered: FORWARD
I/O: Scans=1 LogicalReads=17 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Sort (est Rows=8000 IO=0.0112613 CPU=0.346375 SubtreeCost=0.392681 AvgRowSize=12) (actual Rows=8000 Executions=1 Rebinds=1 Elapsedms=10 CPUms=10)
Node Id: 4 Mode: Row
Order By: cs.product
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1344kB Output=960kB Used=384kB
Output List: cs.product, cs.max_year
-> Clustered Index Scan [PK__contract__F5AE5F626D5DA3B8] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 5 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL, CE model 140
Query Plan Hash: 0x19CEF97EDF69095F
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1344kB MaxUsed=384kB Required=512kB Desired=1344kB Requested=1344kB GrantWaitTime=0ms
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=103 WaitCount=11908
Wait Stats: RESOURCE_GOVERNOR_IDLE WaitTimeMs=67 WaitCount=14
Compile: Time=33ms CPU=25ms Memory=336kB CachedPlanSize=32kB
CPU Time: 47714 ms
Execution Time: 47788 ms | 48.46s |
Inlined, the default at level 170, from 12 ms to 815 ms across the four sizes, the chart's inlined points.
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 12 ms | At 1,000 sheet lines SQL Server has no call to dateOr99 left: a Compute Scalar computes isnull(expiration_date, '9999-01-01') for each contract, and a Hash Match (Aggregate) groups contracts by product and that date, 984 groups. The Probe Residual compares each sheet line with every group of its product, and the call takes 12 ms.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=0.0625361 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.062536 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=12 CPUms=12)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=1000 IO=0 CPU=0.0255344 SubtreeCost=0.0619355 AvgRowSize=15) (actual Rows=1000 Executions=1 Elapsedms=12 CPUms=12)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.75 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1072kB Output=1088kB Used=336kB
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.0245672 SubtreeCost=0.0297899 AvgRowSize=20) (actual Rows=984 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.25
I/O: EndOfScans=1
Memory Grant: Input=1088kB Output=1040kB Used=352kB
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=1000 IO=0 CPU=0.0001 SubtreeCost=0.00522274 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=1000 RowsRead=1000 IO=0.00386574 CPU=0.001257 SubtreeCost=0.00512274 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=4 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F624AFB300E] on contract_sheet cs (est Rows=1000 RowsRead=1000 IO=0.00534722 CPU=0.001257 SubtreeCost=0.00660422 AvgRowSize=12) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xC574B285387F8335
Degree Of Parallelism: 1
Memory Grant: Granted=2112kB MaxUsed=688kB Required=2048kB Desired=2112kB Requested=2112kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=15ms CPU=7ms Memory=456kB CachedPlanSize=72kB
extra: 1
CPU Time: 12 ms
Execution Time: 12 ms | 0.63s |
| 2K | 48 ms | At 2,000 lines SQL Server's aggregate leaves 1,984 groups and the call takes 48 ms, four times as long as at half the size.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=0.0841891 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.084189 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=48 CPUms=48)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=2000 IO=0 CPU=0.0331644 SubtreeCost=0.0829885 AvgRowSize=15) (actual Rows=2000 Executions=1 Elapsedms=48 CPUms=48)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.777778 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1080kB Output=1096kB Used=344kB
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.0312457 SubtreeCost=0.0391499 AvgRowSize=20) (actual Rows=1984 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.222222
I/O: EndOfScans=1
Memory Grant: Input=1096kB Output=1040kB Used=352kB
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=2000 IO=0 CPU=0.0002 SubtreeCost=0.00790422 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=2000 RowsRead=2000 IO=0.00534722 CPU=0.002357 SubtreeCost=0.00770422 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F625B9A8882] on contract_sheet cs (est Rows=2000 RowsRead=2000 IO=0.00831019 CPU=0.002357 SubtreeCost=0.0106672 AvgRowSize=12) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 7 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xFA22674CE1551988
Degree Of Parallelism: 1
Memory Grant: Granted=2120kB MaxUsed=696kB Required=2048kB Desired=2120kB Requested=2120kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=15ms CPU=9ms Memory=448kB CachedPlanSize=72kB
extra: 1
CPU Time: 48 ms
Execution Time: 48 ms | 0.61s |
| 4K | 189 ms | At 4,000 lines SQL Server takes 189 ms for 3,984 groups. Inlining removed the function call, but each sheet line is still compared with every distinct expiration date on its product.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=0.127495 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0024005 SubtreeCost=0.127495 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=189 CPUms=188)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=4000 IO=0 CPU=0.0484244 SubtreeCost=0.125095 AvgRowSize=15) (actual Rows=4000 Executions=1 Elapsedms=188 CPUms=187)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.818182 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1096kB Output=1112kB Used=392kB
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.0446029 SubtreeCost=0.0578701 AvgRowSize=20) (actual Rows=3984 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.181818
I/O: EndOfScans=1
Memory Grant: Input=1112kB Output=1032kB Used=416kB
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=4000 IO=0 CPU=0.0004 SubtreeCost=0.0132672 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=4000 RowsRead=4000 IO=0.00831019 CPU=0.004557 SubtreeCost=0.0128672 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=10 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F622DC11566] on contract_sheet cs (est Rows=4000 RowsRead=4000 IO=0.0142361 CPU=0.004557 SubtreeCost=0.0187931 AvgRowSize=12) (actual Rows=4000 RowsRead=4000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 7 Mode: Row Table Cardinality: 4000 Storage: RowStore
I/O: Scans=1 LogicalReads=18 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x2D09CDED4B2114A6
Degree Of Parallelism: 1
Memory Grant: Granted=2136kB MaxUsed=808kB Required=2048kB Desired=2136kB Requested=2136kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=1 WaitCount=47
Compile: Time=25ms CPU=14ms Memory=416kB CachedPlanSize=72kB
extra: 1
CPU Time: 188 ms
Execution Time: 189 ms | 0.76s |
| 8K | 815 ms | At 8,000 lines SQL Server's 7,984 groups take 815 ms, more than four times as long as at half the size, on one thread. The date comparison still runs for every sheet line against every date on its product, so the time keeps growing with the square of the lines.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=0.213366 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=0.213366 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=815 CPUms=814)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=8000 IO=0 CPU=0.0789444 SubtreeCost=0.208566 AvgRowSize=15) (actual Rows=8000 Executions=1 Elapsedms=814 CPUms=814)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.846154 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1112kB Output=1128kB Used=536kB
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.0713172 SubtreeCost=0.0945695 AvgRowSize=20) (actual Rows=7984 Executions=1 Elapsedms=5 CPUms=5)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.153846
I/O: EndOfScans=1
Memory Grant: Input=1128kB Output=1040kB Used=480kB
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=8000 IO=0 CPU=0.0008 SubtreeCost=0.0232524 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=8000 RowsRead=8000 IO=0.0134954 CPU=0.008957 SubtreeCost=0.0224524 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 6 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=17 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F62C034D9A3] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 7 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x97E9AEAB5DA5ADC6
Degree Of Parallelism: 1
Memory Grant: Granted=2152kB MaxUsed=1016kB Required=2048kB Desired=2152kB Requested=2152kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=1 WaitCount=204
Compile: Time=24ms CPU=17ms Memory=416kB CachedPlanSize=72kB
extra: 1
CPU Time: 814 ms
Execution Time: 815 ms | 1.46s |
At ten times the lines. A later call ran the inlined UDF at 8,000 and 80,000 lines, with the main run's query and tables, and got the same hash join on one thread at both sizes. It took 630 ms and 64 seconds. Its call at 800,000 lines was stopped after 106 seconds without a result. SQL Server's plan for that size, asked for without running it, was the same hash join, in parallel and in batch mode.
SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND ${SCHEMA}.dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL);
INSERT INTO contracts (id, product, expiration_date)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN gs.value <= 24 THEN NULL ELSE DATEADD(DAY, (gs.value - 1) / 8, CAST('2026-01-02' AS DATE)) END
FROM GENERATE_SERIES(1, ${N}) gs;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
SELECT gs.value,
CHOOSE(gs.value % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
DATEADD(DAY, ${N} / 8 + gs.value, CAST('2026-01-02' AS DATE))
FROM GENERATE_SERIES(1, ${N}) gs;
UPDATE STATISTICS contracts; UPDATE STATISTICS contract_sheet;
CREATE FUNCTION dateOr99(@d DATE) RETURNS DATE AS
BEGIN
RETURN ISNULL(@d, DATEFROMPARTS(9999, 1, 1));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 630 ms | At 8,000 sheet lines SQL Server runs the main run's plan on one thread: a Hash Match (Aggregate) leaves 7,984 groups of product and isnull date, and the Probe Residual compares each sheet line with every group on its product. The call takes 630 ms.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=0.213366 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0048005 SubtreeCost=0.213366 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=629 CPUms=629)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=8000 IO=0 CPU=0.0789444 SubtreeCost=0.208566 AvgRowSize=15) (actual Rows=8000 Executions=1 Elapsedms=629 CPUms=628)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.846154 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1112kB Output=1128kB Used=536kB
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.0713172 SubtreeCost=0.0945695 AvgRowSize=20) (actual Rows=7984 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.153846
I/O: EndOfScans=1
Memory Grant: Input=1128kB Output=1040kB Used=480kB
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=8000 IO=0 CPU=0.0008 SubtreeCost=0.0232524 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=8000 RowsRead=8000 IO=0.0134954 CPU=0.008957 SubtreeCost=0.0224524 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 6 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=17 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F6222ADD6F6] on contract_sheet cs (est Rows=8000 RowsRead=8000 IO=0.026088 CPU=0.008957 SubtreeCost=0.035045 AvgRowSize=12) (actual Rows=8000 RowsRead=8000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 7 Mode: Row Table Cardinality: 8000 Storage: RowStore
I/O: Scans=1 LogicalReads=34 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x4FEA93B9882DFCA5
Degree Of Parallelism: 1
Memory Grant: Granted=2152kB MaxUsed=1016kB Required=2048kB Desired=2152kB Requested=2152kB GrantWaitTime=0ms Feedback: No: First Execution
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=1 WaitCount=157
Compile: Time=22ms CPU=16ms Memory=416kB CachedPlanSize=72kB
extra: 1
CPU Time: 629 ms
Execution Time: 630 ms | 1.24s |
| 80K | 63.8s | At 80,000 lines the plan is the same, still on one thread. The aggregate leaves 79,984 groups, each sheet line is compared with every group on its product, and the call takes 63,772 ms, with 63,124 ms of CPU Time: about a hundred times as long for ten times the lines.Compute Scalar (est Rows=1 IO=0 CPU=0.0000001 SubtreeCost=1.76498 AvgRowSize=11)
Node Id: 1 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[globalagg1006],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0480005 SubtreeCost=1.76498 AvgRowSize=15) (actual Rows=1 Executions=1 Elapsedms=63772 CPUms=63124)
Node Id: 2 Mode: Row
I/O: EndOfScans=1
Output List: globalagg1006
Defined Values: globalagg1006 = SUM([partialagg1005])
-> Hash Match (Inner Join) (est Rows=80000 IO=0 CPU=0.628304 SubtreeCost=1.71698 AvgRowSize=15) (actual Rows=80000 Executions=1 Elapsedms=63764 CPUms=63117)
Node Id: 3 Mode: Row
Hash Keys Build: c.product
Hash Keys Probe: cs.product
Probe Residual: [contracts].[product] as [c].[product]=[contract_sheet].[product] as [cs].[product] AND [Expr1003]>[contract_sheet].[max_year] as [cs].[max_year]
Memory Fractions: Input=0.916667 Output=1
I/O: Scans=14 LogicalReads=384 PhysicalReads=63 ReadAheads=728 EndOfScans=1
Memory Grant: Input=1200kB Output=1216kB Used=1096kB
Spill: Level=3 SpilledThreads=1
Hash Spill: GrantedMemoryKb=1152 UsedMemoryKb=1096 WritesToTempDb=728 ReadsFromTempDb=728
Output List: partialagg1005
-> Hash Match (Aggregate) (est Rows=8 IO=0 CPU=0.552174 SubtreeCost=0.763308 AvgRowSize=20) (actual Rows=79984 Executions=1 Elapsedms=465 CPUms=117)
Node Id: 4 Mode: Row
Hash Keys Build: c.product, Expr1003
Build Residual: [contracts].[product] as [c].[product] = [contracts].[product] as [c].[product] AND [Expr1003] = [Expr1003]
Memory Fractions: Input=1 Output=0.0833333
I/O: Scans=12 LogicalReads=256 PhysicalReads=33 ReadAheads=456 EndOfScans=1
Memory Grant: Input=1216kB Output=1040kB Used=1160kB
Spill: Level=2 SpilledThreads=1
Hash Spill: GrantedMemoryKb=1216 UsedMemoryKb=1160 WritesToTempDb=456 ReadsFromTempDb=456
Output List: c.product, Expr1003, partialagg1005
Defined Values: partialagg1005 = COUNT(*)
-> Compute Scalar (est Rows=80000 IO=0 CPU=0.008 SubtreeCost=0.211134 AvgRowSize=12)
Node Id: 5 Mode: Row
Output List: c.product, Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(date,isnull([contracts].[expiration_date] as [c].[expiration_date],'9999-01-01'),0)
-> Index Scan [contracts_product_expiration] on contracts c (est Rows=80000 RowsRead=80000 IO=0.114977 CPU=0.088157 SubtreeCost=0.203134 AvgRowSize=12) (actual Rows=80000 RowsRead=80000 Executions=1 Elapsedms=12 CPUms=12)
Node Id: 6 Mode: Row Table Cardinality: 80000 Storage: RowStore
I/O: Scans=1 LogicalReads=154 EndOfScans=1
Output List: c.product, c.expiration_date
Defined Values: c.product; c.expiration_date
-> Clustered Index Scan [PK__contract__F5AE5F6216C57684] on contract_sheet cs (est Rows=80000 RowsRead=80000 IO=0.237199 CPU=0.088157 SubtreeCost=0.325356 AvgRowSize=12) (actual Rows=80000 RowsRead=80000 Executions=1 Elapsedms=42 CPUms=34)
Node Id: 7 Mode: Row Table Cardinality: 80000 Storage: RowStore
I/O: Scans=1 LogicalReads=319 EndOfScans=1
Output List: cs.product, cs.max_year
Defined Values: cs.product; cs.max_year
Statement: SELECT, optimization FULL, CE model 170
Query Plan Hash: 0x3CFDFA1A71F19490
Degree Of Parallelism: 1
Memory Grant: Granted=2240kB MaxUsed=2024kB Required=2048kB Desired=2240kB Requested=2240kB GrantWaitTime=0ms Feedback: No: First Execution
Missing Index: contract_sheet (EQUALITY product; INEQUALITY max_year) Impact=53.1004
Wait Stats: SOS_SCHEDULER_YIELD WaitTimeMs=90 WaitCount=15745
Wait Stats: PAGEIOLATCH_SH WaitTimeMs=8 WaitCount=1
Wait Stats: RESERVED_MEMORY_ALLOCATION_EXT WaitTimeMs=1 WaitCount=1322
Compile: Time=229ms CPU=122ms Memory=408kB CachedPlanSize=72kB
extra: 1
CPU Time: 63124 ms
Execution Time: 63772 ms | 65.06s |
Source: the main run, 20261119_212614_udf-post-dev, seq 5 to 9. The body's inlining-off card is the repeat run, 20261119_221750_udf-post-ss-dev, seq 1. The three later cards: the hand-written condition to 800,000 lines, 20261120_165401_ss-scale-timed-dev, seq 1; the computed column to 800,000 lines, 20261120_170109_ss-scale-timed-dev, seq 1; the inlined UDF at 80,000 lines, 20261120_170218_ss-scale-timed-dev, seq 1. The plan for 800,000 lines is 20261120_165053_ss-scale-plans-dev, seq 1.
Appendix: PG18's other calls
The first three ran in the main run on PG18 (PostgreSQL 18.7), under EXPLAIN (ANALYZE, TIMING OFF), one execution per size.
dateOr99 as PL/pgSQL, which PostgreSQL never inlines: the same hash join as the hand-written condition, with dateor99() called in the Join Filter on every pair, from 31 ms to 1.9 seconds across the four sizes.
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 31.5 ms | At 1,000 sheet lines PG18 hashes the contracts on product and calls dateor99(c.expiration_date) in the Join Filter on every sheet line and contract that share a product. It removes 122,000 pairs in 31.497 ms.QUERY PLAN
Aggregate (cost=33119.92..33119.93 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=12
-> Hash Join (cost=28.50..33015.75 rows=41667 width=0) (actual rows=3000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 122000
Buffers: shared hit=12
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
Buffers: shared hit=6
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
Planning:
Buffers: shared hit=136
Planning Time: 0.268 ms
Execution Time: 31.497 ms | 0.87s |
| 2K | 122.4 ms | At 2,000 lines PG18's Join Filter removes 494,000 pairs and the call takes 122.351 ms, close to four times as long as at half the size.QUERY PLAN
Aggregate (cost=132383.67..132383.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=22
-> Hash Join (cost=56.00..131967.00 rows=166667 width=0) (actual rows=6000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 494000
Buffers: shared hit=22
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
Buffers: shared hit=11
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
Planning:
Buffers: shared hit=136
Planning Time: 0.267 ms
Execution Time: 122.351 ms | 0.96s |
| 4K | 486.8 ms | At 4,000 lines PG18's Hash Join removes 1,988,000 pairs in the Join Filter, a PL/pgSQL call for each pair it tests, and takes 486.804 ms.QUERY PLAN
Aggregate (cost=529350.67..529350.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=44
-> Hash Join (cost=112.00..527684.00 rows=666667 width=0) (actual rows=12000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 1988000
Buffers: shared hit=44
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
Buffers: shared hit=22
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
Planning:
Buffers: shared hit=136
Planning Time: 0.243 ms
Execution Time: 486.804 ms | 1.34s |
| 8K | 1.9s | At 8,000 lines PG18's Join Filter removes 7,976,000 pairs and the call takes 1,922.966 ms. The plan is the same Hash Join at every size; only the pairs, and the function calls with them, grow.QUERY PLAN
Aggregate (cost=2117034.67..2117034.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=88
-> Hash Join (cost=224.00..2110368.00 rows=2666667 width=0) (actual rows=24000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 7976000
Buffers: shared hit=88
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
Buffers: shared hit=44
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
Planning:
Buffers: shared hit=136
Planning Time: 0.262 ms
Execution Time: 1922.966 ms | 2.80s |
dateOr99 as a one-line LANGUAGE sql function, inlined: the same plan with the COALESCE in the Join Filter, from 6.8 ms to 409 ms.
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 6.8 ms | At 1,000 sheet lines the plan has no dateor99 in it: PG18 inlined the function, and the Join Filter tests COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year on every pair. It removes 122,000 of them in 6.792 ms.QUERY PLAN
Aggregate (cost=1869.92..1869.93 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=12
-> Hash Join (cost=28.50..1765.75 rows=41667 width=0) (actual rows=3000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 122000
Buffers: shared hit=12
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
Buffers: shared hit=6
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
Planning:
Buffers: shared hit=136
Planning Time: 0.266 ms
Execution Time: 6.792 ms | 0.85s |
| 2K | 26 ms | At 2,000 lines PG18 runs the same Hash Join on product with the COALESCE in the Join Filter, which removes 494,000 pairs, in 26.011 ms.QUERY PLAN
Aggregate (cost=7383.67..7383.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=22
-> Hash Join (cost=56.00..6967.00 rows=166667 width=0) (actual rows=6000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 494000
Buffers: shared hit=22
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
Buffers: shared hit=11
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
Planning:
Buffers: shared hit=136
Planning Time: 0.285 ms
Execution Time: 26.011 ms | 0.86s |
| 4K | 110.2 ms | At 4,000 lines PG18's filter removes 1,988,000 pairs in 110.228 ms. Inlining removed the function call, but the date test still runs on every pair.QUERY PLAN
Aggregate (cost=29350.67..29350.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=44
-> Hash Join (cost=112.00..27684.00 rows=666667 width=0) (actual rows=12000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 1988000
Buffers: shared hit=44
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
Buffers: shared hit=22
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
Planning:
Buffers: shared hit=136
Planning Time: 0.291 ms
Execution Time: 110.228 ms | 0.94s |
| 8K | 408.6 ms | At 8,000 lines PG18's Join Filter removes 7,976,000 pairs and the call takes 408.572 ms, close to four times as long as at half the size.QUERY PLAN
Aggregate (cost=117034.67..117034.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=88
-> Hash Join (cost=224.00..110368.00 rows=2666667 width=0) (actual rows=24000.00 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 7976000
Buffers: shared hit=88
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
Buffers: shared hit=44
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
Planning:
Buffers: shared hit=136
Planning Time: 0.297 ms
Execution Time: 408.572 ms | 1.27s |
The UNION ALL split, two counts summed and no function anywhere: each half searches the (product, expiration_date) index, and the IS NULL half caches its lookup per product. It went from 1.5 ms to 13 ms.
EXPLAIN (ANALYZE, TIMING OFF) SELECT sum(n) AS outliving FROM (SELECT count(*) AS n FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date IS NULL UNION ALL SELECT count(*) FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date > cs.max_year) tCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 1.5 ms | At 1,000 sheet lines PG18 gives each half its own Nested Loop with its condition in the Index Cond on contracts_product_expiration, and the IS NULL half sits behind a Memoize keyed on product, 8 misses and 992 hits. The call takes 1.548 ms.QUERY PLAN
Aggregate (cost=1751.89..1751.90 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=3033 read=4
-> Append (cost=76.68..1751.88 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=3033 read=4
-> Aggregate (cost=76.68..76.69 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=27 read=4
-> Nested Loop (cost=0.29..69.18 rows=3000 width=0) (actual rows=3000.00 loops=1)
Buffers: shared hit=27 read=4
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=3) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Memoize (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=1000)
Cache Key: cs.product
Cache Mode: logical
Hits: 992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=21 read=4
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.28..0.35 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=21 read=4
-> Aggregate (cost=1675.17..1675.18 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=3006
-> Nested Loop (cost=0.28..1571.00 rows=41667 width=0) (actual rows=0.00 loops=1)
Buffers: shared hit=3006
-> Seq Scan on contract_sheet cs_1 (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000.00 loops=1)
Buffers: shared hit=6
-> Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.28..1.14 rows=42 width=7) (actual rows=0.00 loops=1000)
Index Cond: ((product = cs_1.product) AND (expiration_date > cs_1.max_year))
Heap Fetches: 0
Index Searches: 1000
Buffers: shared hit=3000
Planning:
Buffers: shared hit=148
Planning Time: 0.349 ms
Execution Time: 1.548 ms | 0.87s |
| 2K | 3.1 ms | At 2,000 lines PG18's Memoize answers 1,992 of the IS NULL half's lookups from its cache, and the > half makes 2,000 index searches. Those find nothing, since every max_year lies past the last listed date, and the call takes 3.087 ms.QUERY PLAN
Aggregate (cost=6163.88..6163.89 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=6040 read=7
-> Append (cost=149.17..6163.87 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=6040 read=7
-> Aggregate (cost=149.17..149.18 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=29 read=7
-> Nested Loop (cost=0.29..134.17 rows=6000 width=0) (actual rows=6000.00 loops=1)
Buffers: shared hit=29 read=7
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=3) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Memoize (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=2000)
Cache Key: cs.product
Cache Mode: logical
Hits: 1992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=18 read=7
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.28..0.35 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=18 read=7
-> Aggregate (cost=6014.67..6014.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=6011
-> Nested Loop (cost=0.28..5598.00 rows=166667 width=0) (actual rows=0.00 loops=1)
Buffers: shared hit=6011
-> Seq Scan on contract_sheet cs_1 (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000.00 loops=1)
Buffers: shared hit=11
-> Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.28..1.95 rows=83 width=7) (actual rows=0.00 loops=2000)
Index Cond: ((product = cs_1.product) AND (expiration_date > cs_1.max_year))
Heap Fetches: 0
Index Searches: 2000
Buffers: shared hit=6000
Planning:
Buffers: shared hit=148
Planning Time: 0.320 ms
Execution Time: 3.087 ms | 0.83s |
| 4K | 6.4 ms | At 4,000 lines PG18's IS NULL half hits the cache 3,992 times and the > half searches the index 4,000 times. The call takes 6.370 ms, twice as long as at half the size.QUERY PLAN
Aggregate (cost=23235.87..23235.88 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=12060 read=9
-> Append (cost=295.17..23235.86 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=12060 read=9
-> Aggregate (cost=295.17..295.18 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=38 read=9
-> Nested Loop (cost=0.29..265.17 rows=12000 width=0) (actual rows=12000.00 loops=1)
Buffers: shared hit=38 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=3) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Memoize (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=4000)
Cache Key: cs.product
Cache Mode: logical
Hits: 3992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=16 read=9
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.28..0.35 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=16 read=9
-> Aggregate (cost=22940.67..22940.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=12022
-> Nested Loop (cost=0.28..21274.00 rows=666667 width=0) (actual rows=0.00 loops=1)
Buffers: shared hit=12022
-> Seq Scan on contract_sheet cs_1 (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000.00 loops=1)
Buffers: shared hit=22
-> Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.28..3.63 rows=167 width=7) (actual rows=0.00 loops=4000)
Index Cond: ((product = cs_1.product) AND (expiration_date > cs_1.max_year))
Heap Fetches: 0
Index Searches: 4000
Buffers: shared hit=12000
Planning:
Buffers: shared hit=148
Planning Time: 0.359 ms
Execution Time: 6.370 ms | 0.84s |
| 8K | 13.2 ms | At 8,000 lines PG18's > half makes 8,000 index searches and the IS NULL half's cache takes 7,992 hits. The call takes 13.226 ms: one search per sheet line, nothing tested pair by pair.QUERY PLAN
Aggregate (cost=89653.89..89653.90 rows=1 width=32) (actual rows=1.00 loops=1)
Buffers: shared hit=24104 read=9
-> Append (cost=587.18..89653.88 rows=2 width=8) (actual rows=2.00 loops=1)
Buffers: shared hit=24104 read=9
-> Aggregate (cost=587.18..587.19 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=60 read=9
-> Nested Loop (cost=0.29..527.18 rows=24000 width=0) (actual rows=24000.00 loops=1)
Buffers: shared hit=60 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=3) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Memoize (cost=0.29..0.36 rows=3 width=3) (actual rows=3.00 loops=8000)
Cache Key: cs.product
Cache Mode: logical
Hits: 7992 Misses: 8 Evictions: 0 Overflows: 0 Memory Usage: 2kB
Buffers: shared hit=16 read=9
-> Index Only Scan using contracts_product_expiration on contracts c (cost=0.28..0.35 rows=3 width=3) (actual rows=3.00 loops=8)
Index Cond: ((product = cs.product) AND (expiration_date IS NULL))
Heap Fetches: 0
Index Searches: 8
Buffers: shared hit=16 read=9
-> Aggregate (cost=89066.67..89066.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24044
-> Nested Loop (cost=0.28..82400.00 rows=2666667 width=0) (actual rows=0.00 loops=1)
Buffers: shared hit=24044
-> Seq Scan on contract_sheet cs_1 (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Index Only Scan using contracts_product_expiration on contracts c_1 (cost=0.28..6.95 rows=333 width=7) (actual rows=0.00 loops=8000)
Index Cond: ((product = cs_1.product) AND (expiration_date > cs_1.max_year))
Heap Fetches: 0
Index Searches: 8000
Buffers: shared hit=24000
Planning:
Buffers: shared hit=148
Planning Time: 0.359 ms
Execution Time: 13.226 ms | 0.88s |
At ten and a hundred times the lines. A later call ran the index on the function's result at 8,000, 80,000 and 800,000 lines, with the main run's query and tables: 13 ms, 137 ms and 1.6 seconds, one index search per sheet line at every size.
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql IMMUTABLE AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
CREATE INDEX contracts_product_expiration99 ON contracts (product, dateOr99(expiration_date));
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 8K | 13.4 ms | At 8,000 sheet lines PG18 runs the same Nested Loop as in the main run: 8,000 searches of contracts_product_expiration99, each returning the 3 contracts that never expire, in 13.400 ms.QUERY PLAN
Aggregate (cost=89242.67..89242.68 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24035 read=9
-> Nested Loop (cost=0.28..82576.00 rows=2666667 width=0) (actual rows=24000.00 loops=1)
Buffers: shared hit=24035 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000.00 loops=1)
Buffers: shared hit=44
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..6.98 rows=333 width=7) (actual rows=3.00 loops=8000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 8000
Buffers: shared hit=23991 read=9
Planning:
Buffers: shared hit=143
Planning Time: 0.292 ms
Execution Time: 13.400 ms | 0.97s |
| 80K | 136.6 ms | At 80,000 lines PG18 keeps the plan: 80,000 index searches, one per sheet line, each returning 3 contracts, and the call takes 136.601 ms, about ten times as long for ten times the lines.QUERY PLAN
Aggregate (cost=8693050.04..8693050.05 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=240424 read=9
-> Nested Loop (cost=0.29..8026449.00 rows=266640417 width=0) (actual rows=240000.00 loops=1)
Buffers: shared hit=240424 read=9
-> Seq Scan on contract_sheet cs (cost=0.00..1233.00 rows=80000 width=7) (actual rows=80000.00 loops=1)
Buffers: shared hit=433
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.29..66.99 rows=3333 width=7) (actual rows=3.00 loops=80000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 80000
Buffers: shared hit=239991 read=9
Planning:
Buffers: shared hit=143
Planning Time: 0.317 ms
Execution Time: 136.601 ms | 1.39s |
| 800K | 1.6s | At 800,000 lines PG18 still searches the index once per sheet line, 800,000 times, and the call takes 1,571.637 ms. The searches' buffer hits come to 3,199,983, about four per search.QUERY PLAN
Aggregate (cost=867027183.28..867027183.29 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=3204308 read=17
-> Nested Loop (cost=0.42..800370409.00 rows=26662709713 width=0) (actual rows=2400000.00 loops=1)
Buffers: shared hit=3204308 read=17
-> Seq Scan on contract_sheet cs (cost=0.00..12325.00 rows=800000 width=7) (actual rows=800000.00 loops=1)
Buffers: shared hit=4325
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.42..667.12 rows=33333 width=7) (actual rows=3.00 loops=800000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Index Searches: 800000
Buffers: shared hit=3199983 read=17
Planning:
Buffers: shared hit=143
Planning Time: 0.303 ms
Execution Time: 1571.637 ms | 5.64s |
Source: the main run, 20261119_212614_udf-post-dev, seq 17 to 19; the last card, 20261120_161840_pg-scale-dev, seq 3.
Appendix: PG17, plan for plan
PG17 (PostgreSQL 17.12) ran four of the versions in the main run, under EXPLAIN (ANALYZE, TIMING OFF), one execution per size. Every plan matched PG18's, node for node, and every time came within 11% of PG18's at the same size. At 8,000 lines:
| Version of the join | PG17, 8,000 lines |
|---|---|
dateOr99 as PL/pgSQL | 1.9 s |
dateOr99 as a SQL function, inlined | 397 ms |
IS NULL OR > written by hand | 415 ms |
| IMMUTABLE SQL function with an index on its result | 12 ms |
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 29.9 ms | At 1,000 sheet lines PG17 hashes the contracts on product and calls dateor99(c.expiration_date) in the Join Filter on every pair. It removes 122,000 of them in 29.912 ms.QUERY PLAN
Aggregate (cost=33119.92..33119.93 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=28.50..33015.75 rows=41667 width=0) (actual rows=3000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 122000
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Planning Time: 0.259 ms
Execution Time: 29.912 ms | 0.30s |
| 2K | 118.3 ms | At 2,000 lines PG17's Join Filter removes 494,000 pairs and the call takes 118.339 ms, about four times as long as at half the size.QUERY PLAN
Aggregate (cost=132383.67..132383.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=56.00..131967.00 rows=166667 width=0) (actual rows=6000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 494000
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Planning Time: 0.238 ms
Execution Time: 118.339 ms | 0.38s |
| 4K | 467.6 ms | At 4,000 lines PG17's Hash Join removes 1,988,000 pairs, with a PL/pgSQL call for every pair it tests, in 467.583 ms.QUERY PLAN
Aggregate (cost=529350.67..529350.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=112.00..527684.00 rows=666667 width=0) (actual rows=12000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 1988000
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Planning Time: 0.220 ms
Execution Time: 467.583 ms | 0.75s |
| 8K | 1.9s | At 8,000 lines PG17 removes 7,976,000 pairs in the Join Filter and takes 1,857.687 ms, four times as long as at half the size.QUERY PLAN
Aggregate (cost=2117034.67..2117034.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=224.00..2110368.00 rows=2666667 width=0) (actual rows=24000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (dateor99(c.expiration_date) > cs.max_year)
Rows Removed by Join Filter: 7976000
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Planning Time: 0.247 ms
Execution Time: 1857.687 ms | 2.17s |
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 6.5 ms | At 1,000 sheet lines PG17 inlines the function, so the Join Filter tests COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year on every pair. It removes 122,000 pairs in 6.460 ms.QUERY PLAN
Aggregate (cost=1869.92..1869.93 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=28.50..1765.75 rows=41667 width=0) (actual rows=3000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 122000
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Planning Time: 0.225 ms
Execution Time: 6.460 ms | 0.25s |
| 2K | 25.2 ms | At 2,000 lines PG17's Hash Join on product removes 494,000 pairs in the Join Filter and takes 25.227 ms.QUERY PLAN
Aggregate (cost=7383.67..7383.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=56.00..6967.00 rows=166667 width=0) (actual rows=6000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 494000
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Planning Time: 0.256 ms
Execution Time: 25.227 ms | 0.29s |
| 4K | 101.3 ms | At 4,000 lines PG17's Join Filter removes 1,988,000 pairs and the call takes 101.325 ms, with no function call left anywhere in the plan.QUERY PLAN
Aggregate (cost=29350.67..29350.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=112.00..27684.00 rows=666667 width=0) (actual rows=12000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 1988000
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Planning Time: 0.234 ms
Execution Time: 101.325 ms | 0.37s |
| 8K | 396.7 ms | At 8,000 lines PG17's filter removes 7,976,000 pairs and the call takes 396.726 ms; the date test still runs on every pair.QUERY PLAN
Aggregate (cost=117034.67..117034.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=224.00..110368.00 rows=2666667 width=0) (actual rows=24000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: (COALESCE(c.expiration_date, '9999-01-01'::date) > cs.max_year)
Rows Removed by Join Filter: 7976000
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Planning Time: 0.255 ms
Execution Time: 396.726 ms | 0.68s |
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND (c.expiration_date IS NULL OR c.expiration_date > cs.max_year)CREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE plpgsql AS $$ BEGIN RETURN COALESCE(d, DATE '9999-01-01'); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 6.6 ms | At 1,000 sheet lines PG17 hashes on product and puts the whole IS NULL OR > in the Join Filter, which removes 122,000 pairs in 6.629 ms.QUERY PLAN
Aggregate (cost=1874.92..1874.93 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=28.50..1765.75 rows=43667 width=0) (actual rows=3000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 122000
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
-> Hash (cost=16.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 47kB
-> Seq Scan on contracts c (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
Planning Time: 0.232 ms
Execution Time: 6.629 ms | 0.26s |
| 2K | 27 ms | At 2,000 lines the OR in PG17's Join Filter removes 494,000 pairs and the call takes 26.961 ms, about four times as long as at half the size.QUERY PLAN
Aggregate (cost=7393.67..7393.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=56.00..6967.00 rows=170667 width=0) (actual rows=6000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 494000
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
-> Hash (cost=31.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Buckets: 2048 Batches: 1 Memory Usage: 95kB
-> Seq Scan on contracts c (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
Planning Time: 0.214 ms
Execution Time: 26.961 ms | 0.27s |
| 4K | 103.2 ms | At 4,000 lines PG17's Join Filter removes 1,988,000 pairs, and the call takes 103.174 ms.QUERY PLAN
Aggregate (cost=29370.67..29370.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=112.00..27684.00 rows=674667 width=0) (actual rows=12000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 1988000
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
-> Hash (cost=62.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Buckets: 4096 Batches: 1 Memory Usage: 189kB
-> Seq Scan on contracts c (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
Planning Time: 0.262 ms
Execution Time: 103.174 ms | 0.43s |
| 8K | 414.9 ms | At 8,000 lines the OR removes 7,976,000 pairs and the call takes 414.908 ms; PG17 reads contracts with a Seq Scan and tests the condition on every pair.QUERY PLAN
Aggregate (cost=117074.67..117074.68 rows=1 width=8) (actual rows=1 loops=1)
-> Hash Join (cost=224.00..110368.00 rows=2682667 width=0) (actual rows=24000 loops=1)
Hash Cond: (cs.product = c.product)
Join Filter: ((c.expiration_date IS NULL) OR (c.expiration_date > cs.max_year))
Rows Removed by Join Filter: 7976000
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
-> Hash (cost=124.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Buckets: 8192 Batches: 1 Memory Usage: 377kB
-> Seq Scan on contracts c (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
Planning Time: 0.285 ms
Execution Time: 414.908 ms | 0.77s |
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearCREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql IMMUTABLE AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
CREATE INDEX contracts_product_expiration99 ON contracts (product, dateOr99(expiration_date));
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 1.5 ms | At 1,000 sheet lines PG17 searches contracts_product_expiration99 once per sheet line with the COALESCE inside the Index Cond, 3 rows per search, in 1.487 ms.QUERY PLAN
Aggregate (cost=1699.17..1699.18 rows=1 width=8) (actual rows=1 loops=1)
-> Nested Loop (cost=0.28..1595.00 rows=41667 width=0) (actual rows=3000 loops=1)
-> Seq Scan on contract_sheet cs (cost=0.00..16.00 rows=1000 width=7) (actual rows=1000 loops=1)
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..1.16 rows=42 width=7) (actual rows=3 loops=1000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Planning Time: 0.308 ms
Execution Time: 1.487 ms | 0.28s |
| 2K | 3.1 ms | At 2,000 lines PG17's Nested Loop runs the index scan 2,000 times and takes 3.072 ms, about twice as long as at half the size.QUERY PLAN
Aggregate (cost=6058.67..6058.68 rows=1 width=8) (actual rows=1 loops=1)
-> Nested Loop (cost=0.28..5642.00 rows=166667 width=0) (actual rows=6000 loops=1)
-> Seq Scan on contract_sheet cs (cost=0.00..31.00 rows=2000 width=7) (actual rows=2000 loops=1)
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..1.98 rows=83 width=7) (actual rows=3 loops=2000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Planning Time: 0.331 ms
Execution Time: 3.072 ms | 0.27s |
| 4K | 6.1 ms | At 4,000 lines PG17 runs the index scan 4,000 times and the call takes 6.059 ms; the time still follows the sheet lines, not the pairs.QUERY PLAN
Aggregate (cost=23028.67..23028.68 rows=1 width=8) (actual rows=1 loops=1)
-> Nested Loop (cost=0.28..21362.00 rows=666667 width=0) (actual rows=12000 loops=1)
-> Seq Scan on contract_sheet cs (cost=0.00..62.00 rows=4000 width=7) (actual rows=4000 loops=1)
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..3.66 rows=167 width=7) (actual rows=3 loops=4000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Planning Time: 0.318 ms
Execution Time: 6.059 ms | 0.28s |
| 8K | 12.1 ms | At 8,000 lines PG17 makes one index search per sheet line, 8,000 in all, and takes 12.126 ms.QUERY PLAN
Aggregate (cost=89242.67..89242.68 rows=1 width=8) (actual rows=1 loops=1)
-> Nested Loop (cost=0.28..82576.00 rows=2666667 width=0) (actual rows=24000 loops=1)
-> Seq Scan on contract_sheet cs (cost=0.00..124.00 rows=8000 width=7) (actual rows=8000 loops=1)
-> Index Scan using contracts_product_expiration99 on contracts c (cost=0.28..6.98 rows=333 width=7) (actual rows=3 loops=8000)
Index Cond: ((product = cs.product) AND (COALESCE(expiration_date, '9999-01-01'::date) > cs.max_year))
Planning Time: 0.321 ms
Execution Time: 12.126 ms | 1.26s |
Source: the main run, 20261119_212614_udf-post-dev, seq 22 to 25.
Appendix: MySQL's other calls
All four ran in the main run on MySQL 8.0.39 (Aurora 3.08.0), under EXPLAIN ANALYZE, one execution per size.
The times in this post are each plan's root line, rounded. The cards' TIME column shows ExoBench's own measure of the call instead, which can differ a little from the root line.
The stored function at its default, NOT DETERMINISTIC: a lookup by product, and the function in a filter on every contract that comes back, from 302 ms to 16 seconds across the four sizes.
EXPLAIN ANALYZE SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearSET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL, INDEX contracts_product_expiration (product, expiration_date));
INSERT INTO contracts (id, product, expiration_date)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN i <= 24 THEN NULL ELSE DATE_ADD('2026-01-02', INTERVAL (i - 1) DIV 8 DAY) END
FROM s;
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'), DATE_ADD('2026-01-02', INTERVAL (${N} DIV 8 + i) DAY)
FROM s;
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE NO SQL RETURN COALESCE(d, '9999-01-01');
ANALYZE TABLE contracts, contract_sheet;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 305 ms | At 1,000 sheet lines MySQL looks up each line's product in contracts_product_expiration and runs dateOr99(c.expiration_date) > cs.max_year as a Filter on each of the 125 contracts it gets back. The root line reports 302 ms.EXPLAIN
-> Aggregate: count(0) (cost=25411 rows=1) (actual time=302..302 rows=1 loops=1)
-> Nested loop inner join (cost=12911 rows=125000) (actual time=0.0618..301 rows=3000 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0164..0.301 rows=1000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.323 rows=125) (actual time=0.017..0.301 rows=3 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.323 rows=125) (actual time=0.0147..0.0313 rows=125 loops=1000)
| 0.66s |
| 2K | 1s | At 2,000 lines each MySQL lookup returns 250 contracts, the stored function runs on every one, and the Filter keeps 3. The root line reports 1,018 ms.EXPLAIN
-> Aggregate: count(0) (cost=100944 rows=1) (actual time=1018..1018 rows=1 loops=1)
-> Nested loop inner join (cost=50944 rows=500000) (actual time=0.0552..1017 rows=6000 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.0144..0.471 rows=2000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.384 rows=250) (actual time=0.0166..0.508 rows=3 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.384 rows=250) (actual time=0.0144..0.0562 rows=250 loops=2000)
| 1.33s |
| 4K | 4.1s | At 4,000 lines MySQL's Filter calls the function on 500 contracts per sheet line, and the root line reports 4,146 ms, about four times as long as at half the size.EXPLAIN
-> Aggregate: count(0) (cost=402375 rows=1) (actual time=4146..4146 rows=1 loops=1)
-> Nested loop inner join (cost=202375 rows=2e+6) (actual time=0.0563..4145 rows=12000 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.0153..1.11 rows=4000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.506 rows=500) (actual time=0.0159..1.04 rows=3 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.506 rows=500) (actual time=0.0137..0.109 rows=500 loops=4000)
| 4.49s |
| 8K | 16.5s | At 8,000 lines MySQL's Filter runs the stored function on all 1,000 contracts of a line's product, for every sheet line. The root line reports 16,459 ms.EXPLAIN
-> Aggregate: count(0) (cost=1.61e+6 rows=1) (actual time=16459..16459 rows=1 loops=1)
-> Nested loop inner join (cost=806699 rows=8e+6) (actual time=0.0545..16457 rows=24000 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.0146..2.13 rows=8000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.749 rows=1000) (actual time=0.016..2.06 rows=3 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.749 rows=1000) (actual time=0.0138..0.219 rows=1000 loops=8000)
| 16.84s |
Declared DETERMINISTIC, the same plan, from 256 ms to 16 seconds.
EXPLAIN ANALYZE SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND dateOr99(c.expiration_date) > cs.max_yearSET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL, INDEX contracts_product_expiration (product, expiration_date));
INSERT INTO contracts (id, product, expiration_date)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN i <= 24 THEN NULL ELSE DATE_ADD('2026-01-02', INTERVAL (i - 1) DIV 8 DAY) END
FROM s;
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'), DATE_ADD('2026-01-02', INTERVAL (${N} DIV 8 + i) DAY)
FROM s;
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE DETERMINISTIC NO SQL RETURN COALESCE(d, '9999-01-01');
ANALYZE TABLE contracts, contract_sheet;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 259 ms | At 1,000 sheet lines, declared DETERMINISTIC, the function still runs in MySQL's Filter on all 125 contracts each product lookup returns. The root line reports 256 ms.EXPLAIN
-> Aggregate: count(0) (cost=25411 rows=1) (actual time=256..256 rows=1 loops=1)
-> Nested loop inner join (cost=12911 rows=125000) (actual time=0.0519..256 rows=3000 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0149..0.2 rows=1000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.323 rows=125) (actual time=0.0153..0.255 rows=3 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.323 rows=125) (actual time=0.0131..0.0284 rows=125 loops=1000)
| 0.49s |
| 2K | 1s | At 2,000 lines each MySQL lookup returns 250 contracts, all of them through the function, and the Filter keeps 3. The root line reports 1,010 ms.EXPLAIN
-> Aggregate: count(0) (cost=100944 rows=1) (actual time=1010..1010 rows=1 loops=1)
-> Nested loop inner join (cost=50944 rows=500000) (actual time=0.0561..1010 rows=6000 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.0146..0.415 rows=2000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.384 rows=250) (actual time=0.0155..0.504 rows=3 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.384 rows=250) (actual time=0.0133..0.0548 rows=250 loops=2000)
| 1.28s |
| 4K | 4.1s | At 4,000 lines MySQL's root line reports 4,076 ms, about four times as long as at half the size: DETERMINISTIC can't save calls when the argument changes on every pair.EXPLAIN
-> Aggregate: count(0) (cost=402375 rows=1) (actual time=4076..4076 rows=1 loops=1)
-> Nested loop inner join (cost=202375 rows=2e+6) (actual time=0.0563..4075 rows=12000 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.0172..0.961 rows=4000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.506 rows=500) (actual time=0.0158..1.02 rows=3 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.506 rows=500) (actual time=0.0136..0.108 rows=500 loops=4000)
| 4.39s |
| 8K | 16.1s | At 8,000 lines MySQL runs the DETERMINISTIC function on all 1,000 contracts per sheet line, and the root line reports 16,074 ms.EXPLAIN
-> Aggregate: count(0) (cost=1.61e+6 rows=1) (actual time=16074..16074 rows=1 loops=1)
-> Nested loop inner join (cost=806699 rows=8e+6) (actual time=0.0668..16072 rows=24000 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.0155..1.9 rows=8000 loops=1)
-> Filter: (dateOr99(c.expiration_date) > cs.max_year) (cost=0.749 rows=1000) (actual time=0.0157..2.01 rows=3 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.749 rows=1000) (actual time=0.0135..0.213 rows=1000 loops=8000)
| 16.44s |
The COALESCE written out in the join, with a functional index on the product and the same COALESCE, which the plan never uses: from 36 ms to 2.1 seconds.
EXPLAIN ANALYZE SELECT COUNT(*) AS outliving FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND COALESCE(c.expiration_date, DATE '9999-01-01') > cs.max_yearSET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL, INDEX contracts_product_expiration (product, expiration_date));
INSERT INTO contracts (id, product, expiration_date)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN i <= 24 THEN NULL ELSE DATE_ADD('2026-01-02', INTERVAL (i - 1) DIV 8 DAY) END
FROM s;
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'), DATE_ADD('2026-01-02', INTERVAL (${N} DIV 8 + i) DAY)
FROM s;
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE NO SQL RETURN COALESCE(d, '9999-01-01');
CREATE INDEX contracts_product_expiration99 ON contracts (product, (COALESCE(expiration_date, DATE '9999-01-01')));
ANALYZE TABLE contracts, contract_sheet;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 39 ms | At 1,000 sheet lines MySQL doesn't touch the functional index: it looks product up in contracts_product_expiration and checks coalesce(c.expiration_date,DATE'9999-01-01') > cs.max_year in a Filter on 125 contracts per line. The root line reports 35.5 ms.EXPLAIN
-> Aggregate: count(0) (cost=25411 rows=1) (actual time=35.5..35.5 rows=1 loops=1)
-> Nested loop inner join (cost=12911 rows=125000) (actual time=0.0424..35.3 rows=3000 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0181..0.202 rows=1000 loops=1)
-> Filter: (coalesce(c.expiration_date,DATE'9999-01-01') > cs.max_year) (cost=0.323 rows=125) (actual time=0.0129..0.0348 rows=3 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.323 rows=125) (actual time=0.0128..0.0272 rows=125 loops=1000)
| 0.32s |
| 2K | 139 ms | At 2,000 lines MySQL runs the same lookup on product and the same Filter, now on 250 contracts per line, and the root line reports 137 ms.EXPLAIN
-> Aggregate: count(0) (cost=100944 rows=1) (actual time=137..137 rows=1 loops=1)
-> Nested loop inner join (cost=50944 rows=500000) (actual time=0.039..136 rows=6000 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.0161..0.382 rows=2000 loops=1)
-> Filter: (coalesce(c.expiration_date,DATE'9999-01-01') > cs.max_year) (cost=0.384 rows=250) (actual time=0.0131..0.0676 rows=3 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.384 rows=250) (actual time=0.0129..0.0526 rows=250 loops=2000)
| 0.43s |
| 4K | 537 ms | At 4,000 lines MySQL's Filter checks the COALESCE on 500 contracts per sheet line; the root line reports 535 ms, close to four times as long as at half the size.EXPLAIN
-> Aggregate: count(0) (cost=402375 rows=1) (actual time=535..535 rows=1 loops=1)
-> Nested loop inner join (cost=202375 rows=2e+6) (actual time=0.0422..534 rows=12000 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.018..0.748 rows=4000 loops=1)
-> Filter: (coalesce(c.expiration_date,DATE'9999-01-01') > cs.max_year) (cost=0.506 rows=500) (actual time=0.0132..0.133 rows=3 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.506 rows=500) (actual time=0.013..0.103 rows=500 loops=4000)
| 0.89s |
| 8K | 2.1s | At 8,000 lines MySQL's Filter checks the COALESCE on 1,000 contracts per sheet line and the root line reports 2,117 ms, while the index built on that very expression, contracts_product_expiration99, never appears in the plan.EXPLAIN
-> Aggregate: count(0) (cost=1.61e+6 rows=1) (actual time=2117..2117 rows=1 loops=1)
-> Nested loop inner join (cost=806699 rows=8e+6) (actual time=0.0445..2116 rows=24000 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.0195..1.51 rows=8000 loops=1)
-> Filter: (coalesce(c.expiration_date,DATE'9999-01-01') > cs.max_year) (cost=0.749 rows=1000) (actual time=0.0132..0.264 rows=3 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.749 rows=1000) (actual time=0.013..0.205 rows=1000 loops=8000)
| 2.58s |
The UNION ALL split, the IS NULL half looked up on product and NULL and the > half looked up by product and filtered: from 37 ms to 2.1 seconds.
EXPLAIN ANALYZE SELECT SUM(n) AS outliving FROM (SELECT COUNT(*) AS n FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date IS NULL UNION ALL SELECT COUNT(*) FROM contract_sheet cs JOIN contracts c ON c.product = cs.product AND c.expiration_date > cs.max_year) tSET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE contracts (id INT PRIMARY KEY, product CHAR(2) NOT NULL, expiration_date DATE NULL, INDEX contracts_product_expiration (product, expiration_date));
INSERT INTO contracts (id, product, expiration_date)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'),
CASE WHEN i <= 24 THEN NULL ELSE DATE_ADD('2026-01-02', INTERVAL (i - 1) DIV 8 DAY) END
FROM s;
CREATE TABLE contract_sheet (line_id INT PRIMARY KEY, product CHAR(2) NOT NULL, max_year DATE NOT NULL);
INSERT INTO contract_sheet (line_id, product, max_year)
WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${N})
SELECT i, ELT(i % 8 + 1, 'CL', 'BZ', 'NG', 'HO', 'RB', 'QM', 'QG', 'HH'), DATE_ADD('2026-01-02', INTERVAL (${N} DIV 8 + i) DAY)
FROM s;
CREATE FUNCTION dateOr99(d DATE) RETURNS DATE NO SQL RETURN COALESCE(d, '9999-01-01');
ANALYZE TABLE contracts, contract_sheet;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 1K | 40 ms | At 1,000 sheet lines MySQL runs the IS NULL half as an index lookup on (product=cs.product, expiration_date=NULL) that returns the 3 contracts per line, while the > half looks up product alone and filters 125 contracts per line. The root line reports 37.2 ms.EXPLAIN
-> Aggregate: sum(t.n) (cost=17635..17635 rows=1) (actual time=37.2..37.2 rows=1 loops=1)
-> Table scan on t (cost=17633..17635 rows=2) (actual time=37.2..37.2 rows=2 loops=1)
-> Union all materialize (cost=17632..17632 rows=2) (actual time=37.1..37.1 rows=2 loops=1)
-> Aggregate: count(0) (cost=554 rows=1) (actual time=3.38..3.38 rows=1 loops=1)
-> Nested loop inner join (cost=453 rows=1016) (actual time=0.0267..3.22 rows=3000 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0156..0.182 rows=1000 loops=1)
-> Filter: (c.expiration_date is null) (cost=0.25 rows=1.02) (actual time=0.00192..0.00273 rows=3 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product, expiration_date=NULL) (cost=0.25 rows=1.02) (actual time=0.00179..0.0024 rows=3 loops=1000)
-> Aggregate: count(0) (cost=17078 rows=1) (actual time=33.8..33.8 rows=1 loops=1)
-> Nested loop inner join (cost=12911 rows=41662) (actual time=33.8..33.8 rows=0 loops=1)
-> Table scan on cs (cost=101 rows=1000) (actual time=0.0102..0.183 rows=1000 loops=1)
-> Filter: (c.expiration_date > cs.max_year) (cost=0.315 rows=41.7) (actual time=0.0335..0.0335 rows=0 loops=1000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.315 rows=125) (actual time=0.0128..0.0269 rows=125 loops=1000)
| 0.30s |
| 2K | 142 ms | At 2,000 lines MySQL's > half checks 250 contracts per line in its Filter and keeps none of them, and the root line reports 139 ms.EXPLAIN
-> Aggregate: sum(t.n) (cost=68717..68717 rows=1) (actual time=139..139 rows=1 loops=1)
-> Table scan on t (cost=68715..68717 rows=2) (actual time=139..139 rows=2 loops=1)
-> Union all materialize (cost=68714..68714 rows=2) (actual time=139..139 rows=2 loops=1)
-> Aggregate: count(0) (cost=1105 rows=1) (actual time=7.06..7.06 rows=1 loops=1)
-> Nested loop inner join (cost=903 rows=2016) (actual time=0.0261..6.75 rows=6000 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.015..0.342 rows=2000 loops=1)
-> Filter: (c.expiration_date is null) (cost=0.25 rows=1.01) (actual time=0.00208..0.00289 rows=3 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product, expiration_date=NULL) (cost=0.25 rows=1.01) (actual time=0.00193..0.00253 rows=3 loops=2000)
-> Aggregate: count(0) (cost=67609 rows=1) (actual time=132..132 rows=1 loops=1)
-> Nested loop inner join (cost=50944 rows=166650) (actual time=132..132 rows=0 loops=1)
-> Table scan on cs (cost=202 rows=2000) (actual time=0.0107..0.393 rows=2000 loops=1)
-> Filter: (c.expiration_date > cs.max_year) (cost=0.376 rows=83.3) (actual time=0.0656..0.0656 rows=0 loops=2000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.376 rows=250) (actual time=0.0131..0.0525 rows=250 loops=2000)
| 0.40s |
| 4K | 532 ms | At 4,000 lines the IS NULL half's Aggregate line in MySQL's plan reports 14.2 ms and the > half's 514 ms. The root line reports 528 ms.EXPLAIN
-> Aggregate: sum(t.n) (cost=271243..271243 rows=1) (actual time=528..528 rows=1 loops=1)
-> Table scan on t (cost=271242..271243 rows=2) (actual time=528..528 rows=2 loops=1)
-> Union all materialize (cost=271241..271241 rows=2) (actual time=528..528 rows=2 loops=1)
-> Aggregate: count(0) (cost=2205 rows=1) (actual time=14.2..14.2 rows=1 loops=1)
-> Nested loop inner join (cost=1804 rows=4016) (actual time=0.0278..13.6 rows=12000 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.0166..0.693 rows=4000 loops=1)
-> Filter: (c.expiration_date is null) (cost=0.25 rows=1) (actual time=0.00212..0.00292 rows=3 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product, expiration_date=NULL) (cost=0.25 rows=1) (actual time=0.00198..0.00259 rows=3 loops=4000)
-> Aggregate: count(0) (cost=269035 rows=1) (actual time=514..514 rows=1 loops=1)
-> Nested loop inner join (cost=202375 rows=666600) (actual time=514..514 rows=0 loops=1)
-> Table scan on cs (cost=402 rows=4000) (actual time=0.0118..0.751 rows=4000 loops=1)
-> Filter: (c.expiration_date > cs.max_year) (cost=0.497 rows=167) (actual time=0.128..0.128 rows=0 loops=4000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.497 rows=500) (actual time=0.013..0.102 rows=500 loops=4000)
| 0.87s |
| 8K | 2.1s | At 8,000 lines the IS NULL half's Aggregate line in MySQL's plan reports 28.8 ms and the > half's 2,047 ms. Nearly all of the root line's 2,075 ms is the > comparison, still made on every contract of a line's product.EXPLAIN
-> Aggregate: sum(t.n) (cost=1.08e+6..1.08e+6 rows=1) (actual time=2075..2075 rows=1 loops=1)
-> Table scan on t (cost=1.08e+6..1.08e+6 rows=2) (actual time=2075..2075 rows=2 loops=1)
-> Union all materialize (cost=1.08e+6..1.08e+6 rows=2) (actual time=2075..2075 rows=2 loops=1)
-> Aggregate: count(0) (cost=4407 rows=1) (actual time=28.8..28.8 rows=1 loops=1)
-> Nested loop inner join (cost=3606 rows=8016) (actual time=0.0275..27.5 rows=24000 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.0156..1.36 rows=8000 loops=1)
-> Filter: (c.expiration_date is null) (cost=0.25 rows=1) (actual time=0.00213..0.00296 rows=3 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product, expiration_date=NULL) (cost=0.25 rows=1) (actual time=0.002..0.00262 rows=3 loops=8000)
-> Aggregate: count(0) (cost=1.07e+6 rows=1) (actual time=2047..2047 rows=1 loops=1)
-> Nested loop inner join (cost=806699 rows=2.67e+6) (actual time=2047..2047 rows=0 loops=1)
-> Table scan on cs (cost=804 rows=8000) (actual time=0.0112..1.49 rows=8000 loops=1)
-> Filter: (c.expiration_date > cs.max_year) (cost=0.741 rows=333) (actual time=0.256..0.256 rows=0 loops=8000)
-> Covering index lookup on c using contracts_product_expiration (product=cs.product) (cost=0.741 rows=1000) (actual time=0.0131..0.203 rows=1000 loops=8000)
| 2.44s |
Source: the main run, 20261119_212614_udf-post-dev, seq 12, 13, 15 and 16.
Appendix: The equality join
Every call here joins two tables of M rows, crm and billing, on a normalized email. PG18's template, as the main run sent it:
CREATE TABLE crm (id int PRIMARY KEY, email text NOT NULL);
CREATE TABLE billing (id int PRIMARY KEY, email text NOT NULL);
INSERT INTO crm SELECT i, 'user' || i || '@example.com' FROM generate_series(1, ${M}) i;
INSERT INTO billing SELECT i, ' USER' || i || '@Example.COM ' FROM generate_series(1, ${M}) i;
CREATE FUNCTION norm_email(e text) RETURNS text LANGUAGE plpgsql AS $$ BEGIN RETURN lower(trim(e)); END $$;
VACUUM ANALYZE;The two lists match one to one after lower(trim()), so each call should count M matches, and every call did. The main run ran 500, 1,000 and 2,000 rows a side.
PG18. Written inline, a merge join on lower(TRIM(...)), from 0.5 ms to 1.9 ms:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS matched FROM crm a JOIN billing b ON lower(trim(a.email)) = lower(trim(b.email))CREATE TABLE crm (id int PRIMARY KEY, email text NOT NULL);
CREATE TABLE billing (id int PRIMARY KEY, email text NOT NULL);
INSERT INTO crm SELECT i, 'user' || i || '@example.com' FROM generate_series(1, ${M}) i;
INSERT INTO billing SELECT i, ' USER' || i || '@Example.COM ' FROM generate_series(1, ${M}) i;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 0.5 ms | At 500 rows a side PG18 sorts both lists on lower(TRIM(BOTH FROM email)) and merge-joins them on the two expressions, in 0.515 ms.QUERY PLAN
Aggregate (cost=104.70..104.71 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=8
-> Merge Join (cost=62.83..101.58 rows=1250 width=0) (actual rows=500.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=8
-> Sort (cost=31.41..32.66 rows=500 width=19) (actual rows=500.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 52kB
Buffers: shared hit=4
-> Seq Scan on crm a (cost=0.00..9.00 rows=500 width=19) (actual rows=500.00 loops=1)
Buffers: shared hit=4
-> Sort (cost=31.41..32.66 rows=500 width=22) (actual rows=500.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 56kB
Buffers: shared hit=4
-> Seq Scan on billing b (cost=0.00..9.00 rows=500 width=22) (actual rows=500.00 loops=1)
Buffers: shared hit=4
Planning:
Buffers: shared hit=84
Planning Time: 0.232 ms
Execution Time: 0.515 ms | 0.73s |
| 1K | 0.9 ms | At 1,000 rows a side PG18 runs the same Merge Join on the two expressions, 1,000 matches, in 0.947 ms.QUERY PLAN
Aggregate (cost=287.16..287.17 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=15
-> Merge Join (cost=134.66..274.66 rows=5000 width=0) (actual rows=1000.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=15
-> Sort (cost=66.83..69.33 rows=1000 width=19) (actual rows=1000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 79kB
Buffers: shared hit=7
-> Seq Scan on crm a (cost=0.00..17.00 rows=1000 width=19) (actual rows=1000.00 loops=1)
Buffers: shared hit=7
-> Sort (cost=67.83..70.33 rows=1000 width=22) (actual rows=1000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 87kB
Buffers: shared hit=8
-> Seq Scan on billing b (cost=0.00..18.00 rows=1000 width=22) (actual rows=1000.00 loops=1)
Buffers: shared hit=8
Planning:
Buffers: shared hit=84
Planning Time: 0.226 ms
Execution Time: 0.947 ms | 0.75s |
| 2K | 1.9 ms | At 2,000 rows a side PG18's sorts and merge take 1.856 ms, about twice as long as at half the rows: the cost of sorting rows, not of testing pairs.QUERY PLAN
Aggregate (cost=868.32..868.33 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=29
-> Merge Join (cost=288.32..818.32 rows=20000 width=0) (actual rows=2000.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=29
-> Sort (cost=143.66..148.66 rows=2000 width=20) (actual rows=2000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 166kB
Buffers: shared hit=14
-> Seq Scan on crm a (cost=0.00..34.00 rows=2000 width=20) (actual rows=2000.00 loops=1)
Buffers: shared hit=14
-> Sort (cost=144.66..149.66 rows=2000 width=23) (actual rows=2000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 173kB
Buffers: shared hit=15
-> Seq Scan on billing b (cost=0.00..35.00 rows=2000 width=23) (actual rows=2000.00 loops=1)
Buffers: shared hit=15
Planning:
Buffers: shared hit=84
Planning Time: 0.260 ms
Execution Time: 1.856 ms | 0.76s |
The LANGUAGE sql version of norm_email(), inlined into the same merge join, from 0.5 ms to 1.9 ms:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS matched FROM crm a JOIN billing b ON norm_email(a.email) = norm_email(b.email)CREATE TABLE crm (id int PRIMARY KEY, email text NOT NULL);
CREATE TABLE billing (id int PRIMARY KEY, email text NOT NULL);
INSERT INTO crm SELECT i, 'user' || i || '@example.com' FROM generate_series(1, ${M}) i;
INSERT INTO billing SELECT i, ' USER' || i || '@Example.COM ' FROM generate_series(1, ${M}) i;
CREATE FUNCTION norm_email(e text) RETURNS text LANGUAGE sql AS $$ SELECT lower(trim(e)) $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 0.5 ms | At 500 rows a side the plan has no norm_email in it: PG18 inlined it to lower(TRIM(BOTH FROM email)) and merge-joins on that in 0.520 ms.QUERY PLAN
Aggregate (cost=104.70..104.71 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=8
-> Merge Join (cost=62.83..101.58 rows=1250 width=0) (actual rows=500.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=8
-> Sort (cost=31.41..32.66 rows=500 width=19) (actual rows=500.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 52kB
Buffers: shared hit=4
-> Seq Scan on crm a (cost=0.00..9.00 rows=500 width=19) (actual rows=500.00 loops=1)
Buffers: shared hit=4
-> Sort (cost=31.41..32.66 rows=500 width=22) (actual rows=500.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 56kB
Buffers: shared hit=4
-> Seq Scan on billing b (cost=0.00..9.00 rows=500 width=22) (actual rows=500.00 loops=1)
Buffers: shared hit=4
Planning:
Buffers: shared hit=94
Planning Time: 0.275 ms
Execution Time: 0.520 ms | 0.79s |
| 1K | 1 ms | At 1,000 rows a side PG18 runs a Merge Join on the inlined expression, sorted on both sides, in 0.978 ms.QUERY PLAN
Aggregate (cost=287.16..287.17 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=15
-> Merge Join (cost=134.66..274.66 rows=5000 width=0) (actual rows=1000.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=15
-> Sort (cost=66.83..69.33 rows=1000 width=19) (actual rows=1000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 79kB
Buffers: shared hit=7
-> Seq Scan on crm a (cost=0.00..17.00 rows=1000 width=19) (actual rows=1000.00 loops=1)
Buffers: shared hit=7
-> Sort (cost=67.83..70.33 rows=1000 width=22) (actual rows=1000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 87kB
Buffers: shared hit=8
-> Seq Scan on billing b (cost=0.00..18.00 rows=1000 width=22) (actual rows=1000.00 loops=1)
Buffers: shared hit=8
Planning:
Buffers: shared hit=94
Planning Time: 0.355 ms
Execution Time: 0.978 ms | 0.73s |
| 2K | 1.9 ms | At 2,000 rows a side PG18's sort-and-merge takes 1.860 ms, though the query names a VOLATILE function that inlining made disappear.QUERY PLAN
Aggregate (cost=868.32..868.33 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=29
-> Merge Join (cost=288.32..818.32 rows=20000 width=0) (actual rows=2000.00 loops=1)
Merge Cond: ((lower(TRIM(BOTH FROM a.email))) = (lower(TRIM(BOTH FROM b.email))))
Buffers: shared hit=29
-> Sort (cost=143.66..148.66 rows=2000 width=20) (actual rows=2000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM a.email)))
Sort Method: quicksort Memory: 166kB
Buffers: shared hit=14
-> Seq Scan on crm a (cost=0.00..34.00 rows=2000 width=20) (actual rows=2000.00 loops=1)
Buffers: shared hit=14
-> Sort (cost=144.66..149.66 rows=2000 width=23) (actual rows=2000.00 loops=1)
Sort Key: (lower(TRIM(BOTH FROM b.email)))
Sort Method: quicksort Memory: 173kB
Buffers: shared hit=15
-> Seq Scan on billing b (cost=0.00..35.00 rows=2000 width=23) (actual rows=2000.00 loops=1)
Buffers: shared hit=15
Planning:
Buffers: shared hit=94
Planning Time: 0.286 ms
Execution Time: 1.860 ms | 0.72s |
The PL/pgSQL version declared IMMUTABLE, a merge join on norm_email() itself, from 0.9 ms to 3.2 ms:
EXPLAIN (ANALYZE, TIMING OFF) SELECT count(*) AS matched FROM crm a JOIN billing b ON norm_email(a.email) = norm_email(b.email)CREATE TABLE crm (id int PRIMARY KEY, email text NOT NULL);
CREATE TABLE billing (id int PRIMARY KEY, email text NOT NULL);
INSERT INTO crm SELECT i, 'user' || i || '@example.com' FROM generate_series(1, ${M}) i;
INSERT INTO billing SELECT i, ' USER' || i || '@Example.COM ' FROM generate_series(1, ${M}) i;
CREATE FUNCTION norm_email(e text) RETURNS text LANGUAGE plpgsql IMMUTABLE AS $$ BEGIN RETURN lower(trim(e)); END $$;
VACUUM ANALYZE;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 0.9 ms | At 500 rows a side PG18's plan still calls norm_email, since PL/pgSQL is never inlined, but as IMMUTABLE it can be a Merge Cond: PG18 sorts both lists on it and merges them in 0.938 ms.QUERY PLAN
Aggregate (cost=962.20..962.21 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=24
-> Merge Join (cost=62.83..959.08 rows=1250 width=0) (actual rows=500.00 loops=1)
Merge Cond: ((norm_email(a.email)) = (norm_email(b.email)))
Buffers: shared hit=24
-> Sort (cost=31.41..32.66 rows=500 width=19) (actual rows=500.00 loops=1)
Sort Key: (norm_email(a.email))
Sort Method: quicksort Memory: 52kB
Buffers: shared hit=20
-> Seq Scan on crm a (cost=0.00..9.00 rows=500 width=19) (actual rows=500.00 loops=1)
Buffers: shared hit=20
-> Sort (cost=31.41..32.66 rows=500 width=22) (actual rows=500.00 loops=1)
Sort Key: (norm_email(b.email))
Sort Method: quicksort Memory: 56kB
Buffers: shared hit=4
-> Seq Scan on billing b (cost=0.00..9.00 rows=500 width=22) (actual rows=500.00 loops=1)
Buffers: shared hit=4
Planning:
Buffers: shared hit=84
Planning Time: 0.232 ms
Execution Time: 0.938 ms | 0.71s |
| 1K | 1.6 ms | At 1,000 rows a side PG18's Merge Join takes 1.641 ms, the function computed as a sort key per row rather than tested per pair.QUERY PLAN
Aggregate (cost=3227.16..3227.17 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=31
-> Merge Join (cost=134.66..3214.66 rows=5000 width=0) (actual rows=1000.00 loops=1)
Merge Cond: ((norm_email(a.email)) = (norm_email(b.email)))
Buffers: shared hit=31
-> Sort (cost=66.83..69.33 rows=1000 width=19) (actual rows=1000.00 loops=1)
Sort Key: (norm_email(a.email))
Sort Method: quicksort Memory: 79kB
Buffers: shared hit=23
-> Seq Scan on crm a (cost=0.00..17.00 rows=1000 width=19) (actual rows=1000.00 loops=1)
Buffers: shared hit=23
-> Sort (cost=67.83..70.33 rows=1000 width=22) (actual rows=1000.00 loops=1)
Sort Key: (norm_email(b.email))
Sort Method: quicksort Memory: 87kB
Buffers: shared hit=8
-> Seq Scan on billing b (cost=0.00..18.00 rows=1000 width=22) (actual rows=1000.00 loops=1)
Buffers: shared hit=8
Planning:
Buffers: shared hit=84
Planning Time: 0.215 ms
Execution Time: 1.641 ms | 0.74s |
| 2K | 3.2 ms | At 2,000 rows a side PG18's IMMUTABLE PL/pgSQL join takes 3.166 ms, about twice as long as at half the rows.QUERY PLAN
Aggregate (cost=11648.32..11648.33 rows=1 width=8) (actual rows=1.00 loops=1)
Buffers: shared hit=45
-> Merge Join (cost=288.32..11598.32 rows=20000 width=0) (actual rows=2000.00 loops=1)
Merge Cond: ((norm_email(a.email)) = (norm_email(b.email)))
Buffers: shared hit=45
-> Sort (cost=143.66..148.66 rows=2000 width=20) (actual rows=2000.00 loops=1)
Sort Key: (norm_email(a.email))
Sort Method: quicksort Memory: 166kB
Buffers: shared hit=30
-> Seq Scan on crm a (cost=0.00..34.00 rows=2000 width=20) (actual rows=2000.00 loops=1)
Buffers: shared hit=30
-> Sort (cost=144.66..149.66 rows=2000 width=23) (actual rows=2000.00 loops=1)
Sort Key: (norm_email(b.email))
Sort Method: quicksort Memory: 173kB
Buffers: shared hit=15
-> Seq Scan on billing b (cost=0.00..35.00 rows=2000 width=23) (actual rows=2000.00 loops=1)
Buffers: shared hit=15
Planning:
Buffers: shared hit=84
Planning Time: 0.226 ms
Execution Time: 3.166 ms | 0.70s |
SQL Server. norm_email() with inlining off on both sides: a serial hash join on the function's results, on database c9ebddf4, from 4 ms to 18 ms.
SELECT COUNT(*) AS matched FROM crm a JOIN billing b ON ${SCHEMA}.norm_email(a.email) = ${SCHEMA}.norm_email(b.email)CREATE TABLE crm (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
CREATE TABLE billing (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
INSERT INTO crm (id, email) SELECT gs.value, CONCAT('user', gs.value, '@example.com') FROM GENERATE_SERIES(1, ${M}) gs;
INSERT INTO billing (id, email) SELECT gs.value, CONCAT(' USER', gs.value, '@Example.COM ') FROM GENERATE_SERIES(1, ${M}) gs;
UPDATE STATISTICS crm; UPDATE STATISTICS billing;
CREATE FUNCTION norm_email(@e VARCHAR(200)) RETURNS VARCHAR(200) WITH INLINE = OFF AS
BEGIN
RETURN LOWER(TRIM(@e));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 4 ms | At 500 rows a side SQL Server computes norm_email once per row in a Compute Scalar on each side and joins the results in a Hash Match. The plan is serial because of the UDF and takes 4 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.0732698 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0003005 SubtreeCost=0.0732698 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=500 IO=0 CPU=0.0607579 SubtreeCost=0.0729693 AvgRowSize=9) (actual Rows=500 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1006
Hash Keys Probe: Expr1005
Probe Residual: [Expr1006]=[Expr1005]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1376kB Output=1376kB Used=640kB
-> Compute Scalar (est Rows=500 IO=0 CPU=0.00005 SubtreeCost=0.00610422 AvgRowSize=111) (actual Rows=500 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: Expr1006
Defined Values: Expr1006 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_06f90068_ebf4_44d2_b96c_707c08580651].[norm_email]([crm].[email] as [a].[email])
-> Clustered Index Scan [PK__crm__3213E83F53F25664] on crm a (est Rows=500 RowsRead=500 IO=0.00534722 CPU=0.000707 SubtreeCost=0.00605422 AvgRowSize=29) (actual Rows=500 RowsRead=500 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 500 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=500 IO=0 CPU=0.00005 SubtreeCost=0.00610422 AvgRowSize=111) (actual Rows=500 Executions=1 Elapsedms=2 CPUms=2)
Node Id: 5 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_06f90068_ebf4_44d2_b96c_707c08580651].[norm_email]([billing].[email] as [b].[email])
-> Clustered Index Scan [PK__billing__3213E83F06BCDFE1] on billing b (est Rows=500 RowsRead=500 IO=0.00534722 CPU=0.000707 SubtreeCost=0.00605422 AvgRowSize=32) (actual Rows=500 RowsRead=500 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 500 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x8999A5E47C7E32FE
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1376kB MaxUsed=640kB Required=1024kB Desired=1376kB Requested=1376kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=17ms CPU=6ms Memory=408kB CachedPlanSize=48kB
CPU Time: 4 ms
Execution Time: 4 ms | 0.61s |
| 1K | 9 ms | At 1,000 rows a side SQL Server runs the same Hash Match on the function's results, 1,000 matches, one thread, 9 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.122222 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.122222 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=9 CPUms=9)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=1000 IO=0 CPU=0.103766 SubtreeCost=0.121622 AvgRowSize=9) (actual Rows=1000 Executions=1 Elapsedms=9 CPUms=9)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1006
Hash Keys Probe: Expr1005
Probe Residual: [Expr1006]=[Expr1005]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1728kB Output=1728kB Used=656kB
-> Compute Scalar (est Rows=1000 IO=0 CPU=0.0001 SubtreeCost=0.00892644 AvgRowSize=111) (actual Rows=1000 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: Expr1006
Defined Values: Expr1006 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_715656af_4deb_4d5a_8a9e_1c02d41110ee].[norm_email]([crm].[email] as [a].[email])
-> Clustered Index Scan [PK__crm__3213E83F794317F4] on crm a (est Rows=1000 RowsRead=1000 IO=0.00756944 CPU=0.001257 SubtreeCost=0.00882644 AvgRowSize=29) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=9 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=1000 IO=0 CPU=0.0001 SubtreeCost=0.00892644 AvgRowSize=111) (actual Rows=1000 Executions=1 Elapsedms=4 CPUms=4)
Node Id: 5 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_715656af_4deb_4d5a_8a9e_1c02d41110ee].[norm_email]([billing].[email] as [b].[email])
-> Clustered Index Scan [PK__billing__3213E83F25F89130] on billing b (est Rows=1000 RowsRead=1000 IO=0.00756944 CPU=0.001257 SubtreeCost=0.00882644 AvgRowSize=32) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=9 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x137FD1738E0C6551
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1728kB MaxUsed=656kB Required=1024kB Desired=1728kB Requested=1728kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=14ms CPU=7ms Memory=408kB CachedPlanSize=48kB
CPU Time: 9 ms
Execution Time: 9 ms | 0.52s |
| 2K | 18 ms | At 2,000 rows a side SQL Server takes 18 ms: with the function computed once per row before the join, the time doubles with the rows even without inlining.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.220867 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.220867 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=18 CPUms=18)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=2000 IO=0 CPU=0.189781 SubtreeCost=0.219667 AvgRowSize=9) (actual Rows=2000 Executions=1 Elapsedms=18 CPUms=18)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1006
Hash Keys Probe: Expr1005
Probe Residual: [Expr1006]=[Expr1005]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1408kB Output=1408kB Used=704kB
-> Compute Scalar (est Rows=2000 IO=0 CPU=0.0002 SubtreeCost=0.0145709 AvgRowSize=111) (actual Rows=2000 Executions=1 Elapsedms=8 CPUms=8)
Node Id: 3 Mode: Row
I/O: EndOfScans=1
Output List: Expr1006
Defined Values: Expr1006 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_50dcf924_a4a4_4da3_a4d8_f36d1a6fa914].[norm_email]([crm].[email] as [a].[email])
-> Clustered Index Scan [PK__crm__3213E83FB303119C] on crm a (est Rows=2000 RowsRead=2000 IO=0.0120139 CPU=0.002357 SubtreeCost=0.0143709 AvgRowSize=30) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=15 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=2000 IO=0 CPU=0.0002 SubtreeCost=0.0153116 AvgRowSize=111) (actual Rows=2000 Executions=1 Elapsedms=8 CPUms=8)
Node Id: 5 Mode: Row
I/O: EndOfScans=1
Output List: Expr1005
Defined Values: Expr1005 = [bench-azure-sql-slot-c9ebddf4-2c1c-4905-b506-057e151d5c61].[exo_temp_50dcf924_a4a4_4da3_a4d8_f36d1a6fa914].[norm_email]([billing].[email] as [b].[email])
-> Clustered Index Scan [PK__billing__3213E83FE77EE913] on billing b (est Rows=2000 RowsRead=2000 IO=0.0127546 CPU=0.002357 SubtreeCost=0.0151116 AvgRowSize=33) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=16 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x76776104E0D7614C
Degree Of Parallelism: 0 Non-Parallel Reason: TSQLUserDefinedFunctionsNotParallelizable
Memory Grant: Granted=1408kB MaxUsed=704kB Required=1024kB Desired=1408kB Requested=1408kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=16ms CPU=9ms Memory=400kB CachedPlanSize=48kB
CPU Time: 18 ms
Execution Time: 18 ms | 0.49s |
Inlined, a hash join on lower(Trim(...)), from 1 ms to 3 ms:
SELECT COUNT(*) AS matched FROM crm a JOIN billing b ON ${SCHEMA}.norm_email(a.email) = ${SCHEMA}.norm_email(b.email)CREATE TABLE crm (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
CREATE TABLE billing (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
INSERT INTO crm (id, email) SELECT gs.value, CONCAT('user', gs.value, '@example.com') FROM GENERATE_SERIES(1, ${M}) gs;
INSERT INTO billing (id, email) SELECT gs.value, CONCAT(' USER', gs.value, '@Example.COM ') FROM GENERATE_SERIES(1, ${M}) gs;
UPDATE STATISTICS crm; UPDATE STATISTICS billing;
CREATE FUNCTION norm_email(@e VARCHAR(200)) RETURNS VARCHAR(200) AS
BEGIN
RETURN LOWER(TRIM(@e));
END;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 1 ms | At 500 rows a side SQL Server has inlined the function to lower(Trim(email)) in a Compute Scalar on each side, and a Hash Match joins the results in 1 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.0732698 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0003005 SubtreeCost=0.0732698 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=500 IO=0 CPU=0.0607579 SubtreeCost=0.0729693 AvgRowSize=9) (actual Rows=500 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1003
Hash Keys Probe: Expr1004
Probe Residual: [Expr1003]=[Expr1004]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1376kB Output=1376kB Used=640kB
-> Compute Scalar (est Rows=500 IO=0 CPU=0.00005 SubtreeCost=0.00610422 AvgRowSize=111)
Node Id: 3 Mode: Row
Output List: Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(varchar(200),lower(Trim([crm].[email] as [a].[email])),0)
-> Clustered Index Scan [PK__crm__3213E83F172839E8] on crm a (est Rows=500 RowsRead=500 IO=0.00534722 CPU=0.000707 SubtreeCost=0.00605422 AvgRowSize=29) (actual Rows=500 RowsRead=500 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 500 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=500 IO=0 CPU=0.00005 SubtreeCost=0.00610422 AvgRowSize=111)
Node Id: 5 Mode: Row
Output List: Expr1004
Defined Values: Expr1004 = CONVERT_IMPLICIT(varchar(200),lower(Trim([billing].[email] as [b].[email])),0)
-> Clustered Index Scan [PK__billing__3213E83F34AE5A95] on billing b (est Rows=500 RowsRead=500 IO=0.00534722 CPU=0.000707 SubtreeCost=0.00605422 AvgRowSize=32) (actual Rows=500 RowsRead=500 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 500 Storage: RowStore
I/O: Scans=1 LogicalReads=6 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0x37103A04CBE259EA
Degree Of Parallelism: 1
Memory Grant: Granted=1376kB MaxUsed=640kB Required=1024kB Desired=1376kB Requested=1376kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=14ms CPU=6ms Memory=456kB CachedPlanSize=48kB
extra: 1
CPU Time: 1 ms
Execution Time: 1 ms | 0.50s |
| 1K | 1 ms | At 1,000 rows a side SQL Server runs the same Hash Match on the inlined expression, on one thread, and the plan still reports 1 ms.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.122222 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0006005 SubtreeCost=0.122222 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=1000 IO=0 CPU=0.103766 SubtreeCost=0.121622 AvgRowSize=9) (actual Rows=1000 Executions=1 Elapsedms=1 CPUms=1)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1003
Hash Keys Probe: Expr1004
Probe Residual: [Expr1003]=[Expr1004]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1728kB Output=1728kB Used=656kB
-> Compute Scalar (est Rows=1000 IO=0 CPU=0.0001 SubtreeCost=0.00892644 AvgRowSize=111)
Node Id: 3 Mode: Row
Output List: Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(varchar(200),lower(Trim([crm].[email] as [a].[email])),0)
-> Clustered Index Scan [PK__crm__3213E83F9A74C39E] on crm a (est Rows=1000 RowsRead=1000 IO=0.00756944 CPU=0.001257 SubtreeCost=0.00882644 AvgRowSize=29) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=9 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=1000 IO=0 CPU=0.0001 SubtreeCost=0.00892644 AvgRowSize=111)
Node Id: 5 Mode: Row
Output List: Expr1004
Defined Values: Expr1004 = CONVERT_IMPLICIT(varchar(200),lower(Trim([billing].[email] as [b].[email])),0)
-> Clustered Index Scan [PK__billing__3213E83F84413443] on billing b (est Rows=1000 RowsRead=1000 IO=0.00756944 CPU=0.001257 SubtreeCost=0.00882644 AvgRowSize=32) (actual Rows=1000 RowsRead=1000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 1000 Storage: RowStore
I/O: Scans=1 LogicalReads=9 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xBAADBE3ADC4C58DA
Degree Of Parallelism: 1
Memory Grant: Granted=1728kB MaxUsed=656kB Required=1024kB Desired=1728kB Requested=1728kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=17ms CPU=7ms Memory=456kB CachedPlanSize=48kB
extra: 1
CPU Time: 1 ms
Execution Time: 1 ms | 0.48s |
| 2K | 3 ms | At 2,000 rows a side SQL Server's hash join on the inlined lower(Trim(email)) takes 3 ms, still on one thread.Compute Scalar (est Rows=1 IO=0 CPU=0 SubtreeCost=0.220867 AvgRowSize=11)
Node Id: 0 Mode: Row
Output List: Expr1002
Defined Values: Expr1002 = CONVERT_IMPLICIT(int,[Expr1007],0)
-> Stream Aggregate (Aggregate) (est Rows=1 IO=0 CPU=0.0012005 SubtreeCost=0.220867 AvgRowSize=11) (actual Rows=1 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 1 Mode: Row
I/O: EndOfScans=1
Output List: Expr1007
Defined Values: Expr1007 = Count(*)
-> Hash Match (Inner Join) (est Rows=2000 IO=0 CPU=0.189781 SubtreeCost=0.219667 AvgRowSize=9) (actual Rows=2000 Executions=1 Elapsedms=3 CPUms=3)
Node Id: 2 Mode: Row
Hash Keys Build: Expr1003
Hash Keys Probe: Expr1004
Probe Residual: [Expr1003]=[Expr1004]
Memory Fractions: Input=1 Output=1
I/O: EndOfScans=1
Memory Grant: Input=1408kB Output=1408kB Used=704kB
-> Compute Scalar (est Rows=2000 IO=0 CPU=0.0002 SubtreeCost=0.0145709 AvgRowSize=111)
Node Id: 3 Mode: Row
Output List: Expr1003
Defined Values: Expr1003 = CONVERT_IMPLICIT(varchar(200),lower(Trim([crm].[email] as [a].[email])),0)
-> Clustered Index Scan [PK__crm__3213E83FFE4F90E0] on crm a (est Rows=2000 RowsRead=2000 IO=0.0120139 CPU=0.002357 SubtreeCost=0.0143709 AvgRowSize=30) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 4 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=15 EndOfScans=1
Output List: a.email
Defined Values: a.email
-> Compute Scalar (est Rows=2000 IO=0 CPU=0.0002 SubtreeCost=0.0153116 AvgRowSize=111)
Node Id: 5 Mode: Row
Output List: Expr1004
Defined Values: Expr1004 = CONVERT_IMPLICIT(varchar(200),lower(Trim([billing].[email] as [b].[email])),0)
-> Clustered Index Scan [PK__billing__3213E83F642B0A6F] on billing b (est Rows=2000 RowsRead=2000 IO=0.0127546 CPU=0.002357 SubtreeCost=0.0151116 AvgRowSize=33) (actual Rows=2000 RowsRead=2000 Executions=1 Elapsedms=0 CPUms=0)
Node Id: 6 Mode: Row Table Cardinality: 2000 Storage: RowStore
I/O: Scans=1 LogicalReads=16 EndOfScans=1
Output List: b.email
Defined Values: b.email
Statement: SELECT, optimization FULL (early abort: GoodEnoughPlanFound), CE model 170
Query Plan Hash: 0xB93F29584762EE0A
Degree Of Parallelism: 1
Memory Grant: Granted=1408kB MaxUsed=704kB Required=1024kB Desired=1408kB Requested=1408kB GrantWaitTime=0ms Feedback: No: First Execution
Compile: Time=16ms CPU=9ms Memory=448kB CachedPlanSize=48kB
extra: 1
CPU Time: 3 ms
Execution Time: 3 ms | 0.51s |
MySQL 8.0.39. The stored function at its default, NOT DETERMINISTIC: a hash join on the function's results, then a filter that checks the equality again, from 5.1 ms to 17 ms.
EXPLAIN ANALYZE SELECT COUNT(*) AS matched FROM crm a JOIN billing b ON norm_email(a.email) = norm_email(b.email)SET SESSION cte_max_recursion_depth = 4294967295;
CREATE TABLE crm (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
CREATE TABLE billing (id INT PRIMARY KEY, email VARCHAR(200) NOT NULL);
INSERT INTO crm (id, email) WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${M}) SELECT i, CONCAT('user', i, '@example.com') FROM s;
INSERT INTO billing (id, email) WITH RECURSIVE s(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM s WHERE i < ${M}) SELECT i, CONCAT(' USER', i, '@Example.COM ') FROM s;
CREATE FUNCTION norm_email(e VARCHAR(200)) RETURNS VARCHAR(200) NO SQL RETURN LOWER(TRIM(e));
ANALYZE TABLE crm, billing;| Scale | Time | Plan | Compute |
|---|---|---|---|
| 500 | 7 ms | At 500 rows a side MySQL hash-joins on the stored function's results and checks the equality again in a Filter above the join. The root line reports 5.11 ms.EXPLAIN
-> Aggregate: count(0) (cost=50053 rows=1) (actual time=5.1..5.11 rows=1 loops=1)
-> Filter: (norm_email(a.email) = norm_email(b.email)) (cost=25053 rows=250000) (actual time=1.97..5.07 rows=500 loops=1)
-> Inner hash join (<hash>(norm_email(a.email))=<hash>(norm_email(b.email))) (cost=25053 rows=250000) (actual time=1.96..3.12 rows=500 loops=1)
-> Table scan on b (cost=0.104 rows=500) (actual time=0.0174..0.115 rows=500 loops=1)
-> Hash
-> Table scan on a (cost=50.8 rows=500) (actual time=0.0365..0.148 rows=500 loops=1)
| 0.24s |
| 1K | 11 ms | At 1,000 rows a side MySQL runs the same Inner hash join with the Filter on top, 1,000 matches, and the root line reports 8.38 ms.EXPLAIN
-> Aggregate: count(0) (cost=200106 rows=1) (actual time=8.38..8.38 rows=1 loops=1)
-> Filter: (norm_email(a.email) = norm_email(b.email)) (cost=100106 rows=1e+6) (actual time=2.28..8.31 rows=1000 loops=1)
-> Inner hash join (<hash>(norm_email(a.email))=<hash>(norm_email(b.email))) (cost=100106 rows=1e+6) (actual time=2.28..4.49 rows=1000 loops=1)
-> Table scan on b (cost=0.105 rows=1000) (actual time=0.0114..0.198 rows=1000 loops=1)
-> Hash
-> Table scan on a (cost=101 rows=1000) (actual time=0.014..0.198 rows=1000 loops=1)
| 0.24s |
| 2K | 19 ms | At 2,000 rows a side MySQL's root line reports 17 ms: NOT DETERMINISTIC didn't stop it from hashing on the function's results.EXPLAIN
-> Aggregate: count(0) (cost=800216 rows=1) (actual time=17..17 rows=1 loops=1)
-> Filter: (norm_email(a.email) = norm_email(b.email)) (cost=400216 rows=4e+6) (actual time=4.49..16.9 rows=2000 loops=1)
-> Inner hash join (<hash>(norm_email(a.email))=<hash>(norm_email(b.email))) (cost=400216 rows=4e+6) (actual time=4.48..9.08 rows=2000 loops=1)
-> Table scan on b (cost=0.107 rows=2000) (actual time=0.0123..0.406 rows=2000 loops=1)
-> Hash
-> Table scan on a (cost=202 rows=2000) (actual time=0.0144..0.405 rows=2000 loops=1)
| 0.28s |
The first probes. Before the rebuild, a round of probes ran the same join at 1,000 rows a side, plus a function of both emails. They're not cards: PostgreSQL's ran on PG17, and PostgreSQL's and MySQL's as EXPLAIN ANALYZE row sets. Times compare within one engine only.
| Engine | Join condition | Plan | Time |
|---|---|---|---|
| PG17 | lower(trim()) written inline | Merge Join | 1.4 ms |
| PG17 | LANGUAGE sql function, default VOLATILE | Merge Join | 1.5 ms |
| PG17 | PL/pgSQL function, default VOLATILE | Nested Loop | 794 ms |
| PG17 | PL/pgSQL function, IMMUTABLE | Merge Join | 1.6 ms |
| PG17 | emails_match(a.email, b.email) | Nested Loop | 832 ms |
| SQL Server | written inline | Hash Match | 1 ms |
| SQL Server | UDF, inlined | Hash Match | 1 ms |
| SQL Server | UDF, inlining off | Hash Match | 7 ms |
| SQL Server | a UDF of both emails, inlined | Nested Loops, parallel | 128 ms |
| SQL Server | a UDF of both emails, inlining off | Nested Loops | 3.7 s |
| MySQL 8.0.39 | LOWER(TRIM()) written inline | hash join | 3.4 ms |
| MySQL 8.0.39 | stored function, NOT DETERMINISTIC | hash join | 8.4 ms |
| MySQL 8.0.39 | stored function, DETERMINISTIC | hash join | 8.4 ms |
| MySQL 8.0.39 | emails_match(a.email, b.email) | hash join with no condition, then a filter | 2.3 s |
Source: the main run, 20261119_212614_udf-post-dev, seq 26 to 32 for the cards; the probe run, 20261119_121537_phase0-dev, seq 21 to 34 for the table.
Appendix: What PostgreSQL's planner does with dateOr99, in the code
The code is cut from the PostgreSQL source at the tags of the minor versions measured, REL_18_7 and REL_17_12, and every excerpt is identical at both. Each block is a run of consecutive lines, comments kept, with links to those lines at both tags under it. The servers print their own build hashes, which aren't upstream commits, so this is upstream code, on the assumption that these functions aren't patched in the hosted builds.
Which functions inline. The planner tries to inline a function while it simplifies expressions:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/util/clauses.c: simplify_function */
if (!newexpr && allow_non_const)
newexpr = inline_function(funcid, result_type, result_collid,
input_collid, args, funcvariadic,
func_tuple, context);On GitHub: REL_18_7, REL_17_12.
The first gate is the language, and a PL/pgSQL function stops here, whatever its body:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/util/clauses.c: inline_function */
/*
* Forget it if the function is not SQL-language or has other showstopper
* properties. (The prokind and nargs checks are just paranoia.)
*/
if (funcform->prolang != SQLlanguageId ||
funcform->prokind != PROKIND_FUNCTION ||
funcform->prosecdef ||
funcform->proretset ||
funcform->prorettype == RECORDOID ||
!heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
funcform->pronargs != list_length(args))
return NULL;On GitHub: REL_18_7, REL_17_12.
The second is the body: one plain SELECT of one expression, with no FROM, no subquery and no aggregate. SELECT COALESCE(d, DATE '9999-01-01') passes.
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/util/clauses.c: inline_function */
/*
* The single command must be a simple "SELECT expression".
*
* Note: if you change the tests involved in this, see also plpgsql's
* exec_simple_check_plan(). That generally needs to have the same idea
* of what's a "simple expression", so that inlining a function that
* previously wasn't inlined won't change plpgsql's conclusion.
*/
if (!IsA(querytree, Query) ||
querytree->commandType != CMD_SELECT ||
querytree->hasAggs ||
querytree->hasWindowFuncs ||
querytree->hasTargetSRFs ||
querytree->hasSubLinks ||
querytree->cteList ||
querytree->rtable ||
querytree->jointree->fromlist ||
querytree->jointree->quals ||
querytree->groupClause ||
querytree->groupingSets ||
querytree->havingQual ||
querytree->windowClause ||
querytree->distinctClause ||
querytree->sortClause ||
querytree->limitOffset ||
querytree->limitCount ||
querytree->setOperations ||
list_length(querytree->targetList) != 1)
goto fail;On GitHub: REL_18_7, REL_17_12.
The third is volatility, and it only binds a function declared IMMUTABLE or STABLE. A LANGUAGE sql dateOr99 left at the default VOLATILE has no check here, so it inlines:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/util/clauses.c: inline_function */
/*
* Additional validity checks on the expression. It mustn't be more
* volatile than the surrounding function (this is to avoid breaking hacks
* that involve pretending a function is immutable when it really ain't).
* If the surrounding function is declared strict, then the expression
* must contain only strict constructs and must use all of the function
* parameters (this is overkill, but an exact analysis is hard).
*/
if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
contain_mutable_functions(newexpr))
goto fail;
else if (funcform->provolatile == PROVOLATILE_STABLE &&
contain_volatile_functions(newexpr))
goto fail;
if (funcform->proisstrict &&
contain_nonstrict_functions(newexpr))On GitHub: REL_18_7, REL_17_12.
Why the date check stays a filter. A join clause can be a hash key or a merge key only when its operator is hashable or mergeable, which in practice means an equality, and only when it contains no volatile function:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/plan/initsplan.c: check_hashjoinable */
/*
* check_hashjoinable
* If the restrictinfo's clause is hashjoinable, set the hashjoin
* info fields in the restrictinfo.
*
* Currently, we support hashjoin for binary opclauses where
* the operator is a hashjoinable operator. The arguments can be
* anything --- as long as there are no volatile functions in them.
*/
static void
check_hashjoinable(RestrictInfo *restrictinfo)
{
Expr *clause = restrictinfo->clause;
Oid opno;
Node *leftarg;
if (restrictinfo->pseudoconstant)
return;
if (!is_opclause(clause))
return;
if (list_length(((OpExpr *) clause)->args) != 2)
return;
opno = ((OpExpr *) clause)->opno;
leftarg = linitial(((OpExpr *) clause)->args);
if (op_hashjoinable(opno, exprType(leftarg)) &&
!contain_volatile_functions((Node *) restrictinfo))
restrictinfo->hashjoinoperator = opno;On GitHub: REL_18_7, REL_17_12.
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/plan/initsplan.c: check_mergejoinable */
/*
* check_mergejoinable
* If the restrictinfo's clause is mergejoinable, set the mergejoin
* info fields in the restrictinfo.
*
* Currently, we support mergejoin for binary opclauses where
* the operator is a mergejoinable operator. The arguments can be
* anything --- as long as there are no volatile functions in them.
*/
static void
check_mergejoinable(RestrictInfo *restrictinfo)
{
Expr *clause = restrictinfo->clause;
Oid opno;
Node *leftarg;
if (restrictinfo->pseudoconstant)
return;
if (!is_opclause(clause))
return;
if (list_length(((OpExpr *) clause)->args) != 2)
return;
opno = ((OpExpr *) clause)->opno;
leftarg = linitial(((OpExpr *) clause)->args);
if (op_mergejoinable(opno, exprType(leftarg)) &&
!contain_volatile_functions((Node *) restrictinfo))
restrictinfo->mergeopfamilies = get_mergejoin_opfamilies(opno);On GitHub: REL_18_7, REL_17_12.
c.product = cs.product qualifies, so every version of the story join that has no index to search joins by hashing on product. dateOr99(c.expiration_date) > cs.max_year, its inlined COALESCE and the hand-written OR aren't equalities, so they stay a Join Filter on every pair the hash join produces. In the equality join, norm_email(a.email) = norm_email(b.email) is an equality, but a PL/pgSQL norm_email() at the default VOLATILE fails the contain_volatile_functions test in both functions, so it's neither a hash key nor a merge key, and with no index the planner falls back to a nested loop.
Why the index on the function's result matches. Creating the index checks the expression for mutable functions, after running it through the planner's simplification, which inlines what can be inlined:
/* PostgreSQL 18.7 and 17.12, src/backend/commands/indexcmds.c: ComputeIndexAttrs */
/*
* An expression using mutable functions is probably wrong,
* since if you aren't going to get the same result for the
* same data every time, it's not clear what the index entries
* mean at all.
*/
if (contain_mutable_functions_after_planning((Expr *) expr))
ereport(ERROR,
(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
errmsg("functions in index expression must be marked IMMUTABLE")));On GitHub: REL_18_7, REL_17_12.
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/util/clauses.c: contain_mutable_functions_after_planning */
/*
* contain_mutable_functions_after_planning
* Test whether given expression contains mutable functions.
*
* This is a wrapper for contain_mutable_functions() that is safe to use from
* outside the planner. The difference is that it first runs the expression
* through expression_planner(). There are two key reasons why we need that:
*
* First, function default arguments will get inserted, which may affect
* volatility (consider "default now()").
*
* Second, inline-able functions will get inlined, which may allow us to
* conclude that the function is really less volatile than it's marked.
* As an example, polymorphic functions must be marked with the most volatile
* behavior that they have for any input type, but once we inline the
* function we may be able to conclude that it's not so volatile for the
* particular input type we're dealing with.
*/
bool
contain_mutable_functions_after_planning(Expr *expr)
{
/* We assume here that expression_planner() won't scribble on its input */
expr = expression_planner(expr);
/* Now we can search for non-immutable functions */
return contain_mutable_functions((Node *) expr);On GitHub: REL_18_7, REL_17_12.
So a PL/pgSQL dateOr99 has to be declared IMMUTABLE to be indexed, since it's never inlined and its own label is what the check sees. For the LANGUAGE sql one the check sees the inlined body. I declared it IMMUTABLE, as the main run's index version shows, and never tried the index without it.
At planning time the index's expression gets the same simplification as the query, so the index on dateOr99(expiration_date) and the query's dateOr99(c.expiration_date) both arrive as the same COALESCE:
/* PostgreSQL 18.7 and 17.12, src/backend/utils/cache/relcache.c: RelationGetIndexExpressions */
/*
* Run the expressions through eval_const_expressions. This is not just an
* optimization, but is necessary, because the planner will be comparing
* them to similarly-processed qual clauses, and may fail to detect valid
* matches without this. We must not use canonicalize_qual, however,
* since these aren't qual expressions.
*/
result = (List *) eval_const_expressions(NULL, (Node *) result);On GitHub: REL_18_7, REL_17_12.
The value the index is searched with, cs.max_year, is a plain column of the outer table, not a volatile expression, so the comparison can be an index condition inside a nested loop:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/path/indxpath.c: match_opclause_to_indexcol */
/*
* Check for clauses of the form: (indexkey operator constant) or
* (constant operator indexkey). See match_clause_to_indexcol's notes
* about const-ness.
*
* Note that we don't ask the support function about clauses that don't
* have one of these forms. Again, in principle it might be possible to
* do something, but it seems unlikely to be worth the cycles to check.
*/
if (match_index_to_operand(leftop, indexcol, index) &&
!bms_is_member(index_relid, rinfo->right_relids) &&
!contain_volatile_functions(rightop))On GitHub: REL_18_7, REL_17_12.
Why the first rebuild cached one function and not the other. With one date for the whole sheet, the inner lookup had only 8 distinct keys, and PG18 cached it for the inlined SQL function: 8 misses, one per product, and a hit for every other line. It won't cache when doing so would call a volatile function fewer times, which is why the PL/pgSQL version still checked every pair:
/* PostgreSQL 18.7 and 17.12, src/backend/optimizer/path/joinpath.c: get_memoize_path */
/*
* We can't use a memoize node if there are volatile functions in the
* inner rel's target list or restrict list. A cache hit could reduce the
* number of calls to these functions.
*/
if (contain_volatile_functions((Node *) innerrel->reltarget))
return NULL;
foreach(lc, innerrel->baserestrictinfo)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
if (contain_volatile_functions((Node *) rinfo))
return NULL;
}
/*
* Also check the parameterized path restrictinfos for volatile functions.
* Indexed functions must be immutable so shouldn't have any volatile
* functions, however, with a lateral join the inner scan may not be an
* index scan.
*/
if (inner_path->param_info != NULL)
{
foreach(lc, inner_path->param_info->ppi_clauses)
{
RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
if (contain_volatile_functions((Node *) rinfo))
return NULL;
}
}
/* Check if we have hash ops for each parameter to the path */Appendix: SQL Server's scalar UDF inlining, rules and dates
Everything here is from Microsoft's documentation and blog posts as fetched on November 19, 2026, and none of it was measured.
What it does. From Scalar UDF inlining: "By using the UDF inlining feature, the database engine automatically transforms scalar UDFs into scalar expressions or scalar subqueries." Without it, the page lists the two behaviors the inlining-off plans in this post show: "Iterative invocation. The SQL Database Engine invokes UDFs iteratively, once per qualifying tuple." and "Serial execution. SQL Server doesn't allow intra-query parallelism in queries that invoke UDFs."
What it needs. "This feature improves the performance of queries that invoke scalar UDFs in SQL Server 2019 (15.x) and later versions." The database also has to be at a high enough level: "You can make workloads automatically eligible for scalar UDF inlining by enabling compatibility level 150 for the database." The compatibility level page maps the levels this post touches:
| Level | Version | What the page says |
|---|---|---|
| 140 | SQL Server 2017 | "Queries referencing T-SQL scalar UDFs will use iterative invocation, lack costing and force serial execution." |
| 150 | SQL Server 2019 | "T-SQL scalar UDFs are transformed into equivalent relational expressions that are "inlined" into the calling query, often resulting in significant performance gains." |
| 170 | SQL Server 2025 | "The default compatibility level is 170 for newly created databases in Azure SQL Database and SQL database in Microsoft Fabric." |
What the function must look like. The inlining page lists the requirements, and many of them carry a footnote naming the cumulative update that added them, CU2 through CU11. dateOr99 meets the CU5 rule, being a single RETURN: "Starting with SQL Server 2019 (15.x) CU5, the UDF can only contain a single RETURN statement to be considered for inlining". The list also says "You don't use the UDF in a computed column or a check constraint definition." That's why the computed column in this post holds ISNULL(...) written out rather than a call to dateOr99: the query is what calls the UDF. KB4538581 lists the restrictions the cumulative updates added.
How to turn it off. Per function, with WITH INLINE = OFF: "After you run the previous statement, this UDF is never inlined into any query that invokes it." Per query, the QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_n hint "Forces the Query Optimizer behavior at a query level. This behavior happens as if the query was compiled with database compatibility level n" (query hints), and inlining has respected it since SQL Server 2019 CU9. KB4538581 lists the fix: "Inconsistent behavior occurs because Scalar UDF Inlining does not respect the QUERY_OPTIMIZER_COMPATIBILITY_LEVEL_n query hint (added in SQL Server 2019 CU9)."
Indexed computed columns. From Indexes on computed columns: "The computed_column_expression must be deterministic." The same page warns about the trap my first attempt walked into: "When you refer to string literals of the date data type in indexed computed columns in SQL Server, we recommend that you explicitly convert the literal to the date type that you want by using a deterministic date format style." SQL Server's refusal, verbatim:
Database initialization failed due to: Computed column 'expiration99' in table 'contracts' cannot be persisted because the column is non-deterministic.
When executing the following statement:
--------
ALTER TABLE contracts ADD expiration99 AS ISNULL(expiration_date, CAST('9999-01-01' AS DATE)) PERSISTED
--------Dates.
| When | What |
|---|---|
| 2017 | Froid, the research behind inlining, in PVLDB 11(4) |
| November 7, 2018 | "now available in public preview with SQL Server 2019 CTP 2.1" (Introducing Scalar UDF Inlining) |
| 2019 | the feature ships in SQL Server 2019 |
| September 7, 2021 | "Scalar UDF inlining is now available for Azure SQL Managed Instance and Azure SQL Database." (announcement) |
The caveat about tracing in the confessions comes from the same announcement.
Microsoft's own numbers. The inlining page shows a TPC-H query with a one-line UDF that took 29 minutes 11 seconds without inlining and 1.6 seconds with it, on Microsoft's machine and data, not measured here. The Froid paper counts "UDFs in use today in the Microsoft Azure SQL Database service, with billions of daily invocations", and quotes the view among "practitioners that UDFs are “evil” when it comes to performance considerations".
Appendix: How the measurements were made
The calls. Every call went to ExoBench's development server, version 1.4.27, on November 19 and 20, 2026 (UTC). The calls were scripted and recorded: direct calls, with no agent in the loop, each one logged with its arguments and its response verbatim, one line per call. Every card in this post is cut from that log byte for byte, and only the captions are written by hand.
The runs, in order.
| Run | UTC | Calls | What it did |
|---|---|---|---|
20261119_121537_phase0-dev | 12:15:37 to 12:17:01 | 34 | versions, the ${SCHEMA} checks, the equality-join probes at 1,000 rows a side |
20261119_210942_story-pilot-dev | 21:09:42 to 21:12:40 | 11 | the first rebuild, one date for the whole sheet, at 2,000 and 8,000 lines |
20261119_211719_story-pilot2-dev | 21:17:19 to 21:19:59 | 12 | a date per line, at 2,000 and 8,000 lines |
20261119_212134_story-ss-retry-dev and 20261119_212147_story-ss-retry8k-dev | 21:21:34 to 21:22:32 | 1 each | SQL Server's inlining-off call alone, at 4,000 and at 8,000 lines |
20261119_212329_story-pilot3-dev | 21:23:29 to 21:23:57 | 7 | the compatibility level 140 hint, the computed column, MySQL's functional index, PG17 |
20261119_212429_story-pilot4-dev | 21:24:29 to 21:24:39 | 2 | the UNION ALL split on MySQL and PG18 |
20261119_212614_udf-post-dev | 21:26:14 to 21:31:15 | 32 | the main run: versions, every version of the story join at 1,000 to 8,000 lines, the equality join at 500 to 2,000 rows |
20261119_221750_udf-post-ss-dev | 22:17:50 to 22:19:26 | 1 | the repeat: SQL Server's inlining-off call at all four sizes, on one database |
20261120_161840_pg-scale-dev | November 20, 16:18:40 to 16:25:39 | 5 | PG18's settings; the hand-written condition at 8,000 and 80,000 lines; the index on the function's result at 8,000, 80,000 and 800,000; the UNION ALL split at the same three sizes, which timed out; the hand-written condition's plan at 800,000, not run |
20261120_162747_pg-scale-union-dev | November 20, 16:27:47 to 16:28:14 | 2 | the UNION ALL split's plans at 80,000 and 800,000 lines, not run; the split at 8,000 and 80,000 lines |
20261120_165053_ss-scale-plans-dev | November 20, 16:50:53 to 16:53:06 | 3 | SQL Server's plans at 80,000 and 800,000 lines, not run: the inlined UDF, the hand-written condition, the computed column |
20261120_165401_ss-scale-timed-dev | November 20, 16:54:01 to 16:58:35 | 4 | SQL Server: the hand-written condition at 8,000, 80,000 and 800,000 lines; the computed column at the same sizes, which failed; the inlined UDF at 8,000 and 80,000 lines, stopped at 80,000, and at 800,000, stopped |
20261120_170109_ss-scale-timed-dev | November 20, 17:01:09 to 17:01:40 | 1 | the computed column at 8,000, 80,000 and 800,000 lines |
20261120_170218_ss-scale-timed-dev | November 20, 17:02:18 to 17:03:28 | 1 | the inlined UDF at 8,000 and 80,000 lines |
20261120_181410_ss-fill-dev | November 20, 18:14:10 to 18:26:39 | 12 | SQL Server at 8,000 and 40,000 lines, each version repeated until it ran on the database of its line on the SQL Server chart, for the chart's 40,000-line points; the inlined UDF at 800,000 lines twice, stopped both times |
That's 129 calls. The cards come from the main run, the repeat and five of the November 20 runs. The two retries wrote the UDF's far-future date as a string literal instead of DATEFROMPARTS, and the repeat and the November 20 runs' timed calls sent the main run's arguments byte for byte, apart from their sizes and a correlation id.
The servers, as the main run read them before its first query:
| Engine | Version and settings |
|---|---|
| PG18 | PostgreSQL 18.7, jit on, work_mem 4MB, 2 parallel workers per gather |
| PG17 | PostgreSQL 17.12, the same settings |
| SQL Server | Azure SQL Database GP_S_Gen5_4, compatibility level 170, TSQL_SCALAR_UDF_INLINING on, MAXDOP 8; one of the two databases, and which one isn't known |
| MySQL | MySQL 8.0.39, Aurora 3.08.0, hash join on |
No template sets jit or the parallel workers. The PostgreSQL templates end with VACUUM ANALYZE and MySQL's with ANALYZE TABLE, and SQL Server's run UPDATE STATISTICS once the tables are loaded. No PostgreSQL plan printed a JIT section, though jit is on, and this post makes no JIT claim.
How each time is read. PostgreSQL: EXPLAIN (ANALYZE, TIMING OFF), the plan's Execution Time. SQL Server: ExoBench captures the actual plan with each result, and the time is its Execution Time, with CPU Time beside it. MySQL: EXPLAIN ANALYZE, the second number of actual time on the plan's root line. Every size ran once, with no warm-up runs. Times compare within one engine only, since the engines run on different hardware.
Correctness. Every measurement that completed, 207 of them plus the 9 probes run as row sets, counted what its own data implies, in its result on SQL Server and in its plan's join rows on PostgreSQL and MySQL: 3N for the story join and M for the equality join. The first rebuild, with one date for the whole sheet, returned 5N, the 3 contracts that never expire plus 2 listed ones per line. Eight failed. Two were in the second pilot: SQL Server's inlining-off call at 8,000 lines, with "An error occurred during the current command (Done status 258).", and the first computed column, refused as non-deterministic. The third was the November 20 call of PG18's UNION ALL split at 8,000, 80,000 and 800,000 lines, which timed out after 330 seconds without a result. The other five were SQL Server calls the same day: the computed column's first call, which returned "Login failed for user" with the user's name and no result, and the inlined UDF at 80,000 lines once and at 800,000 three times, which ExoBench stopped after 67, 106, 134 and 135 seconds with "An error occurred during the current command (Done status 258).".
${SCHEMA}. A SQL Server scalar UDF has to be called by its schema: "Scalar functions must be invoked by using at least the two-part name of the function (<schema>.<function>)." (CREATE FUNCTION) ExoBench builds each run in a fresh schema, so the SQL Server queries write ${SCHEMA}.dateOr99(...) and ExoBench fills the schema in. The probes checked it: called by a one-part name, a scalar UDF failed with "'customer_tier' is not a recognized built-in function name.", and as ${SCHEMA}.customer_tier(1) it returned its row.
Two SQL Server databases. A plan that still calls a UDF names the database it ran on, and these runs used two:
| Database | The calls whose plans name it |
|---|---|
| 09222264 | the body's inlining-off card; the main run's inlining-off call at its three smaller sizes; the main run's two compatibility-hint calls and the third pilot's; both retries; the first pilot's inlining-off call; the first probes' equality join with inlining off |
| c9ebddf4 | the main run's 8,000-line inlining-off call; its equality join with inlining off; the second pilot's inlining-off call; the first probes' function of both emails with inlining off |
Plans with no UDF call left in them name no database, so where the inlined, hand-written and computed-column calls ran isn't known.
The data. PG18's template for the story join, as the main run sent it. SQL Server's and MySQL's build the same rows in their own dialects, and every card shows its own.
CREATE TABLE contracts (id int PRIMARY KEY, product char(2) NOT NULL, expiration_date date);
INSERT INTO contracts
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1],
CASE WHEN i <= 24 THEN NULL ELSE DATE '2026-01-02' + (i - 1) / 8 END
FROM generate_series(1, ${N}) i;
CREATE INDEX contracts_product_expiration ON contracts (product, expiration_date);
CREATE TABLE contract_sheet (line_id int PRIMARY KEY, product char(2) NOT NULL, max_year date NOT NULL);
INSERT INTO contract_sheet
SELECT i, (ARRAY['CL','BZ','NG','HO','RB','QM','QG','HH'])[i % 8 + 1], DATE '2026-01-02' + (${N} / 8 + i)
FROM generate_series(1, ${N}) i;
CREATE FUNCTION dateOr99(d date) RETURNS date LANGUAGE sql AS $$ SELECT COALESCE(d, DATE '9999-01-01') $$;
VACUUM ANALYZE;