SQL left join

Created By: chatGPT

SQL LEFT JOIN is a powerful operation that allows you to combine rows from two or more tables based on a related column between them. The LEFT JOIN keyword returns all records from the left table (the first table) and the matched records from the right table (the second table). If there is no match, the result is still returned with NULL values for the columns from the right table. This is particularly useful for retrieving all data from one table while displaying relevant data from another. Below, I'll illustrate how to use LEFT JOIN with an example.
SELECT employees.name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.id;
In this example, we are selecting the name of employees and their associated department_name from two tables: employees and departments. The two tables are linked by the department_id in the employees table and the id in the departments table. If an employee does not belong to any department, their department name will show as NULL.
SELECT e.name, d.department_name
FROM employees AS e
LEFT JOIN departments AS d ON e.department_id = d.id;
It's also common to use LEFT JOIN to fetch data when you are dealing with optional relationships. For instance, if you want to get all products and their corresponding categories, even if some products do not belong to any category, you can do it like this.
SELECT products.product_name, categories.category_name
FROM products
LEFT JOIN categories ON products.category_id = categories.id;
In the query above, the result will include all products from the products table and their corresponding category names from the categories table. If a product doesn’t have a category assigned, the category_name will be NULL. This demonstrates the utility in preserving all data from the left table while attempting to join relevant data from the right table.
SELECT p.product_name, c.category_name
FROM products AS p
LEFT JOIN categories AS c ON p.category_id = c.id;
Introduction And SetupSelectFromWhereJoinInner JoinLeft JoinRight JoinFull JoinOnGroup ByHavingOrder ByLimitInsert IntoValuesUpdateSetDeleteCreate TableAlter TableDrop TableCreate IndexDrop IndexUnionUnion AllIntersectExceptCaseWhenThenElseEndInBetweenLikeIs NullIs Not NullExistsNot ExistsAndOrNotAsWithDistinctCountSumAvgMinMaxCastCoalesceNullifSubstringConcatLowerUpperTrimReplaceRoundFloorCeilAbsModCurrent_dateCurrent_timeCurrent_timestamp