STRCMP Function in SQL

The STRCMP string function in SQL compares the two strings which are passed as the argument in the STRCMP function. This function returns 0 if the length of the first string is equal to the length of the second string. If the length of the first string is more than the length of the second string, then it returns 1 otherwise -1.

Syntax of STRCMP String Function

Syntax1: This syntax uses the STRCMP function with two columns of the SQL table:

In the syntax, we have to define the name of those columns whose length we want to compare.

Syntax3: This syntax uses the STRCMP function with two strings:

Examples of STRCMP String function

Example 1: The following SELECT query compares the length of JAVATPOINT and EXAMPLES strings:

Output:

1

Example 2: The following SELECT query compares the length of two sentences passing in the STRCMP function:

Output:

-1

Example 3: The following SELECT query compares the length of two cities:

Output:

0

Example 4: This example uses the STRCMP function with the table in Structured Query Language.

Now, we create the new SQL table, which helps to understand the STRCMP string function.

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

The following CREATE statement creates the Worker_Info table:

The below INSERT queries insert the records of industry workers in the Worker_Info table:

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


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

The following SELECT query uses the STRCMP function with the Worker_First_Name and Worker_City columns of the above Worker_Info table:

This SQL query compares the first name and city of each worker.

Output:

Worker_First_NameWorker_CityCompare_Firstname_City
ArushDelhi0
BulbulDelhi1
SaurabhMumbai1
ShivaniKolkata0
AvinashDelhi1
ShyamLucknow-1

The following SELECT query uses STRCMP() with the Worker_first_Name and Worker_Last_Name columns of the above Worker_Info table:

This SQL statement compares the first name and last name of each Worker.

Output:

Worker_First_NameWorker_Last_NameSTRCMP_Firstname_Lastname
ArushSharma-1
BulbulRoy1
SaurabhRoy1
ShivaniSinghania-1
AvinashSharma1
ShyamBesas0





Latest Courses