In SQL, ‘CHARINDEX‘ is a function that returns the starting position of a specified substring within a string. If the substring is not found, it returns 0. The syntax for ‘CHARINDEX‘ is as follows:

CHARINDEX(substring, string, start_position)
  • substring‘: The substring you want to find within the string.
  • string‘: The string in which you want to search for the substring.
  • start_position‘ (optional): The position in the string to start the search. If omitted, the search starts from the beginning of the string.

Here’s a live example using SQL Server:

-- Sample table
    EmployeeName VARCHAR(50)

-- Inserting some data
INSERT INTO Employee VALUES (1, 'John Doe');
INSERT INTO Employee VALUES (2, 'Jane Smith');
INSERT INTO Employee VALUES (3, 'Bob Johnson');

-- Using CHARINDEX to find the position of 'Doe' in EmployeeName
SELECT EmployeeName, CHARINDEX('Doe', EmployeeName) AS Position
FROM Employee;

In this example, we have a table called ‘Employee‘ with two columns: ‘EmployeeID‘ and ‘EmployeeName‘. We then insert some sample data into the table.

The ‘SELECT‘ statement uses ‘CHARINDEX‘ to find the position of the substring ‘Doe‘ in the ‘EmployeeName‘ column. The result will show the original ‘EmployeeName‘ and the position of ‘Doe‘ within it.

Keep in mind that ‘CHARINDEX‘ is case-sensitive. If you want a case-insensitive search, you might want to use the ‘PATINDEX‘ function or convert both the substring and the string to lowercase (or uppercase) using functions like ‘LOWER‘ or ‘UPPER‘.

Categories: SQL


Leave a Reply

Avatar placeholder

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