Interview Question of the Week #052 – Print String in Reverse Order

Question: Can you reverse a string, or its suffix, without using REVERSE? Yes. Keep the prefix and append the suffix’s characters from the end back to the chosen starting position.

Two rows of colored beads keep the first two positions and reverse the last three

At the last interview of the year, a co-interviewer gave a candidate an hour with SQL Server and the installed help files, but no internet. The candidate produced a useful extra feature: reversal could start at a selected position. There was one important catch, though. The answer used REVERSE, which the question had forbidden.

Let us keep that suffix idea and meet the restriction. This function is for a separate scratch database and refuses to overwrite an existing demo function.

IF OBJECT_ID(N'dbo.InterviewReverseSuffix',N'FN') IS NOT NULL
 THROW 50001,'Use a fresh scratch database; the demo function already exists.',1;
GO
CREATE FUNCTION dbo.InterviewReverseSuffix
(@Text varchar(8000),@StartPosition int)
RETURNS varchar(8000)
AS
BEGIN
 IF @Text IS NULL OR @StartPosition IS NULL RETURN NULL;
 DECLARE @Length int=LEN(CONVERT(varchar(max),@Text)+CHAR(1))-1;
 IF @StartPosition<=0 OR @StartPosition>@Length SET @StartPosition=1;
 DECLARE @Result varchar(8000)=LEFT(@Text,@StartPosition-1),@Pos int=@Length;
 WHILE @Pos>=@StartPosition
 BEGIN
  SET @Result=@Result+SUBSTRING(@Text,@Pos,1);
  SET @Pos-=1;
 END;
 RETURN @Result;
END;
GO
SELECT dbo.InterviewReverseSuffix('forward string',3) AS FromThird,
       dbo.InterviewReverseSuffix('forward string',0) AS WholeString,
       dbo.InterviewReverseSuffix('forward string',-9) AS NegativeStart,
       dbo.InterviewReverseSuffix('forward string',900) AS BeyondEnd;
SELECT '['+dbo.InterviewReverseSuffix('ab  ',1)+']' AS PreservedSpaces;

Starting at position 3 preserves fo and returns fognirts drawr. The original displayed forgnirts draw, which does not match its position-3 call. Starting at zero, a negative position or beyond the end returns the full reversal: gnirts drawrof.

The SQL Server 2025 result shows the corrected position-3 suffix, the full reversal and the preserved trailing spaces. The scratch database name belongs only to this lab.
The SQL Server 2025 result shows the corrected position-3 suffix, the full reversal and the preserved trailing spaces. The scratch database name belongs only to this lab.

Spaces and missing values are part of the answer

LEN normally ignores trailing spaces. The sentinel in the length expression counts them without changing the input, so 'ab ' becomes ' ba', shown between brackets in the second result. A NULL input or position returns NULL.

This preserves the original VARCHAR(8000) interface and simple-character exercise. It is not a general-purpose Unicode grapheme reversal routine. Combining characters and Unicode supplementary characters need a deliberately chosen representation and collation.

Without the interview restriction, SQL Server’s built-in REVERSE is the straightforward choice. The value of this exercise is reading the requirement carefully, defining boundary behavior and checking that the displayed result actually follows from the code.

The REVERSE reference describes the built-in alternative.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

Previous Post
Interview Question of the Week #051 – Actual Execution Plan vs. Estimated Execution Plan
Next Post
Interview Question of the Week #053 – What is the Difference Between Deterministic Functions and Nondeterministic Functions?

Related Posts

No results found.

12 Comments. Leave new

  • but… there is a the reverse statement in the UDF function! so is it not supposed to be a failure instead of success? or I missed something in the question?

    Reply
  • How about with a WHILE loop?

    —————————————————-
    DECLARE @string varchar(10) = ‘Andrew’
    DECLARE @reverse varchar(10) = ”
    DECLARE @i int = len(@string)

    WHILE @i between 0 AND len(@string)
    begin
    set @reverse = @reverse + substring(@string,@i,1)
    set @i = @i-1
    print @i
    end
    SELECT @reverse
    —————————————————-

    Reply
  • That IS using reverese! Duh! :o)

    Reply
  • alter function fnReverse (@text varchar(500), @FromPosition int=0 )
    returns varchar(500)
    as
    begin
    declare @retext varchar(500)=”, @input varchar(500)=”
    set @input =substring(@text,0,@FromPosition)
    set @text=substring(@text,@fromPosition,len(@text)+1)
    while (len (@text)>0)
    begin
    set @retext=@retext+RIGHT(@text,1)
    set @text=LEFT(@text,len(@text)-1)

    end
    return @input+@retext
    end

    go
    select dbo.fnReverse(‘vikas’,default)

    Reply
  • This UDF uses the REVERSE function twice. Perhaps the interviewers were so dazzled with extra functionality that they didn’t notice the base requirement wasn’t met.

    Reply
  • Vaibhav Baweja
    January 4, 2016 12:38 pm

    Pinal, this does not seem to be a true solution for the said problem. as the UDF uses the REVERSE here.

    Reply
  • Arsen Barbakadze
    January 6, 2016 6:33 am

    By the way, Pinal, there is missed comma after @startposition and before LEN() in STUFF function.

    Reply
  • CREATE FUNCTION UDF_ReverseString
    ( @string VARCHAR(8000),
    @Pos INT)
    RETURNS VARCHAR(8000)
    AS
    BEGIN

    DECLARE @reverse varchar(8000) = ”

    DECLARE @i int = len(@string)

    SET @Pos = @Pos+1

    WHILE @i between @Pos AND len(@string)
    begin
    set @reverse = @reverse + substring(@string,@i,1)
    set @i = @i-1
    –print @i
    end

    Return @reverse

    END

    Reply
  • Truth is you don’t need a loop:

    declare
    @str varchar(1000)=’1234567890′,
    @rev_str varchar(1000)=”

    ;with nr as ( — generate numbers from 1 to 100,000;
    select top (100000)
    N = row_number() over (order by s1.[object_id])
    FROM
    sys.all_objects s1
    cross join sys.all_objects s2
    )
    select
    @rev_str=@rev_str+substring(@str,len(@str)-N+1,1)
    from
    nr
    where
    nr.n<=len(@str)

    select
    @str 'String',
    @rev_str 'Rev_String'

    Reply
  • Truth is you don’t need a loop:

    declare
    @str varchar(1000)=’1234567890′,
    @rev_str varchar(1000)=”

    ;with nr as ( — generate numbers from 1 to 100,000
    select top (100000)
    N = row_number() over (order by s1.[object_id])
    FROM
    sys.all_objects s1
    cross join sys.all_objects s2
    )
    select
    @rev_str=@rev_str+substring(@str,len(@str)-N+1,1)
    from
    nr
    where
    nr.n<=len(@str)

    select
    @str 'String',
    @rev_str 'Rev_String'

    Reply
  • I’m not sure what value a question like this provides. I’d prefer the candidate know that there is a a REVERSE function. Although the use of a numbers “table” by thesqllist does impress me.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.