Wednesday, August 1, 2012

left, inner, and right joins in SQL

I have some data for this schema in which Vehicle is a child of RegisteredDriver and a RegisteredDriver has zero to n Vehicles in a one-to-many relationship. A Vehicle always has one RegisteredDriver.

  • SELECT * FROM RegisteredDriver returns 400 records
  • SELECT * FROM Vehicle returns 573 records

 
 

SELECT *
FROM RegisteredDriver AS man
LEFT JOIN Vehicle AS car
ON man.RegisteredDriverId = car.RegisteredDriverId

...returns 676 rows including those for which a RegisteredDriver has no Vehicle (there are 103 of these) and including one row for each of the 573 Vehicle records.

 
 

SELECT *
FROM RegisteredDriver AS man
INNER JOIN Vehicle AS car
ON man.RegisteredDriverId = car.RegisteredDriverId

...returns 573 rows, one row for each of the 573 Vehicle records.

 
 

SELECT *
FROM RegisteredDriver AS man
RIGHT JOIN Vehicle AS car
ON man.RegisteredDriverId = car.RegisteredDriverId

...returns 573 rows, one row for each of the 573 Vehicle records. If a Vehicle could be without a RegisteredDriver then additional records for such circumstances would be included in this record set.

No comments:

Post a Comment