This article explains the base functionality and uses of the LEFT, RIGHT, SUBSTRING and CHARINDEX functions in SQL.
Samples script:
-- Local variable declare @locavariable varchar(20); set @locavariable = 'HELLO WORLD'; -- Sample Execution select @locavariable as 'Variables Data Results'; SELECT RIGHT(@locavariable, 3) as 'RIGHT Results'; SELECT LEFT(@locavariable, 3) as 'LEFT Results'; SELECT CHARINDEX(' ',@locavariable) as 'CHARINDEX Results'; SELECT SUBSTRING(@locavariable,4,5) as 'SUBSTRING Results' -- Using together SELECT LEFT(@locavariable,CHARINDEX(' ',@locavariable)-1) as 'Combined Results'
Sample Results:
Variable Data Results
——————–
HELLO WORLD
RIGHT Results
————-
RLD
LEFT Results
————
HEL
CHARINDEX Results
—————–
6
SUBSTRING Results
—————–
LO WO
Combined Results
——————–
HELLO