LOCATE Function in SQL

This string function of Structured Query Language returns the index value of the searching string in the original string. If the searched string is not found in the original string, then the function returns 0.

Syntax of LOCATE String Function

Syntax1: This syntax uses the LOCATE function with the column name of the SQL table:

In the syntax, we have to specify the name of that column on which we want to run th LOCATE function. In the function start_position parameter is optional.

Syntax2: This syntax uses the LOCATE function with the original string:

Examples of LOCATE String function

Example 1: The following SELECT query finds the position of the 'P' character in the JAVATPOINT string:

Output:

LOCATE_P_Position
6

Example 2: The following SELECT query shows the position of a substring from the second index value in the original string using the LOCATE string function:

Output:

LOCATE_.com12_Position
6

Example 3: This example uses the LOCATE function with the SQL table

To understand the LOCATE function with table, we have to create the SQL table first using CREATE TABLE statement.

The syntax for creating the new table in the SQL database is as follows:

The following CREATE statement creates the Teacher_Info table:

The below INSERT queries insert the records of college teachers in the Teacher_Info table:

The following SELECT statement displays the inserted records of the above Teacher_Info table:


Teacher_IdTeacher_First_NameTeacher_Last_NameTeacher_Dept_IdTeacher_AddressTeacher_CityTeacher_Salary
1001ArushSharma4001Aman ViharDelhi20000
1002BulbulRoy4002Nirman ViharDelhi38000
1004SaurabhRoy4001Sector 128Mumbai45000
1005ShivaniSinghania4001Vivek ViharKolkata42000
1006AvinashSharma4002Sarvodya CalonyDelhi28000
1007ShyamBesas4003Krishna NagarLucknow35000

Query 1: The following SELECT query uses the LOCATE function with the Teacher_Address column of the above Teacher_Info table:

This SQL SELECT statement shows the position of the 'Vihar' string in the address of each teacher.

Output:

Teacher_AddressLOCATE_Vihar_Position
Aman Vihar4
Nirman Vihar6
Sector 1280
Vivek Vihar5
Sarvodya Calony0
Krishna Nagar0

Query 2: The following SELECT query uses the LOCATE function with the Teacher_First_Name and Teacher_Last_Name columns of the Teacher_Info table:

SELECT Teacher_First_Name, LOCATE('a', Teacher_First_Name, 1) AS LOCATE_a_Position, Teacher_Last_Name, LOCATE('h', Teacher_Last_Name, 1) AS LOCATE_h_Position, FROM Teacher_Info;

This SQL statement shows the position of character 'a' in the first name and character 'h' in the last name of each teacher.

Output:

Teacher_First_NameLOCATE_a_PositionTeacher_Last_NameLOCATE_h_Position
Arush1Sharma2
Bulbul0Roy0
Saurabh2Roy0
Shivani5Singhania5
Avinash 1Sharma2
Shyam4Besas0





Latest Courses