How do you use charindex in SQL?

In SQL, the CHARINDEX function is used to find the first occurrence of a string within another string. Its syntax is as follows:

Finds the position of a specific expression within another expression, starting from a specified location.

Specification:

  1. string_to_search:The string that needs to be found.
  2. String to search for.
  3. start location (optional): the position to start searching from, default is 1.

Return value: If the specified string is found, return its position in the original string (starting from 1), otherwise return 0.

Imagine there is a table named “Customers” with a field named “Address”. We want to find all the records that contain the word “Street” in the address. This can be achieved using the CHARINDEX function.

SELECT * FROM Customers
WHERE CHARINDEX('Street', Address) > 0;

This will retrieve all records that contain “Street” in the address.

bannerAds