Following the process of normalization - a well designed Relational database will usually have more than one table with related data in it. The reason for normalization is to separate data into tables, representing single entities, to prevent data redundancy. These tables will be linked together using foreign keys. When we want to correlate data from multiple tables we can use the join key word to do so. The following is a brief description of three commonly used joins: left, inner and right.
LEFT JOIN Will return all the rows in the table on the left of the join. It will then attempt to get any matching rows in the right table. If it can’t match a particular row, it will return NULL.
RIGHT JOIN This will do the opposite of the above, by returning all the rows in the table in the right of the join and then attempt to get matching rows from the table in the left. This join is less commonly used because you can simple swap the left and right tables in a left join to have the same effect.
INNER JOIN This join will return no NULL values. It will only return complete rows. That is, where a row in the left table matches a row in the right table. If there is a row in the left table but no matching row in the right table, the left row is not returned.
Example database tables
|8||boxer||The Boxer is ..|
|2||poodle||The poodle is..|
|3||labrador||The labrador is..|
|4||cavalier||The Cavalier is..|
Left join of tables Left join results
You will notice that in every row we have the Dog data. This is because the left join will return data from this table whether or not there is a match with rows in the table dog_type or the table health. For the top row “Bengy” - because it could not match any rows from dog_type it returns null values for those columns, next it did match a row from the health table and display the data.
Inner join of tables Inner join results
In this case only one row was returned. This is because an inner join will only return matching rows, and because we have two inner joins in our query there must be a match in both right tables for the query to return a resulting row.