SQL
Select
SELECT [DISTINCT]
column_names* 1.05 AS new_salary -- gives this column the name new_salary
salary FROM
table
ORDER BY
ASC|DESC] -- defaults to ASC
colum [LIMIT 1 OFFSET 1 -- can be written as LIMIT 1,1
WHERE
BETWEEN 9000 AND 12000 AND
salary IN (8, 9) AND
department_id LIKE 'jo%' AND -- % matches anything, _ matches one character
first_name > ALL (SELECT salary FROM employees WHERE department_id = 8) AND
salary < ANY (subquery) -- equivalent to SOME
salary EXISTS(subquery) AND
year(date) BETWEEN 1999 AND 2005
Condition Syntax
= for equality
IS NULL column_name
Functions
YEAR(date)
CHAR_LENGTH(varchar)
- number of characters
Table Management
Constraints
PRIMARY_KEY
- only one exists, non nullUNIQUE,
NOT NULLCHECK(boolean_expression)
Create
CREATE TABLE table_name (
CHAR,VARCHAR(max_length),INT,DATE] [constraints]
column1 [ )
Alter
ALTER TABLE table_name
ADD new_column data_type constraints [AFTER existing_column]
DROP column_name]
[MODIFY column_name new_constraints]
[ADD CONSTRAINT constraint_name constraint (column_name)
Delete Table
DROP TABLE [IF EXISTS] table_name
Delete all Data
TRUNCATE TABLE tabl_name
Foreign Key
- A linked key between two tables
CREATE TABLE project_milestones (
columns
FOREIGN KEY (key_name)
REFERENCES other_table (key_name)
);
Case
SELECT
first_name,
last_name,
hire_date,CASE (2000 - YEAR(hire_date))
WHEN 1 THEN '1 year'
WHEN 3 THEN '3 years'
WHEN 5 THEN '5 years'
WHEN 10 THEN '10 years'
WHEN 15 THEN '15 years'
WHEN 20 THEN '20 years'
WHEN 25 THEN '25 years'
WHEN 30 THEN '30 years'
END aniversary
FROM
employeesORDER BY first_name;
Joins
- Inner join - select values in both tables
- Left join - values in the first table and both
- Full outer join - all values
Syntax:
SELECT
A.nFROM A
INNER JOIN B on B.n = A.n;
SQL vs. NoSQL
- Aggregation is easier in SQL (ex. COUNT)
- Grouping-by requires application logic in NoSQL