Logical Operators

I am going to make headway on the series of very short articles or tidbits on Transaction SQL Operators. An operator is a symbol specifying an action that is performed on one or more expressions.

I will exploring the Logical Operators today. In short, these operators return either a boolean TRUE or FALSE.

To demonstrate many of these operators, we need a temporary table to query against. The Transaction SQL code below creates a table that contains the first eight prime numbers.

Any complex real world programming example probably has one or more of these operators in the TSQL script.

The output of the SELECT statement showing the prime numbers.

The SOME operator compares a scalar value with a single column set of values. It returns TRUE when one or more conditions are satisfied.

The ANY operator is equivalent to the SOME operator. It returns FALSE when all of the conditions are not satisfied.

The ALL operator compares a scalar value with a single column set of values. It returns TRUE when all of the conditions are satisfied.

The BETWEEN operator compares a scalar against a range of values. It returns TRUE when the scalar is greater than or equal to the lower limit and less than or equal to the upper limit.

The logical AND operator combines two BOOLEAN expressions. It returns TRUE if both conditions are true; otherwise, it returns false. The example below uses simple integer expressions to demonstrate this operator.

The logical OR operator combines two BOOLEAN expressions. It returns TRUE if any conditions are true; otherwise, it returns false. The example below uses simple integer expressions to demonstrate this operator.

The LIKE operator determines if a character string matches a specific pattern. The example below queries the sys.databases table and returns the row for the master database.

The IN operator ascertains if a value matches any elements in the sub-query or list of elements. The example below queries the sys.databases table and returns a row for each system database.

The NOT operator negates the BOOLEAN expression. The example below queries the sys.databases table and returns the first 10 databases by id. It removes the master database by using the NOT LIKE clause.

Last but not least, the EXISTS operator finds out if the sub-query contains at least one row. The following example checks to see if the Adventure Works database for 2012 is installed.

Next time, I will be researching the Set Operators.

Related posts

Leave a Comment