SQL Lesson 3 - Queries with constraints (Pt. 2)

When writingĀ WHEREĀ clauses with columns containing text data, SQL supports a number of useful operators to do things like case-insensitive string comparison and wildcard pattern matching. We show a few common text-data specific operators below:

Operator Condition Example
= Case sensitive exact string comparison (notice the single equals) col_nameĀ =Ā "abc"
!= or <> Case sensitive exact string inequality comparison col_nameĀ !=Ā "abcd"
LIKE Case insensitive exact string comparison col_nameĀ LIKEĀ "ABC"
NOT LIKE Case insensitive exact string inequality comparison col_nameĀ NOT LIKEĀ "ABCD"
% Used anywhere in a string to match a sequence of zero or more characters (only with LIKE or NOT LIKE) col_nameĀ LIKEĀ "%AT%"
(matches "AT", "ATTIC", "CAT" or even "BATS")
_ Used anywhere in a string to match a single character (only with LIKE or NOT LIKE) col_nameĀ LIKEĀ "AN_"
(matches "AND", but not "AN")
IN (…) String exists in a list col_nameĀ INĀ ("A", "B", "C")
NOT IN (…) String does not exist in a list col_nameĀ NOT INĀ ("D", "E", "F")

Did you know?

All strings must be quoted so that the query parser can distinguish words in the string from SQL keywords.

We should note that while most database implementations are quite efficient when using these operators, full-text search is best left to dedicated libraries likeĀ Apache LuceneĀ orĀ Sphinx. These libraries are designed specifically to do full text search, and as a result are more efficient and can support a wider variety of search features including internationalization and advanced queries.

Exercise

Here's the definition of a query with aĀ WHEREĀ clause again, go ahead and try and write some queries with the operators above to limit the results to the information we need in the tasks below.

Select query with constraints

SELECT column, another_column, … FROM mytable **WHERE _condition_ AND/OR _another_condition_ AND/OR …**;

1. Find all the Toy Story movies
	1. SELECT * FROM movies WHERE Title LIKE 'Toy Story%';
2. Find all the movies directed by John Lasseter
	1. SELECT * FROM movies WHERE Director LIKE 'John Lasseter%';
3. Find all the movies (and director) not directed by John Lasseter
	1. SELECT Title, Director FROM movies WHERE Director NOT LIKE 'John Lasseter%';
4. Find all the WALL-* movies
	1. SELECT Title FROM movies WHERE Title LIKE 'WALL-_';

Exercise 3 — Tasks

1. Find all the Toy Story moviesĀ āœ“
2. Find all the movies directed by John LasseterĀ āœ“
3. Find all the movies (and director) not directed by John LasseterĀ āœ“
4. Find all the WALL-* moviesĀ āœ“

This page is Lesson 3 from SQLBolt, titled "Queries with constraints (Pt. 2)". It teaches how to use various SQL operators in the WHERE clause, especially for working with text data. The main points include:

The lesson includes interactive exercises to practice writing SQL queries using these operators and constraints in the WHERE clause.[1]

1