1

I have a table that has 3 columns.

id | name | score | approve
--------------------
1  | foo  |  90   |   f
2  | foo  |  80   |   t

I want to

SELECT id WHERE name='foo'

with these conditions:

  1. if approve is True, then return that one (only one will be true for the same name)

  2. otherwise select the one that has highest score

I was looking into IF...ELSE but cannot even come up with a query that executes (despite a working one...)

How to set up the query command for this type of queries?

2
  • what if there are more users with the same highest score? Commented Oct 17, 2018 at 20:23
  • @RadimBača good question. In this case we can choose just one of them. Doesn't have to be random so it can always return the same person. We don't expect this to happen though as the score is actually going to 8 digits after decimal instead of an int Commented Oct 17, 2018 at 20:25

1 Answer 1

1

In SQL, you can often use some logic by defining the right order and limit:

select id
from my_table
where name = 'foo'
order by approve desc, score desc
limit 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.