Queries Flashcards
SELECT
SELECT column1, column2
FROM table_name;
AS
SELECT name AS ‘Titles’
FROM movies;
DISTINCT
SELECT DISTINCT tools
FROM inventory;
will return unique values in the output, and filters out all duplicate values in the specified column(s).
WHERE
SELECT *
FROM movies
WHERE imdb_rating > 8;
used to obtain only the info we want from a table.
Comparison Operators:
= equal to != not equal to > greater than < less than >= greater than or equal to <= less than or equal to
LIKE
SELECT *
FROM movies
WHERE name LIKE ‘Se_en’;
used to compare similar values (this example returns both movies Seven and Se7en).
SELECT *
FROM movies
WHERE name LIKE ‘A%’;
will return all movies that begin with the letter ‘A’.
SELECT *
FROM movies
WHERE name LIKE ‘%a’;
will return all movies that end with ‘a’.
IS NULL
unknown values are indicated by NULL. You can use IS NULL or IS NOT NULL.
SELECT name
FROM movies
WHERE imdb_rating IS NOT NULL;
will return all movies with an imdb rating.
BETWEEN
The BETWEEN operator is used in a WHERE clause to filter the result set within a certain range. It accepts two values that are either numbers, text or dates.
SELECT *
FROM movies
WHERE year BETWEEN 1990 AND 1999;
will return movies from 1990 up to, and including 1999.
SELECT *
FROM movies
WHERE name BETWEEN ‘A’ AND ‘J’;
will return movies that begin with the letter ‘A’ up to, but not including one’s that begin with ‘J’.
AND
Used to combine multiple conditions in a WHERE clause to make the result set more specific.
SELECT *
FROM movies
WHERE year BETWEEN 1990 AND 1999
AND genre = ‘romance’;
OR
Used to combine multiple conditions in WHERE if any condition is true (for AND all conditions must be true).
SELECT *
FROM movies
WHERE year > 2014
OR genre = ‘action’;
ORDER BY
Used to sort the results either alphabetically or numerically.
SELECT *
FROM movies
ORDER BY name;
You can specify the order by using DESC (high to low or Z-A) or ASC (low to high or A-Z).
SELECT *
FROM movies
WHERE imdb_rating > 8
ORDER BY year DESC;
LIMIT
Used to specify the max number of rows in the result set.
SELECT *
FROM movies
ORDER BY imdb_rating DESC
LIMIT 20;
CASE
Allows us to create different outputs (usually in the SELECT statement). It is SQL’s way of handling the if-then logic.
ELSE gives us the string if all conditions are false.
The CASE statement must end with END.
SELECT name,
CASE
WHEN imdb_rating > 8 THEN ‘Fantastic’
WHEN imdb_rating > 5 THEN ‘Poorly Received’
ELSE ‘Avoid at All Costs’
END
FROM movies;
You can add AS to END to rename the CASE statement.
SELECT name,
CASE
WHEN imdb_rating > 8 THEN ‘Fantastic’
WHEN imdb_rating > 5 THEN ‘Poorly Received’
ELSE ‘Avoid at All Costs’
END AS ‘Review’
FROM movies;