PHP, Snippets, Web Development Blog

LEFT JOIN and RIGHT JOIN in mysql

Use LEFT JOIN when you want to return all rows from left table regardless of whether they have any associated rows on right table.

Use RIGHT JOIN when you want to return all rows from right table regardless of whether they have any associated rows on left table.

SELECT 
  users.`firstname`,
  pets.`nickname`
FROM `users`
LEFT JOIN `pets` 
ON users.`id` = pets.`user`";

The above query will return all rows in users table regardless of whether they have any pets associated with them or not.

[tags]mysql, sql, join, left join, right join[/tags]

Career Guide for Software Developers