3

On one of my interviews I was asked how it's possible to select maximal value from DB without keyword MAX and TOP.

My answer was:

select Table.Value 
from Table 
where Table.Value >= all( select Table.Value from Table) 

But this wasn't the right one. The interviewer said that I should do it only with one select.

Any ideas ?

Thank you ;)

3
  • Possibly wants you to use row_number? MAX and TOP would both be more efficient. Also what do you mean by "one SELECT". With a CTE the SELECT keyword appears twice. Once for the definition and once to SELECT from it but it isn't really 2 SELECT operations. Commented May 5, 2011 at 12:06
  • I mean there is one "nested" select. Commented May 5, 2011 at 12:13
  • I don't find those types of interview questions useful. How often would that particular tidbit of knowledge come in useful? Commented May 5, 2011 at 13:14

5 Answers 5

6

How about;

select -min(-fld) from table


Less efficient & uglier Woops missed the single select restriction

select distinct Value from Table T
  where not exists (select Value from Table where Value > T.Value)
Sign up to request clarification or add additional context in comments.

4 Comments

Could you please explain this ?
If you have a set [1,5,9] then transform it to [-1,-5,-9] the lowest (min()) number is -9, flip the sign (-min()) to get 9 back again
The second one would be dismissed on the same grounds the OP's solution was. But the first one is a brilliant workaround!
@Andrei I think if you'd have been suggest this solution they would have hired you without any other question:). Awesome solution...
4
SELECT t1.Value
FROM atable t1
 LEFT JOIN atable t2 ON t1.Value < t2.Value
WHERE t2.ID IS NULL

Comments

2

One suggestion (if you use MySQL, I put limit also):

SELECT table.value FROM table ORDER BY table.value DESC LIMIT 1;

3 Comments

Well, I think that TOP and LIMIT are both prohibited.
@Andrei If you remove limit you will still have the first result (of multiple ones) as the highest ;). But however, you must be sure that he restricted limit also, which does not make sense to me...
I understand, but there was question only about one row.
2
SET ROWCOUNT 1

SELECT number 
FROM master..spt_values
ORDER BY number DESC

Comments

0

order the result set by the key, descending, nulls last. That makes the row with the max, first.

select the first row, and you are done.

1 Comment

How do you select the first row?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.