I posted a question here, but no one answer so I tried to focus what's making my query slow and a question came into my mind. Which one is faster and more efficient? LEFT or SUBSTRING?
Substring: Using Substring give the initial position values and End position values. Left: using Substring give only how many char you want from LEFT Side.
The LEFT() function extracts a number of characters from a string (starting from left).
Substring() is a function in SQL which allows the user to derive substring from any given string set as per user need. Substring() extracts a string with a specified length, starting from a given location in an input string. The purpose of Substring() in SQL is to return a specific portion of the string.
MySQL SUBSTR() Function The SUBSTR() function extracts a substring from a string (starting at any position). Note: The SUBSTR() and MID() functions equals to the SUBSTRING() function.
There is no difference at all between left
and substring
because left
is translated to substring
in the execution plan.
For example:
select substring(col, 1, 2),
left(col, 3)
from YourTable
will look like this in the execution plan
<DefinedValue>
<ColumnReference Column="Expr1004" />
<ScalarOperator ScalarString="substring([col],(1),(2))">
<Intrinsic FunctionName="substring">
<ScalarOperator>
<Identifier>
<ColumnReference Column="col" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(1)" />
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(2)" />
</ScalarOperator>
</Intrinsic>
</ScalarOperator>
</DefinedValue>
<DefinedValue>
<ColumnReference Column="Expr1005" />
<ScalarOperator ScalarString="substring([col],(1),(3))">
<Intrinsic FunctionName="substring">
<ScalarOperator>
<Identifier>
<ColumnReference Column="col" />
</Identifier>
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(1)" />
</ScalarOperator>
<ScalarOperator>
<Const ConstValue="(3)" />
</ScalarOperator>
</Intrinsic>
</ScalarOperator>
</DefinedValue>
SQL Server is a database. You dod not ask questions of which string processing function is 'faster'. You ask the questions 'which can use an index?' and 'do I have the required index?'. Is all about data access, because disks are sloooooow, not about shifting CPU registers.
So, Which can use an index? (which one is sargable?). In theory LEFT
could use an index, but in practice it usually does not. SUBSTRING
cannot. Instead of SUBSTRING
use Full Text.
Design your data model to take advantage of sargable expressions, index accordingly. That's all there is to it, there is no magic bullet. Avoid scans.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With