0

I'm a SQL newbie, in that case, I want to perform an IF..THEN in SQL SELECT statement, I try to write code like this, but it returns an error syntax

Here's my code :

SELECT *,IF(total_skor <= 100 AND total_skor >= 80,"Amat Baik")
AS pred FROM rekap_nilai ORDER BY id ASC

Can you tell me what's wrong in my code? Thanks sir/madam.

  • 1
    Ya prob wanna goggle `mysql case when` – Drew Jun 18 '15 at 04:52
  • possible duplicate of [How to perform an IF...THEN in an SQL SELECT?](http://stackoverflow.com/questions/63447/how-to-perform-an-if-then-in-an-sql-select) – VJS Jun 18 '15 at 05:20

3 Answers3

1

You missing else part in your query otherwise your query ok.Below query with else part.

SELECT *,IF(total_skor <= 100 AND total_skor >= 80,"Amat Baik",NULL) AS pred FROM rekap_nilai ORDER BY id ASC;
0

The MySQL IF function takes three arguments. The first is evaluated as a boolean expression, if it evaluates to true (any non-zero integer value), the function returns the second argument, otherwise, it returns the third argument.

Your IF is missing a third argument, a value to return when the boolean expression does not evaluate to TRUE.

This can be any expression, including a literal empty string or NULL keyword, whatever you want to return.

    IF(total_skor <= 100 AND total_skor >= 80,'Amat Baik','foo')
                                                         ^^^^^^

NOTES:

Your first argument could also be re-written using a BETWEEN comparison, e.g.

    IF(total_skor BETWEEN 80 AND 100, 'Amat Baik', '')
spencer7593
  • 106,611
  • 15
  • 112
  • 140
0

Use the following IF statement

SELECT *, IF (total_skor <= 100 AND total_skor >= 80,"AmatBaik",NULL)AS pred 
FROM rekap_nilai 
ORDER BY id ASC
shubhamagiwal92
  • 1,362
  • 4
  • 25
  • 47