SQL Cheat Sheet
SQL Cheat Sheet
Creating and managing databases in SQL involves various commands and concepts that handle
the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for
essential SQL operations, offering a practical reference for tasks ranging from database creation to advanced data
handling techniques.
It includes fundamental SQL commands like CREATE DATABASE and DROP DATABASE, data manipulation commands
such as INSERT INTO and UPDATE, as well as querying techniques using SELECT, WHERE and aggregate functions.
Table of Content
SQL Operator
Constraints in SQL
Joins in SQL
SQL Functions
Subqueries in SQL
Views in SQL
Indexes in SQL
Transactions in SQL
Explore this section to get hands on all the cheat sheet that help you in order to create a database in SQL.
USE company;
This command selects the database named “company” for further operations.
This command deletes the database named “company” and all its associated data.
Here in this SQL cheat sheet we have listed down all the cheat sheet that help to create, insert, alter data in table.
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
This command creates a table named “employees” with columns for employee ID, first name, last name, department,
and salary. The employee_id column is set as the primary key.
VALUES
This command inserts sample data into the “employees” table with values for employee ID, first name, last name,
department, and salary.
This command adds a new column named “new_column” of integer type to the existing “employees” table.
This command deletes the entire “employees” table along with all its data.
Explore this section to get the cheat sheet on how to use select, distinct and other querying data in SQL.
This query will retrieve all columns from the employees table.
This query will return unique department names from the employees table.
This query will return employees whose salary is greater than 55000.00.
12. LIMIT: Limit The Number Of Rows Returned In The Result Set
This query will limit the result set to the first 3 rows.
13. OFFSET: Skip A Specified Number Of Rows Before Returning The Result Set
This query will skip the first 2 rows and return the rest.
14. FETCH: Retrieve A Specified Number Of Rows From The Result Set
This query will fetch the first 3 rows from the result set.
SELECT
first_name,
last_name,
CASE
ELSE 'Low'
END AS salary_category
FROM employees;
This query will categorize employees based on their salary into ‘High’, ‘Medium’, or ‘Low’.
Get a cheat sheet on how to update or manipulate data in SQL by exploring this section.
UPDATE employees
WHERE employee_id = 1;
This query will update the salary of the employee with employee_id 1 to 55000.00.
WHERE employee_id = 5;
This query will delete the record of the employee with employee_id 5 from the employees table.
This query will retrieve all employees who work in the IT department.
This query will retrieve all employees whose first name starts with ‘J’.
This query will retrieve all employees who work in the HR or Finance departments.
21. BETWEEN: Match Values Within A Specified Range
This query will retrieve all employees whose salary is between 50000 and 60000.
This query will retrieve all employees where the department is not assigned (NULL).
This query will retrieve all employees sorted by salary in descending order.
SQL Operator
Here in this section we have added a cheat sheet for SQL Operators. So, explore and learn how to use AND, OR, NOT
and others oprtators.
This query will retrieve employees who work in the IT department and have a salary greater than 60000.
25. OR: Specifies Multiple Conditions Where Any One Of Them Should Be True
This query will retrieve employees who work in either the HR or Finance department.
This query will retrieve employees who do not work in the IT department.
This query will retrieve employees whose first name starts with ‘J‘.
This query will retrieve employees who work in the HR or Finance departments.
This query will retrieve employees whose salary is between 50000 and 60000.
This query will retrieve employees where the department is not assigned (NULL).
31. ORDER BY: Sorts the Result Set in Ascending or Descending Order
This query will retrieve all employees sorted by salary in descending order.
32. GROUP BY: Groups Rows that have the Same Values into Summary Rows
FROM employees
GROUP BY department;
This query will group employees by department and count the number of employees in each department.
Get an hands in aggregation data in SQL. Here you will find cheat sheet for how to count numbers, sum of numbers
and more.
This query will find the maximum salary among all employees.
FROM employees
GROUP BY department;
This query will group employees by department and count the number of employees in each department.
FROM employees
GROUP BY department
This query will calculate the average salary for each department and return only those departments where the
average salary is greater than 55000.
Constraints in SQL
Constraints in SQL act as data quality guardrails, enforcing rules to ensure accuracy, consistency, and integrity within
your database tables.
first_name VARCHAR(50),
last_name VARCHAR(50)
);
employee_id is designated as the primary key, ensuring that each employee record has a unique identifier.
department_name VARCHAR(50)
);
first_name VARCHAR(50),
last_name VARCHAR(50),
department_id INT,
);
department_id column in the employees table is a foreign key that references the department_id column in the
departments table, establishing a relationship between the two tables.
);
43. NOT NULL: Ensures That a Column Does Not Contain NULL Values
);
first_name and last_name columns must have values and cannot be NULL.
44. CHECK: Specifies a Condition That Must Be Met for a Column’s Value
);
age column must have a value of 18 or greater due to the CHECK constraint.
Joins in SQL
Explore different join types to seamlessly merge data from multiple tables in your SQL queries.
45. INNER JOIN: Retrieves Records That Have Matching Values in Both Tables
46. LEFT JOIN: Retrieves All Records from the Left Table and the Matched Records from the Right Table
This query will retrieve all records from the employees table and only the matching records from the departments
table.
47. RIGHT JOIN: Retrieves All Records from the Right Table and the Matched Records from the Left Table
This query will retrieve all records from the departments table and only the matching records from the employees
table.
48. FULL OUTER JOIN: Retrieves All Records When There Is a Match in Either the Left or Right Table
This query will retrieve all records from both the employees and departments tables, including unmatched records.
49. CROSS JOIN: Retrieves the Cartesian Product of the Two Tables
This query will retrieve all possible combinations of records from the employees and departments tables.
In this example, the employees table is joined to itself to find employees and their respective managers based on the
manager_id column.
SQL Functions
In this section we have compiled SQL cheat sheet for SQL functions. It is used for common tasks like aggregation,
filtering, date/time manipulation, and more!
This query uses the UPPER() scalar function to convert the first_name column values to uppercase.
52. Aggregate Functions: Functions That Operate on a Set of Values and Return a Single Value
This query uses the CONCAT() string function to concatenate the first_name and last_name columns into a single
column called full_name.
This query uses the SUBSTR() function to extract the first three characters of the first_name column for each
employee. The result is displayed in a new column called short_name.
This query first concatenates the first_name and last_name columns into a single column called full_name. Then, it
uses the INSERT() function to insert the string ‘Amazing ‘ at the 6th position of the full_name column for each
employee. The modified names are displayed in a new column called modified_name.
54. Date and Time Functions: Functions That Operate on Date and Time Values
This query uses the CURRENT_DATE date function to retrieve the current date.
This query uses the SQRT() mathematical function to calculate the square root of 25.
Subqueries in SQL
This SQL cheat sheet explains how to nest queries for powerful data filtering and manipulation within a single
statement.
FROM employees
In this example, the subquery (SELECT MAX(salary) FROM employees) returns a single row containing the maximum
salary, and it’s used to filter employees who have the maximum salary.
SELECT department_name
FROM departments
In this example, the subquery (SELECT department_id FROM employees) returns multiple rows containing department
IDs, and it’s used to filter department names based on those IDs.
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE department = e.department);
In this example, the subquery (SELECT AVG(salary) FROM employees WHERE department = e.department) is
correlated with the outer query by referencing the department column from the outer query. It calculates the average
salary for each department and is used to filter employees whose salary is greater than the average salary of their
respective department.
FROM employees
WHERE department_id IN (
SELECT department_id
FROM departments
);
In this example, the subquery (SELECT department_id FROM departments WHERE department_name = ‘IT’) is nested
within the outer query. It retrieves the department ID for the IT department, which is then used in the outer query to
filter employees belonging to the IT department.
Views in SQL
Here in this SQL cheat sheet unveils how to create virtual tables based on existing data for streamlined access.
60. CREATE VIEW: Create a Virtual Table Based on the Result of a SELECT Query
SELECT *
FROM employees
This query creates a views named high_paid_employees that contains all employees with a salary greater than 60000.
Indexes in SQL
Speed up your SQL queries with our Indexes Cheat Sheet! Learn how to create and optimize indexes to dramatically
improve database performance.
This query creates an index named idx_department on the department column of the employees table.
63. DROP INDEX: Remove an Index
Transactions in SQL
Learn how to manage groups of database operations as a single unit for reliable data updates.
BEGIN TRANSACTION;
COMMIT;
This statement saves all changes made during the current transaction.
ROLLBACK;
This statement undoes all changes made during the current transaction.
In the last we have complied all the imprtant queries under the one advanced SQL cheat sheet.
67. Stored Procedures: Precompiled SQL Statements That Can Be Executed with a Single Command
BEGIN
END;
This query creates a stored procedure named get_employee_count that returns the count of employees.
68. Triggers: Automatically Execute a Set of SQL Statements When a Specified Event Occurs
BEGIN
END;
This query creates a trigger named before_employee_insert that sets the creation_date column to the current date
and time before inserting a new employee record.
69. User-defined Functions (UDFs): Custom SQL Functions Created by Users to Perform Specific Tasks
END;
This query creates a user-defined function named calculate_bonus that calculates the bonus based on the salary.
70. Common Table Expressions (CTEs): Temporary Result Sets That Can Be Referenced Within a SELECT, INSERT,
UPDATE, or DELETE Statement
WITH high_paid_employees AS (
This query uses a common table expression named high_paid_employees to retrieve all employees with a salary
greater than 60000.
Conclusion
This SQL cheat sheet provide a wide range of commands and techniques essential for effective database management
and data manipulation. By familiarizing yourself with these SQL operations, you can streamline your workflow,
optimize performance and ensure data integrity across your database. Whether you are creating databases, modifying
data, querying information, or implementing advanced features like triggers and stored procedures, this guide
provides the necessary tools to handle various SQL tasks with confidence