SQL_Cheat_Sheet_with_JOIN_and_Integrity_Constraints
SQL_Cheat_Sheet_with_JOIN_and_Integrity_Constraints
SQL_Cheat_Sheet_with_JOIN_and_Integrity_Constraints
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
...
);
Example:
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
salary DECIMAL(10, 2)
);
2. INSERT INTO
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO employees (employee_id, first_name, last_name, department_id, salary)
VALUES (1, 'John', 'Doe', 1, 50000.00);
3. SELECT
Syntax:
SELECT column1, column2, ...
FROM table_name;
Example:
SELECT first_name, last_name, salary
FROM employees;
4. WHERE Clause
Syntax:
SELECT column1, column2
FROM table_name
WHERE condition;
Example:
SELECT first_name, last_name, salary
FROM employees
WHERE department_id = 1;
5. Aggregation Functions
Example:
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;
6. JOINs
JOINs combine rows from two or more tables based on a related column between them.
Syntax:
SELECT column1, column2, ...
FROM table1
JOIN table2 ON table1.column_name = table2.column_name;
7. UNION
Use to combine the result sets of two or more SELECT queries. Removes duplicates.
Syntax:
SELECT column1, column2
FROM table1
UNION
SELECT column1, column2
FROM table2;
Example:
SELECT first_name, last_name FROM employees
UNION
SELECT first_name, last_name FROM customers;
8. Subqueries
A subquery is a query within another query, often used in SELECT, WHERE, or FROM
clauses.
9. Integrity Constraints
Integrity Constraints are used to ensure the accuracy and reliability of data in a database.
- **PRIMARY KEY**: Ensures that each row in a table has a unique identifier. A column with
the primary key constraint cannot contain NULL values.
- **FOREIGN KEY**: Enforces a link between the columns in two tables. It ensures that the
values in one table must exist in another table.
- **NOT NULL**: Ensures that a column cannot have a NULL value.
- **UNIQUE**: Ensures that all values in a column are unique.
- **CHECK**: Ensures that all values in a column satisfy a specific condition.
- **DEFAULT**: Provides a default value for a column when no value is specified.
Quick Reference