UPDATESQL

Unit 1, Checking AI-written SQL · Checking AND and OR

Checking AI-written SQL: does it answer the question?

Check the AI: affordable audio and lighting

AI assistants write SQL that runs and looks right, but runs is not the same as right. Read the query clause by clause against the question: are the right columns returned, does every condition in the question appear in WHERE, and are the ones joined with OR grouped the way the question means them?

Example
-- Question: Audio products under $200
SELECT name, price
FROM products
WHERE category = 'Audio'
  AND price < 200;

Review the AI's query

Someone asked an AI assistant: List the name, category and price of every Audio or Lighting product that costs under $100. It wrote this query:

SELECT name, category, price
FROM products
WHERE category = 'Audio'
   OR category = 'Lighting'
  AND price < 100;

Does it answer the question?

  • Yes, it answers the question
  • No: it includes Audio products that cost $100 or more
  • No: it leaves out the Lighting products
Show the answer

No: it includes Audio products that cost $100 or more. AND is evaluated before OR, so the price limit only applies to Lighting. Every Audio product comes back, including the $249 headphones and the $149 speakers. The query runs without an error, which is what makes this kind of bug easy to miss.

Then fix it

Now fix the AI's query so it answers the question: Audio or Lighting products under $100.

Tables you will use: products

Try it in your browserFree, no sign-up. Your query is checked as you go.