In today's SQL session, we will explore GROUP BY, HAVING, subqueries, JOINs, and other advanced SQL topics. Let's dive into each topic with explanations, examples, and best practices.
1οΈβ£ GROUP BY and HAVING
πΉ GROUP BY
- Used to group rows with the same values in specified columns.
- Often used with aggregate functions (
COUNT(),SUM(),AVG(), etc.).
πΉ HAVING vs. WHERE
| Feature | WHERE | HAVING |
|---|---|---|
| Use Case | Filters rows before grouping | Filters grouped results |
| Works With | Columns and raw data | Aggregated data (SUM(), COUNT()) |
| Example | SELECT * FROM employees WHERE salary > 5000; |
SELECT department, SUM(salary) FROM employees GROUP BY department HAVING SUM(salary) > 50000; |
β
Example: Using GROUP BY and HAVING
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
βοΈ Explanation: Groups employees by department and filters those with more than 10 employees.
2οΈβ£ Subqueries (Nested Queries)
A subquery is a SQL query inside another query.
πΉ Types of Subqueries
- Scalar Subquery β Returns single value
- Multi-row Subquery β Returns multiple rows
- Correlated Subquery β Uses outer query values inside subquery
β Example: Finding employees who earn more than the average salary
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
βοΈ Explanation: The subquery finds the average salary, and the outer query selects employees earning above that.
3οΈβ£ LIMIT and OFFSET
πΉ LIMIT
- Restricts the number of rows returned.
- Useful for pagination and top results queries.
πΉ OFFSET
- Skips a number of rows before starting to return results.
- Used with
LIMITfor pagination.
β Example: Fetch top 5 highest salaries
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 5;
β Example: Fetch next 5 highest salaries (Pagination)
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 5 OFFSET 5;
βοΈ When to use?
- Use LIMIT when fetching a specific number of rows.
- Use OFFSET when implementing pagination (e.g., showing page 2 results).
βοΈ When NOT to use?
- If performance is critical, avoid high OFFSET values, as it scans many rows before returning results.
4οΈβ£ IN and NOT IN Operators
Used for filtering results based on a list of values.
β Example: Employees in specific departments
SELECT name FROM employees
WHERE department IN ('HR', 'Finance', 'IT');
βοΈ IN selects employees from HR, Finance, and IT departments.
β Example: Employees NOT in specific departments
SELECT name FROM employees
WHERE department NOT IN ('HR', 'Finance', 'IT');
βοΈ NOT IN excludes employees from HR, Finance, and IT departments.
βοΈ When to use?
- Use
INfor short lists of known values. - Avoid
INfor large lists; useJOINorEXISTSfor better performance.
5οΈβ£ Naming Rules in PostgreSQL
πΉ Table Naming Rules
- Must start with a letter or underscore (_).
- Can contain letters, numbers, and underscores.
-
Cannot use PostgreSQL reserved keywords (e.g.,
SELECT,TABLE).
β
Valid Table Names: employees, _user_data, customer_orders
β Invalid Table Names: 123table, select, table-name
6οΈβ£ When Can We Join Tables?
β You can join tables when:
- They have a common column (Primary Key & Foreign Key).
- Data is related (e.g.,
customersandorders).
πΉ Example: INNER JOIN
SELECT customers.name, orders.order_id
FROM customers
INNER JOIN orders ON customers.customer_id = orders.customer_id;
7οΈβ£ What if Two Tables Have No Common Column?
If two tables donβt have a common column, we cannot use JOINs directly. Instead, we can:
β Use CROSS JOIN (Cartesian Product)
SELECT employees.name, departments.department_name
FROM employees
CROSS JOIN departments;
βοΈ Generates all possible combinations of employees and departments.
β Use UNION (Combine Results from Two Tables)
If tables have similar structures, use UNION:
SELECT name FROM employees
UNION
SELECT name FROM managers;
βοΈ Combines employee and manager names without duplicates.
π₯ Summary of Todayβs SQL Topics
β
GROUP BY & HAVING β Used for grouping and filtering aggregated data.
β
Subqueries β Nested queries used for advanced filtering.
β
LIMIT & OFFSET β Control result pagination.
β
IN & NOT IN β Filter results based on lists.
β
Naming Rules β Follow PostgreSQL naming conventions for tables, columns, and databases.
β
JOINing Tables β Only possible if thereβs a common column. If not, use CROSS JOIN or UNION.
Top comments (0)