Skip to content
Related Articles

Related Articles

Improve Article

SQL Query to Compare Two Strings

  • Last Updated : 14 Sep, 2021

SQL stands for Structured Query Language. It is used to communicate with the database. There are some standard SQL commands like ‘select’, ‘delete’, ‘alter’ etc. To compare two strings in SQL Server, there is no direct way. In this article, we will learn how to compare two strings in an MS SQL server and we will provide some examples.

A string function is a function that takes a string value as an input regardless of the data type of the returned value. In SQL Server, there are many built-in string functions that can be used by developers.

We can compare strings by using the IF-ELSE statement.

Syntax:

 IF Boolean_expression    



    { sql_statement | statement_block }    

[ ELSE    

    { sql_statement | statement_block } ]  

Declare variable:

We can declare variables easily by using the keyword DECLARE before the variable name. By default, the local variable starts with @.

Syntax:

 DECLARE @variable_name datatype;

Set values to the variable:

We can assign value to the variables using the SET keyword.

Syntax: 



SET @variable_name;

Example 1:

Query:

DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20);
Set @Name1='geeks';
Set @Name2='geeks';
If @Name1=@Name2 Select 'match' else Select 'not match';

Output:

The above example shows the string comparison and returns the result as a ‘match’ because both strings are the same.

Example 2:

Query:

DECLARE @Name1 VARCHAR(30), @Name2 VARCHAR(20);
Set @Name1='geeks';
Set @Name2='geeksforgeeks';
If @Name1=@Name2 Select 'match' else Select 'not match';

Output:

The above example shows the string comparison and returns the result as a ‘not match’ because both strings are not the same.

Attention reader! Don’t stop learning now. Learn SQL for interviews using SQL Course  by GeeksforGeeks.

My Personal Notes arrow_drop_up