Saturday, March 19, 2011

The Ice Cream Shop

Today we are going to create a database that can be used to store ice cream brands and ice cream flavors. The database should be extensible enough to allow users to search for ice cream by flavor or by the brand. When they search for flavors, it should show all the brands that offer that flavor. And if they search by brand, the system should return all flavors the brand offers.

To simplify things, I have already created the tables and the data inside of them. The queries to accomplish our tasks will be at the bottom of this post.

Download the IceCreamStore Database:

These files are scripts you can run to create the database and insert the records.


Selecting all the flavors for a specific brand:
To select all the flavors from a specific brand, we will use two techniques: inner joins and a cross reference table. A cross reference table is a table that exists 'between' two tables that creates a link for those tables. It usually holds the primary keys of the original two tables to create a relation between those tables.

To select all flavors for a specific brand:
  1. USE IceCreamStore;
  2. GO
  3. -- Select all flavors from a specific brand.
  4. SELECT F.Name AS 'Flavor Name'
  5. FROM dbo.Flavors AS F
  6. INNER JOIN dbo.xBrandsFlavors AS X
  7. ON F.flavorID = X.flavorID
  8. INNER JOIN dbo.Brands AS B
  9. ON X.brandID = B.brandID
  10. WHERE B.Name = 'Amul';

In the above query, "Amul" is the name of the brand we want to search for. The query returns all the ice cream flavors that a brand offers.

Selecting all brands that sell a particular flavor:
This query uses the same techniques as selecting the flavors for a specific brand, except it does it in reverse.

To select all brands for a particular flavor:
  1. USE IceCreamStore;
  2. GO
  3. -- Select all brands that sell a specific flavor.
  4. SELECT B.Name AS 'Brand Name'
  5. FROM dbo.Brands AS B
  6. INNER JOIN dbo.xBrandsFlavors AS X
  7. ON B.brandID = X.brandID
  8. INNER JOIN dbo.Flavors AS F
  9. ON X.flavorID = F.flavorID
  10. WHERE F.Name = 'Vanilla Ice Cream';

In the above query "Vanilla Ice Cream" is the ice cream flavor we want to search for. The query returns all the brands that offer that ice cream flavor.

No comments:

Post a Comment

I Break Code Where code gets done.
ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |