Logical Operators

Logical Operators

Logical operators are used, together with the comparison operators =, <, >, <=, >= and LIKE, in the WHERE or HAVING clause of a SELECT query to form a condition that restricts the rows returned from a search. 

At National 5 we used the following logical operators:

We will now use the following operators at Advanced Higher:

Logical Operator: NOT 

The NOT operator returns a record from the underlying tables when the specified condition is not true.

Example Syntax

Logical Operator: BETWEEN 

The between operator selects values that fall within a specified range of values. The results returned are inclusive of the lower and upper values.

Example Syntax

Logical Operator: IN 

This allows multiple values to be specified as an alternative to multiple OR conditions and can be used to select values using subquerys.

Example

Sub Query Example

Logical Operator: ANY 

The ANY operator returns TRUE if any of the subquery values meet the condition specified in the main query.  The operator below could be any operator required such as LIKE, =

Additional Notes: ANY

Query 1: If we look at the graphical representation of the query below. The results of the inner query can be viewed as the coloured balls. 

As 90>6 is true, data is returned. Using the ANY operator, generates TRUE and so returns data to the main query.

Query 2: using the ANY operator,  the query below would generate FALSE and so does not return data to the main query.

Query 3: using the ANY operator,  the query below would generate FALSE and so does not return data to the main query.

Logical Operator: Exists

EXISTS:

Query 4: general format of an SQL query that uses the EXISTS operator. The subquery would be evaluated first and if there was any results the the EXISTS (subquery) would evaluate as TRUE.

WHERE EXISTS ( subquery );

Query 5: In the example below the inner query would return some values ( as there are values in the COL_1 field that are <=15).  Using the EXISTS operator, returns TRUE.

The subquery contains more than one row, so it returns TRUE. 

Data is therefore returned from the main query.

Query 6: In the example below the inner query would not return any values ( as there are no values in the COL_1 field that are >=15).  Using the EXISTS operator, returns FALSE.

The subquery contains no rows, so it returns FALSE. 

No data is therefore returned from the main query.

Subqueries in the WHERE clause

A subquery is a query embedded within the WHERE clause of another SQL query

The subquery executes before the main query, so the results can be passed to the main query as a condition to further restrict the data to be retrieved.

Rules for using a subquery