Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

SQL Cheat Sheet With Tips

Uploaded by

deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL Cheat Sheet With Tips

Uploaded by

deepak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

SQL Query Cheat Sheet with Tips

1. SELECT Statement

- Use SELECT to retrieve data from one or more columns.

- Example: SELECT column1, column2 FROM table_name;

- Tip: Avoid SELECT * unless you need all columns.

2. WHERE Clause

- Filters rows based on a condition.

- Example: SELECT * FROM table WHERE column_name = 'value';

- Tip: Use WHERE to reduce the result set for better performance.

3. AND/OR Operators

- Combine multiple conditions.

- Example: SELECT * FROM table WHERE column1 = 'value1' AND column2 = 'value2';

- Tip: Be careful when combining AND/OR to ensure proper logic in the query.

4. ORDER BY Clause

- Sort results by one or more columns.

- Example: SELECT * FROM table ORDER BY column_name ASC/DESC;

- Tip: Always use ORDER BY when displaying data to control the order of rows.

5. GROUP BY Clause

- Group rows with identical values in specified columns.

- Example: SELECT column1, COUNT(*) FROM table GROUP BY column1;

- Tip: GROUP BY is often used with aggregate functions like SUM(), COUNT(), AVG().
6. HAVING Clause

- Filter results after grouping (used with GROUP BY).

- Example: SELECT column1, COUNT(*) FROM table GROUP BY column1 HAVING COUNT(*) >

10;

- Tip: HAVING filters groups after the aggregation.

7. JOIN Operations

- Combine rows from two or more tables based on a related column.

- INNER JOIN: SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id;

- LEFT JOIN: SELECT * FROM table1 LEFT JOIN table2 ON table1.id = table2.id;

- Tip: Always use proper JOIN conditions to avoid Cartesian products.

8. DISTINCT Keyword

- Remove duplicate rows from the result.

- Example: SELECT DISTINCT column FROM table;

- Tip: Use DISTINCT when you only need unique values.

9. Aggregate Functions

- SUM(): Calculate the total sum of a column.

- COUNT(): Count the number of rows.

- AVG(): Calculate the average value.

- Example: SELECT SUM(salary), COUNT(*) FROM employees;

- Tip: Aggregate functions work on grouped data and require a GROUP BY clause.

10. Subqueries

- A query inside another query.


- Example: SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM

employees);

- Tip: Use subqueries for complex filtering that cannot be handled with a JOIN.

11. LIMIT and OFFSET

- Limit the number of rows returned or skip a number of rows.

- Example: SELECT * FROM employees LIMIT 5 OFFSET 10;

- Tip: Use LIMIT to control large result sets and avoid performance issues.

You might also like