LEFT() and RIGHT() function in SQL Server

In SQL Server, both LEFT() and RIGHT() functions work similarly to the SUBSTRING() function, these functions return the specified number of the characters from the appropriate end of the string.

The SUBSTRING() function can easily be used in place of the LEFT() function, but returning data from the right end of a string is much more easy to code without RIGHT() function.

Summery

LEFT ( chars_exp , Char_Len )
RIGHT ( chars_exp , Char_Len )

chars_exp can be a constant, variable, or column.
Char_Len is the positive integer type value the describe how many characters of the chars_exp will be returned. If integer_expression is negative, SQL Server returns an error.

Example:

Suppose we have a table ‘tbl_employee’

Table name: tbl_Employee

Employee IdEmpNameSalaryDepartment
1Ankur1200Sales
2David3400Sales
3John1500HR
4James1200Production
5Mohan4500Production
6Ram2300HR

See the following query ( we create a Employee code  with the help of Employee name and Employee id).

SELECT EmpName,

CONVERT(CHAR(1),Employee Id)  + ‘-‘ + LEFT(EmpName,3) AS “Employee Code”

FROM tbl_Employee

 

Output Will be:

EmpNameEmployee Code
AnkurAnk-1
DavidDav-2
JohnJoh-3
JamesJam-4
MohanMoh-5
RamRam-6