1

I need to know how to write a SQL statement for the following senario;

I have a table, which consist of 2 columns. ParentName and No_Of_Kids. so say we have a record called parent A and parent A had 2 kids.(in 2008)

Now in 2011 Parent A has got another 3 kids, so i need to update this table, to say Parent A has 5 kids altogether.

UPDATE ParentKidsTable
SET parentName=value, No_Of_kids=??? // (how to write the SQL no. of Kids in 2008 + no. of kids in 2011)
WHERE parentName=some_value
1
  • 1
    Why are you setting parentName again? Commented Jan 6, 2012 at 11:01

3 Answers 3

2

The general statement to update a table is:

UPDATE table
SET field = 'newValue'
WHERE otherfield = 'condition'

So in your case this makes:

UPDATE ParentKidsTable
SET No_Of_Kids = 5
WHERE ParentName = 'some_value'

This would update the No_Of_Kids to 5 where the ParentName equals some_value. Make sure you put the String literals between apostrophes.

If you want to add a certain number of kids to the yet existing number you can do:

UPDATE ParentKidsTable
SET No_Of_Kids = (No_Of_Kids + 3)
WHERE ParentName = 'some_value'

which is basically short (and better) for:

UPDATE ParentKidsTable
SET No_Of_Kids = ((SELECT No_Of_Kids 
                  FROM ParentKidsTable 
                  WHERE ParentName = 'some_value') + 3)
WHERE ParentName = 'some_value'
Sign up to request clarification or add additional context in comments.

3 Comments

Or SET No_Of_Kids = No_Of_Kids + 3
No, i only know the number of kids in 2011 (which is 3), so i have to add the previous 2 kids with the new kids (3), and update it as 5. how can i do this ?
Actually i want to add a Value to a previously saved value. 2+3=5
2

To increment number of kids:

UPDATE ParentKidsTable
SET No_Of_Kids = No_Of_Kids + 3
WHERE ParentName = 'some_value'

Comments

1

I'm assuming that you're looking for the generic case of adding N kids, so you don't have to look up the value No_Of_Kids first in which case you can do:

UPDATE ParentKidsTable
SET No_Of_Kids = No_Of_Kids + 3
WHERE ParentName = 'some_value'

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.