Have you ever encountered a situation where you needed to extract the first name from a full name stored in a single column? In this blog post, we will explore different ways to achieve this without using the CHARINDEX and SUBSTRING functions.
Let’s consider a scenario where we have a table called EMPLOYEE with a column named NAME, which stores the full name of each employee. Our goal is to retrieve only the first name from this column.
Here is a sample database, table, and data that we will be using:
-- Database Creation
CREATE DATABASE SQLAuthority;
GO
USE SQLAuthority;
GO
-- Table Creation
CREATE TABLE EMPLOYEE (ID INT IDENTITY(1,1), NAME VARCHAR(100));
GO
-- Sample Data
INSERT INTO EMPLOYEE (NAME) VALUES('PINAL DAVE');
GO
INSERT INTO EMPLOYEE (NAME) VALUES('CHETAN DAVE');
GO
INSERT INTO EMPLOYEE (NAME) VALUES('BHIM RAO');
GO
INSERT INTO EMPLOYEE (NAME) VALUES('SRK SINGH');
Now, let’s explore some possible solutions to extract the first name:
Solution 1: Using LEFT and CHARINDEX
SELECT LEFT(Name, CHARINDEX(' ', Name + ' ') - 1) AS FirstName
FROM EMPLOYEE;
This solution uses the LEFT function to retrieve the characters from the beginning of the NAME column until the first occurrence of a space. The CHARINDEX function is used to find the position of the space character.
Solution 2: Using SUBSTRING and CHARINDEX
SELECT SUBSTRING(Name, 0, CHARINDEX(' ', Name, 0)) AS FirstName
FROM EMPLOYEE;
Similar to the previous solution, this approach uses the SUBSTRING function to extract the characters from the NAME column starting from position 0 until the first occurrence of a space.
Now, here comes the puzzle for you. Can you think of any other practical solutions to extract the first name without using the CHARINDEX and SUBSTRING functions? Share your answers in the comment section below.
Stay tuned for the next blog post where we will reveal the additional solutions and discuss their pros and cons. Don’t forget to share this puzzle with your friends and see if they can solve it too!