Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL MAX function in non-numeric columns

Tags:

sql

select

max

As far as I understand the MAX function, it shall return a maximum value from a given column. In case of numeric values, for example a salary column, it is clear for me - and this is the only application I find in tutorials. However, I have a problem to understand how does it work in case of non-numeric columns.

My problems originates from this exercise (on sql-ex.ru)

Find out makers who produce only the models of the same type, and the number of those models exceeds 1. The table "Product" includes information about the maker, model number, and type ('PC', 'Laptop', or 'Printer'). One of the solutions to this is:

SELECT maker,        MAX(type) AS type FROM   product GROUP  BY maker HAVING COUNT(DISTINCT type) = 1        AND COUNT(model) > 1  

I don't understand the function of max - what does it count? I tried a simpler query to understand it, but it only made it more difficult.

SELECT maker,        MAX(type) AS type, COUNT(type) AS QTY FROM product GROUP BY maker ORDER BY maker 

The returned set was

maker  type      QTY A      Printer   7 B      PC        2 C      Laptop    1 D      Printer   2 E      Printer   4 

The MAX(type) seems to me to show a random value e.g. why for the maker B the result is PC and not Laptop? Why for E it is Printer and not PC?

Full Table
http://i.stack.imgur.com/gObvQ.png

like image 367
Bartias Avatar asked Sep 01 '13 12:09

Bartias


People also ask

Can you use Max on a char column?

MAX is allowed only on expressions that evaluate to built-in data types (including CHAR, VARCHAR, DATE, TIME, CHAR FOR BIT DATA, etc.).

Does SQL Max work on strings?

The MAX() function can be used on the string column.

How does Max work with text SQL?

SQL MAX() aggregate function is used to return the maximum value from the provided numerical expression or the highest value in the collating sequence from the provided character expression.

How can I get max value in SQL without using max function?

You can do that as: select MIN(-1 * col)*-1 as col from tableName; Alternatively you can use the LIMIT clause if your database supports it.


1 Answers

The functions MAX, MIN, etc. use the lexicographic order when applied to text columns. Therefore, your MAX(type) will return 'Printer' instead of 'PC' because 'Printer' is after (greater than) 'PC' in alphabetic order.

Notice that in your first query the condition HAVING COUNT(distinct type) = 1 means that there can only be a single typevalue for each group. The MAX(type) clause in the select is used because simply type can not be used in the select as it is not in the GROUP BY clause.

like image 80
trogdor Avatar answered Sep 23 '22 10:09

trogdor