Question

I have searched for this but couldn't find any answer on this particular matter. For my Databases class we have to make a demonstration of the use of some SQL functions on a database we have created. One of those functions is MIN(), while the other is MAX(), among others.

What's happening to me is that when running the command SELECT nome AS mais_barato FROM equipamento HAVING MIN(preço); (names are in portuguese: nome=name, mais_barato=cheaper, equipamento=equipment, preço=price) the output is the following:

+-------------+
| mais_barato |
+-------------+
| ZON Hub     |
+-------------+

Where one would expect (the original table is further bellow, for you to see for yourselves what would be expected):

+-------------+
| mais_barato |
+-------------+
| Modem       |
+-------------+

What is wrong in the statement? When running the SELECT nome AS mais_caro FROM equipamento HAVING MAX(preço); (mais_caro=more_expensive) the output is the same as the one using MIN(preço).

The original table equipamento is (cod is the unique code associated with the equipments):

+-----+----------+--------+
| cod | nome     | preço  |
+-----+----------+--------+
| 152 | ZON Hub  |    120 |
| 228 | PowerBox |    100 |
| 444 | Fibra    |    200 |
| 673 | NetGear  |     70 |
| 779 | Modem    |     50 |
+-----+----------+--------+

I am using mysql Ver 14.14 Distrib 5.5.34, for debian-linux-gnu (i686) using readline 6.2 on Ubuntu 13.10

Thank you very much

Was it helpful?

Solution

Just a wild guess: MySQL is incorrectly interpreting MIN() and MAX() as booleans here.

Your question isn't entirely clear, but I'm guessing you simply want an order by clause:

SELECT nome AS mais_caro
FROM equipamento
ORDER BY preço DESC limit 1

If not, look into subqueries, e.g.:

SELECT nome AS mais_caro
FROM equipamento
WHERE preço = (SELECT MAX(preço) FROM equipamento);

Btw, to learn SQL, you really ought to look into PostgreSQL. The manual is beyond excellent, and it's extremely strict, unforgiving, and informative, when it comes to errors such as the one you did:

denis=# create table test (id serial);
CREATE TABLE
denis=# select id from test having min(id);
ERROR:  argument of HAVING must be type boolean, not type integer
LINE 1: select id from test having min(id);
                                   ^

MySQL, in contrast and as you've found out, accepts a lot of garbage in unless you enable strict mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top