I have a table called uk that contains a field called EvName. EvName is mediumtext format and contains entries with the following syntax:
Rochdale 1st Jan – 12:20 2 hours 30 min
I want to extract the time from EvName for each record and return it in a new field called StartTime. I am new to MySQL but have come up with the following. It seems quite clunky and inefficient. For example, it takes a few minutes to run on a table that has c50,000 records.
Is there a better approach?
Thanks
SELECT
*,
CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX(EvName, ':', 1), ' ', -1), ":", SUBSTRING_INDEX(SUBSTRING_INDEX(EvName, ':', -1), ' ', 1)) AS StartTime
FROM uk;
2
Answers
Strings manipulation is always costly, so you should try to avoid it and enter the data as needed.
You can try as Barmar already wrote
REGEXP_SUBSTR
fiddle
If you want to avoid the overhead of the string-splitting expression, then split it when you insert the row, and put the time into its own column.
That said, here’s a way to measure which string expression is faster:
So the regular expression solution is slightly slower, but I had to execute both of them 10 million times to get a duration that is large enough to be compared.
I ran this test on a Macbook Pro M1 2020. If it takes you several minutes to do the same test on your server with only 50,000 rows, then you need to upgrade your server.