Posts

Showing posts with the label SQL Joins

PostgreSQL SELF JOIN, CROSS JOIN, UNION and UNION ALL: Practical SQL Guide

 These concepts are useful for SQL Developers, Data Analysts, and technical interviews. What You Will Learn What is a SELF JOIN? What is a CROSS JOIN? Difference between UNION and UNION ALL Practical SQL examples Common mistakes and interview questions 1. What Is a SELF JOIN? A SELF JOIN joins a table with itself. It is useful when records in the same table are related to each other. For example, an employee table may contain both employees and their managers. Create an Employee Table CREATE TABLE company_employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(50), manager_id INT ); INSERT INTO company_employees VALUES (1, 'Rahul', NULL), (2, 'Priya', 1), (3, 'Arjun', 1), (4, 'Sneha', 2), (5, 'Kiran', 2); Here, manager_id refers to another employee_id in the same table. Example: Display Employees and Their Managers SELECT e.employee_name AS employee, m.employee_name AS manager FROM company_employees e LEFT JOIN company...

PostgreSQL JOINs Explained: INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL OUTER JOIN

 PostgreSQL JOINs help you retrieve related data from two or more tables. They are essential for SQL developers, Data Analysts, and anyone working with relational databases. For example, a company may store employee information in one table and department information in another. JOINs allow you to combine these tables and generate meaningful reports. What You Will Learn What is a JOIN in PostgreSQL? INNER JOIN LEFT JOIN RIGHT JOIN FULL OUTER JOIN JOIN conditions and common mistakes Practical exercises and interview questions 1. Create Sample Tables We will use two tables: employees and departments. Departments table CREATE TABLE departments ( department_id INT PRIMARY KEY, department_name VARCHAR(50) ); INSERT INTO departments VALUES (1, 'Analytics'), (2, 'Finance'), (3, 'IT'), (4, 'HR'); Employees table CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(50), department_id INT ); INSERT INTO employees VALUES...