SELECT
- Determines which columns to include.
SELECT *
to cover all columns in your table(s).SELECT col1, col2, ...
to choose specific columns.SELECT DISTINCT col1, col2, ...
to choose columns, then filter out duplicate rows. Identical rows are shown only once.SELECT COUNT(col1, col2, ...)
instead of showing the selected table, show the number of rows are in it.AS
if you want to rename a selected column
SELECT salary AS totalSalary
FROM
- Determines which table the columns are drawn from.
SELECT table1.name, table2.city
ON
to specify which PK/FK column the tables share. ON table1.employeeid = table2.employeeid
Use AS
to give a nickname to distinguish them.
Use nickname.column in the SELECT
statement
Select junior.Name AS Employee
FROM Employee as junior, Employee as manager
WHERE manager.Id = junior.ManagerId AND junior.Salary > manager.Salary
WHERE
- Filter rows using custom rules
a.column = b.column
Filter rows where 2 columns have the same value.
LIKE
- Match row values to a string, similar to regular expressions.
%
as placeholder for any characters._
as placeholder for a single character[aeiou]
to represent a single characterWHERE name LIKE %iva
- Only include rows where name value starts with “iva”.LIKE %iva%
- Contains “iva”LIKE %van
- Ends with “van”LIKE S___
- Starts with “S”, then followed by 3 characters.IN
- Value must be in the given set of possible values.
WHERE first_name IN ('Laura', 'Adam', 'Mike')
;NOT
- Combine with IN
or LIKE
other keywords. Include everything that doesn’t satisfy your rule.
SELECT MAX(Salary) as SecondHighestSalary
FROM Employee
WHERE Salary NOT IN (
SELECT MAX(Salary)
FROM Employee
)
AND
- Require multiple rules to be satisfied.
OR
- Require one of several rules to be satisfied.
LIMIT
- Filter the top N rows
SELECT FROM col1 LIMIT 5
OFFSET
to skip N rows before applying LIMIT
LIMIT 1 OFFSET 3
- Show only the 4th row.ORDER BY
- Sort selection table by one column
ASC
or DESC
for sort order.SELECT * FROM table ORDER BY name ASC
- Sort all rows by value in name column, A→ZJoins are used to merge columns from two different tables together into one table.
3 main types of Joins
![JoinDiagram.jpg](<https://s3-us-west-2.amazonaws.com/secure.notion-static.com/c68b6d8b-034b-40e2-ab5e-b1416c3592e5/JoinDiagram.jpg>)
2 Special Joins
SELECT FROM
the same table twiceSELECT
first_name,
last_name,
first_name || ' ' || last_name full_name -- Newly created column: full_name
FROM users
column1 || ' ' || column2
is the same as string1 + " " + string2