1

I'm trying to query from an SQL table. I am having issues getting an if statement to work for a conditional thing I'm trying to achieve in the query.

If the deaths of the player = 0, I want the kd column (ratio) to be equal to kills, not NULL. Here is my current query, I have no clue how to take this.

SELECT name, time, map, kills, deaths, kills/deaths AS kd 
FROM history;

Logic I want:

  • if deaths = 0: kills/deaths = kills

2 Answers 2

2

You can use a case expression:

SELECT name, time, map, kills, deaths,
       (case when deaths = 0 then kills else kills/deaths end) as kd 
FROM history;

Normally, to avoid divide by zero, it is sufficient for the result to be NULL. If this is what you really want, then NULLIF() is a better solution:

SELECT name, time, map, kills, deaths,
       ( kills / NULLIF(deaths, 0) ) as kd 
FROM history;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. The case expression was exactly what I'm looking for.
0

All you need is a WHERE clause you know.

And to make better statements when you insert in your database.

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.