A SQL query goes to a bar, walks up to two tables, and asks…
Can I join you?
Hello, all my beginner SQL people. Below you will find a cheat sheet of basic SQL clauses to help you on your journey to becoming an expert at SQL.
SELECT
The SELECT statement will fetch all columns as conditioned in the result set.
FROM
Use the FROM statement to identify the table you want to pull from
WHERE
Use the WHERE clause to filter rows that match a certain condition
AND
Use then AND Clause declare multiple conditions that must be met. All conditions must be met to return the value.
AGGREGATE FUNCTIONS
Aggregate functions perform a calculation and return a single value of a specified condition or column.
MAX()
Use MAX() to return the largest value of a column. It takes the column name as the argument.
MIN()
Use MIN() to return the smallest value of a column. It takes the column name as the argument
COUNT()
Use to return the total number of rows that match a specific criteria
AVG()
Use AVG( ) to find the average value of a column
Aliasing
AS
Use AS to rename or reference columns or tables as an alias. AS can be helpful when referencing multiple tables or columns from different tables. AS can also rename columns when fetching them from other tables.
GROUP BY
Use when you want to group a result of an aggregate function by a certain column. This clause must go after the SELECT, FROM, and WHERE statement but before an ORDER BY or LIMIT clause.
ORDER BY
Use ORDER BY to sort the result of a query by a particular column either alphabetically or numerically. Use DESC to order the assigned column in descending order or ASC in ascending order.
- Pro-tip: by default, it will order by ASC so you don’t really need to type it.
JOIN Statements
OUTER JOIN
Use OUTER JOIN to combine rows from a different table even if the join condition is not met.
LEFT JOIN
Use LEFT JOIN to join rows from different tables where the left table is returned in the result set and if the join condition is not met then null values are used to fill in the columns from the right table.
INNER JOIN
Use an INNER JOIN clause to return the results from more than one table by joining them together with other results based on common column values specified using an ON clause.
Pro Tip: INNER JOIN is the default of a JOIN statements so you can also just type JOIN