SQL_Cheat_Sheet
SQL_Cheat_Sheet
to ORDER BY
1. CREATE TABLE
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 VARCHAR(50),
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, salary)
VALUES (1, 'John', 'Doe', 'Sales', 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 = 'Sales';
5. Aggregation Functions
Example:
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department;
6. GROUP BY
Used to group rows that have the same values in specified columns.
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Example:
SELECT department, COUNT(employee_id) AS total_employees
FROM employees
GROUP BY department;
7. HAVING Clause
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Example:
SELECT department, COUNT(employee_id) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(employee_id) > 1;
8. ORDER BY
Syntax:
SELECT column1, column2
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Example:
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC;
You can combine WHERE, GROUP BY, HAVING, and ORDER BY to create complex queries.
Example:
SELECT department, SUM(salary) AS total_salary
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING SUM(salary) > 100000
ORDER BY total_salary DESC;
Quick Reference