I have a table that has a date value in column A and other columns B,C,D. I wanted to update the values of new column E based on the values of B,C,D for a given time period from A. It was slow so I added an index to A with the idea of avoiding a full table scan during the where clause A>date A<date. Still in explain and analyze I see a full table scan and the time is not being optimized as well. What to do?
Lets say the table is Table_1 and the query is:
Update Table_1
set E = CASE WHEN B>5 THEN B*2 ELSE 0
WHERE C>6 and D>8
AND A<'2024-01-01' and A>'2023-01-31'
Lets say A has data from 2000 to 2024 and using the index on A I dont want a full scan.
-
It will use an index on A if it think that that will be useful. It will depend on how much of the table is thought to match the condition on A. If most of the table matches, then using the index will be counter-productive, and it will not use it.jjanes– jjanes2024年10月24日 16:11:05 +00:00Commented Oct 24, 2024 at 16:11
-
What is the actual query plan if possible, and especially what is the total number of rows in the table, expeced number of returned rows actual number of returned rows? The relationship between these three numbers should be informative as to why postgres prefers a tablescan.user1937198– user19371982024年10月25日 02:31:22 +00:00Commented Oct 25, 2024 at 2:31
2 Answers 2
Have you tried include(B,C,D,E). Maybe the full scan is a result of a lookup. Forgive me if I'm off. I'm newer to postgres, coming from a sql server background.
-
2I'm also from a sql server background and I can assure you we don't know about indexing in postgres - better to stay silent, listen and learn in this case.topsail– topsail2024年10月24日 00:35:45 +00:00Commented Oct 24, 2024 at 0:35
You are using all the columns of a table to filter, so obviously any query processor will be using tablescan. If you want your query processor to use Index, you should add all the columns to an Index. Query will perform a little better as the data in index will be sorted than a table data.
-
1If one of the filters has sufficiently high selectivity, postgres is perfectly happy to filter initially by an index and then subsequently by additional filters.user1937198– user19371982024年10月25日 02:32:54 +00:00Commented Oct 25, 2024 at 2:32
Explore related questions
See similar questions with these tags.