Once upon a time, I compared the performance of PostgreSQL's extract() and date_part() functions in this article.
Recently I came across a query that provided an opportunity to revisit that comparison and explore another way to improve performance.
Here is a simple test script, which I ran using PostgreSQL 18.
create table online_order (
ord_no bigint not null,
cust_no int not null,
ord_date date not null,
ord_dt varchar(8) not null,
ord_status_cd varchar(1) not null,
comment varchar(100)
);
insert into online_order
select i, mod(i, 1000000) as cust_no,
'20241015'::date - mod(i, 1000) as ord_date,
to_char('20241015'::date - mod(i, 1000), 'yyyymmdd') as ord_dt,
(mod(i, 4) + 1) as ord_status_cd,
lpad('x', 100, 'x')
from generate_series(1, 2000000, 2) as a(i);
alter table online_order add constraint online_order_pk primary key (ord_no);
create table offline_order (
ord_no bigint not null,
cust_no int not null,
ord_date date not null,
ord_dt varchar(8) not null,
ord_status_cd varchar(1) not null,
empno int,
comment varchar(100)
);
insert into offline_order
select i, mod(i,1000000) as cust_no
,'20241015'::date - mod(i,1000) as ord_date
,to_char(('20241015'::date - mod(i,1000)),'yyyymmdd') as ord_dt
,(mod(i/2,4) + 1) as ord_status_cd
,mod(i,10000) + 1 as empno
,lpad('y',100,'y')
from generate_series(2,2000000,2) a(i);
alter table offline_order add constraint offline_order_pk primary key (ord_no);
create table ord_item (
ord_no bigint not null,
prod_id varchar(10) not null,
unit_price int not null,
quantity int not null,
on_off_code varchar(2) not null,
oder_comment varchar(100)
);
insert into ord_item
select a.ord_no, 'prod'||(mod(ord_no,200)+1)::text as prod_id
, trunc(100*random())+1 as unit_price
, trunc(10*random())+1 as quantity
, case when mod(ord_no,2)=0 then '01' else '02' end as on_off_code
, lpad('c',100,'y')
from
(select ord_no from online_order
union all
select ord_no from offline_order
) a
;
insert into ord_item
select a.ord_no, 'prod'||(mod(ord_no,200)+2)::text as prod_id
, trunc(100*random())+1 as unit_price
, trunc(10*random())+1 as quantity
, case when mod(ord_no,2)=0 then '01' else '02' end as on_off_code
, lpad('d',100,'q')
from
(select ord_no from online_order
union all
select ord_no from offline_order
) a
;
alter table ord_item add constraint ord_item_pk primary key(ord_no, prod_id);
Here is the query we have to optimize.
The query calculates the total order quantity for each day of the week:
select sum (case when extract(dow from a.ord_date) = 0 then b.quantity end) as Sunday
, sum (case when extract(dow from a.ord_date) = 1 then b.quantity end) as Monday
, sum (case when extract(dow from a.ord_date) = 2 then b.quantity end) as Tuesday
, sum (case when extract(dow from a.ord_date) = 3 then b.quantity end) as Wednesday
, sum (case when extract(dow from a.ord_date) = 4 then b.quantity end) as Thursday
, sum (case when extract(dow from a.ord_date) = 5 then b.quantity end) as Friday
, sum (case when extract(dow from a.ord_date) = 6 then b.quantity end) as Saturday
from online_order a, ord_item b
where a.ord_no = b.ord_no
and a.ord_date between '2022-01-01' and '2022-12-31';
And here is the execution plan:
Aggregate (actual time=1991.543..1991.545 rows=1.00 loops=1)
Buffers: shared hit=15714 read=80441, temp read=14327 written=14327
-> Hash Join (actual time=143.111..1481.563 rows=692000.00 loops=1)
Hash Cond: (b.ord_no = a.ord_no)
Buffers: shared hit=15714 read=80441, temp read=14327 written=14327
-> Seq Scan on ord_item b (actual time=6.971..433.665 rows=4000000.00 loops=1)
Buffers: shared hit=15150 read=61774
-> Hash (actual time=135.484..135.485 rows=346000.00 loops=1)
Buckets: 262144 Batches: 4 Memory Usage: 6105kB
Buffers: shared hit=564 read=18667, temp written=1138
-> Seq Scan on online_order a (actual time=0.218..81.167 rows=346000.00 loops=1)
Filter: ((ord_date >= '2022-01-01'::date) AND (ord_date <= '2022-12-31'::date))
Rows Removed by Filter: 654000
Buffers: shared hit=564 read=18667
Planning Time: 0.183 ms
Execution Time: 1992.431 ms
When I encountered the query, I remembered the performance comparison from my 2023 note. And I decided to replace extract() with date_part() function.
select sum (case when date_part('dow', a.ord_date) = 0 then b.quantity end) as Sunday
, sum (case when date_part('dow', a.ord_date) = 1 then b.quantity end) as Monday
, sum (case when date_part('dow', a.ord_date) = 2 then b.quantity end) as Tuesday
, sum (case when date_part('dow', a.ord_date) = 3 then b.quantity end) as Wednesday
, sum (case when date_part('dow', a.ord_date) = 4 then b.quantity end) as Thursday
, sum (case when date_part('dow', a.ord_date) = 5 then b.quantity end) as Friday
, sum (case when date_part('dow', a.ord_date) = 6 then b.quantity end) as Saturday
from online_order a, ord_item b
where a.ord_no = b.ord_no
and a.ord_date between '2022-01-01' and '2022-12-31';
The resulting execution plan is shown below:
Aggregate (actual time=1896.727..1896.730 rows=1.00 loops=1)
Buffers: shared hit=15787 read=80368, temp read=14327 written=14327
-> Hash Join (actual time=157.433..1498.384 rows=692000.00 loops=1)
Hash Cond: (b.ord_no = a.ord_no)
Buffers: shared hit=15787 read=80368, temp read=14327 written=14327
-> Seq Scan on ord_item b (actual time=11.601..444.162 rows=4000000.00 loops=1)
Buffers: shared hit=14934 read=61990
-> Hash (actual time=144.631..144.632 rows=346000.00 loops=1)
Buckets: 262144 Batches: 4 Memory Usage: 6105kB
Buffers: shared hit=853 read=18378, temp written=1138
-> Seq Scan on online_order a (actual time=0.407..86.320 rows=346000.00 loops=1)
Filter: ((ord_date >= '2022-01-01'::date) AND (ord_date <= '2022-12-31'::date))
Rows Removed by Filter: 654000
Buffers: shared hit=853 read=18378
Planning Time: 0.356 ms
Execution Time: 1898.921 ms
In my repeated tests, the query using date_part() generally performed better than the version using extract(), although the performance gap was not significant.
This is consistent with my earlier experiment: date_part() can be fasater than extract(), even when both expressions have the same estimated cost.
However, the execution plan also reveals another opportunity for improvement.
Reduing the Number of Fuction Evaluations
The query contains seven calls to date_part(), one for each day of the week.
Since the join produces 692,000 rows, the number of the function calls can be calculated as 692,000 * 7, which can result in substantial repeated computation.
Instead of calculating the day of the week separately in each conditional aggregate, we can calculate it once per input row and aggregate the quantities by day of the week first. And then we can then pivot the seven aggregated results into columns using any_value():
select any_value(case when dayofwk = 0 then c.s_quantity end) as Sunday
, any_value(case when dayofwk = 1 then c.s_quantity end) as Monday
, any_value(case when dayofwk = 2 then c.s_quantity end) as Tuesday
, any_value(case when dayofwk = 3 then c.s_quantity end) as Wednesday
, any_value(case when dayofwk = 4 then c.s_quantity end) as Thursday
, any_value(case when dayofwk = 5 then c.s_quantity end) as Friday
, any_value(case when dayofwk = 6 then c.s_quantity end) as Saturday
from (select date_part('dow', a.ord_date) as dayofwk, sum(b.quantity) as s_quantity
from online_order a, ord_item b
where a.ord_no = b.ord_no
and a.ord_date between '2022-01-01' and '2022-12-31'
group by date_part('dow', a.ord_date)) c;
Here is the resuling execution plan:
Aggregate (actual time=1584.536..1584.539 rows=1.00 loops=1)
Buffers: shared hit=14179 read=81976, temp read=14327 written=14327
-> HashAggregate (actual time=1584.520..1584.529 rows=7.00 loops=1)
Group Key: date_part('dow'::text, (a.ord_date)::timestamp without time zone)
Batches: 1 Memory Usage: 65kB
Buffers: shared hit=14179 read=81976, temp read=14327 written=14327
-> Hash Join (actual time=176.354..1512.115 rows=692000.00 loops=1)
Hash Cond: (b.ord_no = a.ord_no)
Buffers: shared hit=14179 read=81976, temp read=14327 written=14327
-> Seq Scan on ord_item b (actual time=8.353..430.188 rows=4000000.00 loops=1)
Buffers: shared hit=761 read=76163
-> Hash (actual time=167.838..167.839 rows=346000.00 loops=1)
Buckets: 262144 Batches: 4 Memory Usage: 6105kB
Buffers: shared hit=13418 read=5813, temp written=1138
-> Seq Scan on online_order a (actual time=0.214..103.156 rows=346000.00 loops=1)
Filter: ((ord_date >= '2022-01-01'::date) AND (ord_date <= '2022-12-31'::date))
Rows Removed by Filter: 654000
Buffers: shared hit=13418 read=5813
Planning Time: 0.166 ms
Execution Time: 1585.523 ms
The HashAggregate, which corresponds to the inline view c, reduces the 692,000 joined rows to just seven rows, one for each day of the week.
The key point is that we no longer need seven separate DATE_PART() expressions in the conditional aggregates. In the inline view the number of the function date_part() calls is just 692,000.
The day-of-week value is calculated in the inner query and reused by the outer query.
The execution time drops from approximately 1,899 ms to 1,586 ms—a reduction of about 16.5%.
Interestingly, the number of block IOs is identical, and the temporary I/O remains unchanged.
- EXTRACT(): 15,714 + 80,441 = 96,155
- DATE_PART(): 15,787 + 80,368 = 96,155
- Pre-aggregation: 14,179 + 81,976 = 96,155
This suggests that the improvement comes primarily from reducing CPU work rather than reducing the amount of data read.
Conclusion
This experiment highlights two useful SQL tuning principles:
1. Keep extract() in quarantine. Instead, use the date_part() function.
2. Avoid unnecessary function evaluations. When the same function is called repeatedly across many rows, consider calculating it once and reusing the result through pre-aggreation.
Addendum
The PostgreSQL documentation explictly recommends extract() because date_part() can lose precision in certain cases.
However, I have never been in a situation where I had to use extract() instead of date_part().