Essential SQL Cheat Sheet: Quick Reference for Data Analysts
For this practice we are going to use WORLD database from mysql.com. you can download from here: https://dev.mysql.com/doc/index-other.html
1. Data Retrieval (SELECT Statements)
Used to fetch data from a database.
- Basic SELECT: Retrieves all columns from a table
select * from city/country/countrylanguage;
- SELECT Specific Columns: Fetch only specific columns.
SELECT column1, column2 FROM table_name;
select Name from city; will give you the below result:
2. Filtering Data (WHERE Clause)
Used to filter records based on conditions.
- WHERE Clause: Retrieve rows based on conditions.
- WHERE with Multiple Conditions: Use
AND
/OR
to combine conditions.
3. Sorting Data (ORDER BY)
Sort query results by one or more columns in ascending or descending order.
- Ascending Order:
- Descending Order:
4. Limiting Rows (LIMIT)
Retrieve only a specific number of rows.
- Limit the Number of Results:
5. Aggregate Functions
Used to perform calculations on data. Perform a calculation on a set of values, and return a single value.
- COUNT: Counts the number of rows.
- SUM: Adds up the values in a column.
- AVG: Calculates the average value.
6. Grouping Data (GROUP BY)
Group rows with similar values and perform aggregation.
- GROUP BY with Aggregate Functions:
7. Filtering Groups (HAVING)
Filter grouped data after using GROUP BY
.
- Using HAVING to Filter Aggregated Results:
8. Joining Tables (JOIN)
Combine rows from two or more tables.
- INNER JOIN: Returns rows when there’s a match in both tables.
- LEFT JOIN: Returns all rows from the left table and matched rows from the right table.
- RIGHT JOIN: Returns all rows from the right table and matched rows from the left table.
b.Name
is NULL
), effectively performing the left exclusive join.Self Join: A self join is used when you need to join a table to itself, usually to compare rows within the same table. It can be helpful in a variety of situations where relationships within the same dataset need to be compared.
9. Inserting Data (INSERT INTO)
Add new rows into a table.
- Insert Single Row:
10. Updating Data (UPDATE)
Modify existing rows in a table.
- Update a Specific Row:
11. Deleting Data (DELETE)
Remove rows from a table.
- Delete Specific Rows:
12. Table Creation (CREATE TABLE)
Create a new table with specific columns and data types.
- Basic Table Creation:
13. Table Alteration (ALTER TABLE)
Modify the structure of an existing table. (To change the schema)
- Add a New Column:
- Drop a Column:
14. Indexing
Indexes improve the speed of data retrieval.
- Create Index:
15. Subqueries
Queries within queries.
- Subquery in SELECT:
16. Aliasing
Use aliases to simplify queries.
- Column Alias:
- Table Alias:
17. Distinct Values (DISTINCT)
Select only distinct (unique) values.
- Distinct in SELECT:
18. Set Operations
Combine the results of two or more SELECT queries.
- UNION: Combines the results of two queries and removes duplicates.
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2; - UNION ALL: Combines the results of two queries and keeps duplicates.
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;
19. Conditional Statements (CASE)
Return values based on conditions.
- CASE Statement:
SELECT column1,
CASE
WHEN condition THEN 'result1'
ELSE 'result2'
END
FROM table_name;
20. Data Export
Export query results to a file.
- Export Data to CSV:
SELECT * FROM table_name INTO OUTFILE '/path/to/file.csv'
FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';
21. Date Functions
Work with dates and times.
- Get Current Date:
SELECT CURRENT_DATE;
- Format Date:
SELECT DATE_FORMAT(column, '%Y-%m-%d') FROM table_name;
22. Handling NULL Values
Work with NULLs in your queries.
- Check for NULL:
SELECT * FROM table_name WHERE column IS NULL;
- Replace NULL with a Value:
SELECT IFNULL(column, 'default_value') FROM table_name;
23. String Functions
Manipulate text data.
- Concatenate Strings:
SELECT CONCAT(column1, ' ', column2) FROM table_name;
- Substring Extraction:
SELECT SUBSTRING(column, 1, 5) FROM table_name;
24. Data Type Conversion
Convert between data types.
- Cast to a Specific Type:
SELECT CAST(column AS datatype) FROM table_name;
25. Transactions
Manage multiple SQL operations in a single transaction.
- Start a Transaction:
START TRANSACTION;
- Commit Changes:
COMMIT;
- Rollback Changes:
ROLLBACK;