Sample Header Ad - 728x90

How to efficiently get absolute value of a time interval in Postgresql?

0 votes
1 answer
1239 views
I have a huge table in Postgresql-11 like following: CREATE TABLE my_huge_table( tick_time timestamp(6) with time zone NOT NULL, brok_time timestamp(6) with time zone, trade_day date NOT NULL, --other fields ... ... CONSTRAINT my_huge_table_pkey PRIMARY KEY (tick_time) ); CREATE INDEX idx_my_huge_table_td_time ON my_huge_table USING brin ( trade_day, abs(tick_time - brok_time) ); Then I make a query and want it to take advantage of the index idx_my_huge_table_td_time, like this: SELECT * FROM my_huge_table WHERE trade_day BETWEEN TO_DATE('20220104', 'YYYYMMDD') AND TO_DATE('20220104', 'YYYYMMDD') AND ABS(tick_time - brok_time) ERROR: function abs(interval) does not exist > > LINE 3: AND ABS(tick_time - brok_time) > ^ > > HINT: No function matches the given name and argument types. You might need to add explicit type casts. > > SQL state: > 42883 Character: 525 It looks like that the func abs() can **NOT** accept a interval value as a argument. Then, I changed my query: SELECT * FROM my_huge_table WHERE trade_day BETWEEN TO_DATE('20220104', 'YYYYMMDD') AND TO_DATE('20220104', 'YYYYMMDD') AND GREATEST(tick_time - brok_time, brok_time - tick_time) < INTERVAL '10 s'; This time it can be executed, but didn't take advantage of the index. My questions: 1.How should I compose the expression of index? In fact I want it to record a distance(absolute interval value) between two timestamp fields; 2.How should I code the query that can use the index above? 3.In fact GREATEST(tick_time - brok_time, brok_time - tick_time) is **NOT** a good idea, since it invoked two times computing. Isn't it? 4.After created the index, I note that the real DDL SQL of the index reported by PostgreSQL is: CREATE INDEX idx_my_huge_table_td_time ON public.my_huge_table USING brin (trade_day, abs(date_part('epoch'::text, tick_time - brok_time))); Have the value of the expresstion casted into a text type? It apparently is **NOT** my expectation!
Asked by Leon (411 rep)
Apr 23, 2023, 06:23 AM
Last activity: Apr 23, 2023, 11:13 PM