Finding Flowers By Color Query Explanation

The Complete Query

SELECT flower_varieties.variety, flowers.color, flowers.stem_length
FROM flowers
JOIN flower_varieties ON flowers.variety_id = flower_varieties.id
WHERE flowers.color IN ('pink', 'purple')
ORDER BY flower_varieties.variety, flowers.color, flowers.stem_length;
    

Breaking Down the Query

Tables Used

The query uses two tables from our database:

How the JOIN Works

The JOIN operation connects the flowers table with the flower_varieties table using the variety_id as a bridge:

Real World Analogy

Think of it like a library catalog system:

Query Components

  1. SELECT: Specifies which columns we want
  2. FROM flowers: Starts with the flowers table
  3. JOIN flower_varieties: Connects with the varieties table
  4. ON flowers.variety_id = flower_varieties.id: Specifies how tables connect
  5. WHERE flowers.color IN ('pink', 'purple'): Filters for specific colors
  6. ORDER BY: Sorts results in a specific order

Why We Use Full Table Names

Using full table names (flowers.color instead of just color) provides several benefits:

Sample Data Flow

Let's see how data flows through this query:

1. Start with flowers table:
   id | color  | stem_length | variety_id
   1  | pink   | long       | 1
   2  | purple | long       | 1

2. JOIN with flower_varieties:
   variety_id | color  | stem_length | id | variety
   1         | pink   | long        | 1  | Carnation
   1         | purple | long        | 1  | Carnation

3. After WHERE clause (pink or purple):
   variety    | color  | stem_length
   Carnation | pink   | long
   Carnation | purple | long

4. After ORDER BY:
   variety    | color  | stem_length
   Carnation | pink   | long
   Carnation | purple | long
    

Common Issues and Solutions

Alternative Approaches

While our solution uses an INNER JOIN, here are other valid approaches:

-- Using subquery
SELECT v.variety, f.color, f.stem_length
FROM flowers f,
     (SELECT id, variety FROM flower_varieties) v
WHERE f.variety_id = v.id
  AND f.color IN ('pink', 'purple')
ORDER BY v.variety, f.color, f.stem_length;

-- Using LEFT JOIN (would include varieties with no matching flowers)
SELECT flower_varieties.variety, flowers.color, flowers.stem_length
FROM flower_varieties
LEFT JOIN flowers ON flowers.variety_id = flower_varieties.id
WHERE flowers.color IN ('pink', 'purple')
ORDER BY flower_varieties.variety, flowers.color, flowers.stem_length;