r/ProgrammerHumor • • Aug 01 '22

>>>print(“Hello, World!”)

Post image
60.8k Upvotes

5.7k comments sorted by

View all comments

13

u/[deleted] Aug 01 '22

I'm also well aware of the issues in it. Exam question I ran across.

SELECT customer#, SUM(quantity*retail) "Total Sales"
FROM orders JOIN orderitems ON orders.order# = orderitems.order#
JOIN books ON orderitems ON orderitems.ISBN = books.ISBN
HAVING orderdate = '02-APR-09'
GROUP BY customer#;

35

u/a-slice-of-toast Aug 01 '22

code if it were to work in retail

11

u/BlendeLabor Aug 01 '22

Fuck you, why is this so right

Don't know programming my ass

4

u/Arctos_FI Aug 01 '22

Had to scroll pretty far before saw any sql

1

u/the-software-man Aug 01 '22

if that the 2nd of April, 2009 or the 9th of April 2002?

4

u/[deleted] Aug 01 '22

DD MM YR

1

u/[deleted] Aug 01 '22

Yes.

1

u/ChuckFina74 Aug 02 '22

HAVING?

1

u/koos_die_doos Aug 02 '22

Yes, but HAVING is always after the GROUP BY.

Having filters grouped records, WHERE filters records before grouping is applied.

1

u/DXPower Aug 02 '22

I'm merely a C++ programmer with a passing knowledge of SQL. What's wrong here?

1

u/koos_die_doos Aug 02 '22 edited Aug 02 '22

SELECT customer#, SUM(quantity*retail) "Total Sales"FROM orders JOIN orderitems ON orders.order# = orderitems.order#JOIN books ON orderitems ON orderitems.ISBN = books.ISBNHAVING orderdate = '02-APR-09'GROUP BY customer#;

Too much to mention, but I can try:

  1. Having clause must always be after the group by clause, it looks as if it should be a WHERE

  2. JOIN books ON orderitems ON orderitems.ISBN -> ON something ON is not valid syntax.

  3. '02-APR-09' is not a deterministic date format, it's not an end of the world error, but you don't know what date SQL will use without knowing something about the server setup.

  4. The # in customer# and order# is legal, but rarely found in production databases. So much so that I had to check, and I've been working with SQL for 20 years, I have never seen a field name with a #, I've seen field names with spaces though.

  5. orderdate is not included in the GROUP BY, so you can't use it in the HAVING clause.

  6. The join on books is present but never used, so it is not serving any useful function.

It's probably supposed to be something like this:

SELECT customer#, SUM(quantity*retail) "Total Sales"  
FROM orders 
		JOIN orderitems ON orders.order# = orderitems.order#  
		JOIN books ON orderitems.ISBN = books.ISBN  
WHERE orderdate = '02-APR-09'
GROUP BY customer#;

1

u/TheKeyboardKid Aug 02 '22

Does this attempt to calculate the total sales for each customer on orders placed on April 2, 2009?

1

u/koos_die_doos Aug 02 '22

Could also be April 9, 2002, depending on the SQL server's (not the client machine) settings.