0

How do i actually use if else with update in sql? I have tried a lot of ways but it still doesnt work.

This is the question:

Add a column called ‘Status’ to a relational table Customer and use one UPDATE statement to fill the column with information about the customer status. Mark ‘Y’ if the customers had placed any orders otherwise ‘X’ will be initialised.

I am stuck at the update part.

UPDATE CUSTOMER
IF(customer.customerID IN (SELECT customerID from invoice))
( set status = 'y' )
else
( set status = 'x' )
endif
where status is null;
1
  • you need to use case statement in the update Commented Jun 5, 2014 at 13:41

3 Answers 3

2

You could use a case statement

UPDATE CUSTOMER
SET Status = CASE WHEN CUSTOMER.CUSTOMERId IN (SELECT customerID from invoice)
    THEN 'y'
    ELSE 'n' END
where status is null;
Sign up to request clarification or add additional context in comments.

2 Comments

My answer is a very simplistic one. Easy to understand for someone who's new to SQL. But this is the correct answer. This is the right way of going about this. This is a perfect example of the use of SQL Case statements and how it helps in condensing SQl queries.
+1 Upvoted this. Also, OP should be marked this as the right answer.
2

What you want to do is a case statement because that's the closest you can get to an IF in sql.

update customer
set status
  case
    when exists (select customerID from Customer where CustomerID in (select customerID from invoice) 
    then
        'y'
    else
        'x'
  end
where stats is null

Comments

0
DECLARE      @customerID INT
SET          @customerID = (SELECT       CustomerID
                            FROM         Invoice 
                            WHERE        CustomerName = 'some_customer_name')

IF (@customerID = NULL)
BEGIN
   UPDATE     Customer
   SET        Status = 'Y'
   WHERE      CustomerID = @customerID
END
ELSE
BEGIN
   UPDATE     Customer
   SET        Status = 'x'
   WHERE      CustomerID = @customerID
END

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.