Coder Perfect

In SQL, how do you get the first character of a string?


I have a SQL column that is 6 characters long. Now you simply want to take the first character of that column. Is there a string function in SQL that can accomplish this?

Asked by Vinod

Solution #1

LEFT(colName, 1) will do the same thing. It’s the same as SUBSTRING (colName, 1, 1).

I prefer LEFT because it is a little cleaner, but there isn’t much of a difference.

Answered by Eric

Solution #2

I prefer:

SUBSTRING (my_column, 1, 1)

Because the syntax is Standard SQL-92, it is more portable.

The conventional version, strictly speaking, would be

SUBSTRING (my_column FROM 1 FOR 1)

The point is, transforming from one to the other, hence to any similar vendor variation, is trivial.

p.s. It was only recently brought to my attention that functions in standard SQL are purposefully incongruent, with parameter lists that aren’t the typical commalists, in order to make them immediately identifiable as being from the standard!

Answered by onedaywhen

Solution #3

For the first character, use SUBSTRING (MyColumn, 1, 1), and for the first two, use SUBSTRING (MyColumn, 1, 2).

Answered by Damovisa

Solution #4

SELECT SUBSTR(thatColumn, 1, 1) As NewColumn from student

Answered by Devendra Verma

Solution #5

It is simple to accomplish by following the steps below.

DECLARE @SomeString NVARCHAR(20) = 'This is some string'


SET @Result = SUBSTRING(@SomeString, 2, 3)
SELECT @Result

@Result = his


SET @Result = LEFT(@SomeString, 6)
SELECT @Result

@Result = This is the result.

Answered by jet_choong

Post is based on