24

I Have a table of bike details and I want to add different prices to different bike types using SQL queries, but what I have gives me a syntax error:

INSERT INTO bike (full_day)
VALUES (10)
WHERE bike_type = 'mens_hybrid';

What is wrong with this code?

1 Answer 1

68

An INSERT statement is only for creating completely new records, not for populating data into existing ones. What you need is an UPDATE statement, which updates an existing record:

UPDATE bike SET full_day = 10 WHERE bike_type = 'mens_hybrid';

(Note: below is an earlier version of this answer, from before it was clear to me what the original poster was trying to do. I'm leaving it here because multiple people who originally answered this question did not seem to notice the problem with writing INSERT ... VALUES (...) WHERE, which makes me think that this explanation might be useful to some people coming across this question.)


That statement doesn't make sense. An INSERT can't take a WHERE clause, because WHERE refers to existing records, and an INSERT creates new ones.

(To forestall potential confusion: there exists such a thing as INSERT INTO ... SELECT ..., where the records to insert are determined by a SELECT query rather than by a VALUES expression, and in that case the SELECT query can, of course, have a WHERE clause. But in no case does the WHERE clause belong to the INSERT statement directly.)

Sign up to request clarification or add additional context in comments.

5 Comments

How would I add the value 10 to that column only where the bike model is mens mountain bike
@Matt: I don't know if you saw, but I edited my answer; everything from the word Update onward is new, and I think it's what you're looking for. If it isn't, then you might have to post some sample data, showing how your table will look before and after you run the statement.
@Matt: Also, what DBMS are you using? (MySQL? PostgreSQL? Oracle? SQL Server?) I can add links to the relevant documentation, which you'll probably find helpful, but the detailed rules depend a bit on the DBMS, so I don't want to post (say) Oracle docs if you're using (say) MySQL.
we must have edited at the same time, this is great thanks, btw I am using PostgreSQL
@Matt: You're welcome! I've edited the answer to link to the relevant PostgreSQL documentation pages: postgresql.org/docs/8.4/static/sql-insert.html for INSERT, postgresql.org/docs/8.4/static/sql-update.html for UPDATE.

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.