Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
SQL

Get the First and Last Word from a String or Sentence in SQL

- 11.06.18 | 24.03.26 - ErcanOPAK

The Challenge: You have a column of full names, product titles, or long descriptions, and you need to grab just the first and last words. Since SQL doesn’t have a native Split() function that returns an array easily, we have to get creative with string positioning.

The Solution: We use a combination of CHARINDEX, SUBSTRING, and the clever REVERSE trick to pinpoint the boundaries of our target words.


πŸš€ The “Bulletproof” SQL Script

This script handles full sentences, single words, and even empty strings without breaking. Copy-paste this into your query window:

DECLARE @Sentence VARCHAR(MAX) = 'The quick brown fox jumps over the lazy dog';

-- Calculate indices for the first and last space
DECLARE @first_space_index INT = CHARINDEX(' ', @Sentence) - 1;
DECLARE @last_space_index  INT = CHARINDEX(' ', REVERSE(@Sentence)) - 1;

-- Logic: If no space is found, the whole string is both the first and last word.
IF @first_space_index < 0
    SELECT @Sentence AS [First Word], @Sentence AS [Last Word];
ELSE
    SELECT 
        SUBSTRING(@Sentence, 1, @first_space_index) AS [First Word], 
        REVERSE(SUBSTRING(REVERSE(@Sentence), 1, @last_space_index)) AS [Last Word];

πŸ“Š Expected Results:

Input First Word Last Word
‘The quick brown dog’ The dog
‘The’ The The

πŸ” The “Secret Sauce”: Why use REVERSE?

Finding the first word is easy (look for the first space from the left). But finding the last word is tricky because its position varies.

The Pro Trick: By REVERSE-ing the entire sentence, the last word becomes the first word. We grab it, and then REVERSE it back to its original form. It’s significantly faster and cleaner than writing complex loops!

πŸ’‘ Use Case: Cleaning Name Data

This is perfect for splitting a FullName column into FirstName and LastName when you don’t have a middle name column:

SELECT FirstName = SUBSTRING(FullName, 1, CHARINDEX(' ', FullName) - 1)...

Summary

Mastering string boundaries is essential for any SQL developer. By using REVERSE, you’ve just added a high-performance tool to your T-SQL toolkit that handles dynamic data lengths with ease.

Related posts:

SQL Index Fragmentation β€” What Actually Matters (and What Doesn't)

"ORDER BY" with CASE and UNION in SQL Server

How to find a specific text string in a SQL Server Stored Procedure, Function, View or Trigger

Post Views: 836

Post navigation

Add Constraint to SQL Table to ensure email contains @
Get the User Name and Domain Name from an Email Address in SQL

2 thoughts on “Get the First and Last Word from a String or Sentence in SQL”

  1. Daniel says:
    17.05.22 at 12:27

    Fails if only 1 word

    Reply
    1. ErcanOPAK says:
      20.05.22 at 11:50

      Thanks for the feedback, Daniel. I have updated the solution. πŸ™‚

      Reply

Leave a Reply Cancel reply

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

April 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
27282930  
« Mar    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)
  • Add Constraint to SQL Table to ensure email contains @ (578)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (564)
  • Average of all values in a column that are not zero in SQL (531)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (489)
  • Find numbers with more than two decimal places in SQL (448)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries
  • SQL: Use Window Functions for Advanced Analytical Queries
  • .NET Core: Use Background Services for Long-Running Tasks
  • .NET Core: Use Minimal APIs for Lightweight HTTP Services
  • Git: Use Cherry-Pick to Apply Specific Commits Across Branches
  • Git: Use Interactive Rebase to Clean Up Commit History Before Merge

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (950)
  • How to add default value for Entity Framework migrations for DateTime and Bool (859)
  • Get the First and Last Word from a String or Sentence in SQL (836)
  • How to select distinct rows in a datatable in C# (805)
  • How to make theater mode the default for Youtube (754)

Recent Posts

  • C#: Use Init-Only Setters for Immutable Objects After Construction
  • C#: Use Expression-Bodied Members for Concise Single-Line Methods
  • C#: Enable Nullable Reference Types to Eliminate Null Reference Exceptions
  • C#: Use Record Types for Immutable Data Objects
  • SQL: Use CTEs for Readable Complex Queries

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com