Fetch Only Firstname from Fullname Column

We need to use the SUBSTRING function on the full name column to extract the first name.

  • SUBSTRING, which helps in extracting a part of a column value, based on the start and end index values provided with the function.

Syntax

Here is the syntax for the SUBSTRING function, which will return a part of a column value.

  • The column_name defines the column name
  • The start_index defines the substring beginning index
  • The end_index defines the substring ending index
SUBSTRING(column_name, start_index, end_index)

Table Data

Let's assume a table with the below table definition and data, where we need to fetch employees who are also managers.

id   name             email
=============================================
1    Arun Kumar       arun@example.com
2    Kiran Kapoor     kiran@example.com
3    James Franklin   james@example.com
4    Sammy Anderson   sammy@example.com
5    Martin K         martin@example.com

SQL Query

SELECT SUBSTRING(name, 0, charindex(' ', name)) FROM employees;

This query returns the first names of all the employees from the table.

  • The starting index is zero, which means from the beginning.
  • The ending index is defined based on the position of space in the name column.

SQL Query to fetch other columns as well

SELECT id, name, email, SUBSTRING(name, 0, charindex(' ', name)) as firstname FROM employees;

This query returns the list of employee IDs who are also managers from the table.

Overall

We now know the SQL Query to fetch only the first name from a full name column.

Related Links