Skip to content
Advertisement

speed up join on string field

I have a table with data like the tableA example below. the date column is formatted as a string. the close column is an integer, ticker is formatted as string.
I’m trying to run the query below on a mysql database and it is taking a very long time. is there anything I can do to speed this up, like changing the format of the date column, or adding indices or primary keys? The combination of ticker and date should be a unique value, and the date field is a timestamp, it’s just currently formatted as string.

code:

tableA

update answer:

Advertisement

Answer

If you want the difference from a year ago, then use window functions. Before that, though, fix the data model! Do not store dates as strings. So:

Then to get the close from a year ago:

You don’t have to worry about NULL values because AVG() ignores them.

Here is a db<>fiddle.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement