LEFT and RIGHT are used to retrieve parts of a content in a column starting from left and right respectively.
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE #temp ( ID INT, Name VARCHAR(10) ); INSERT INTO #temp VALUES (123, 'John'), (23456,'Sarah'), (345678,'Tim'); SELECT * FROM #temp |
1 2 3 4 |
ID Name 123 John 23456 Sarah 345678 Tim |
John has four characters. Starting from left for 2 characters, we should get ‘Jo.’ Starting from right for 2 characters, we should get ‘hn.’
1 2 3 |
SELECT LEFT(Name, 2) AS Left_Name, RIGHT(Name, 2) AS Right_Name FROM #temp |
1 2 3 4 |
Left_Name Right_Name Jo hn Sa ah Ti im |
In addition to text, LEFT and RIGHT can also retrieve numbers from integer variable.
1 2 3 4 5 |
SELECT LEFT(Name, 2) AS Left_Name, RIGHT(Name, 2) AS Right_Name, LEFT(ID, 2) AS Left_ID, RIGHT(ID, 2) AS Right_ID FROM #temp |
1 2 3 4 |
Left_Name Right_Name Left_ID Right_ID Jo hn 12 23 Sa ah 23 56 Ti im 34 78 |
However, the returned data type will be character.
1 2 3 4 5 6 7 8 |
SELECT SUM(temp2.LEFT_ID) FROM ( SELECT LEFT(Name, 2) AS Left_Name, RIGHT(Name, 2) AS Right_Name, LEFT(ID, 2) AS Left_ID, RIGHT(ID, 2) AS Right_ID FROM #temp ) AS temp2 |
1 |
Operand data type varchar is invalid for sum operator. |
Unless, we use CAST .
1 2 3 4 5 6 7 8 |
SELECT SUM(CAST(temp2.LEFT_ID AS INT)) AS SUM FROM ( SELECT LEFT(Name, 2) AS Left_Name, RIGHT(Name, 2) AS Right_Name, LEFT(ID, 2) AS Left_ID, RIGHT(ID, 2) AS Right_ID FROM #temp ) AS temp2 |
1 2 |
SUM 69 |