Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
John Grillo30,216 Points
SQL, NULL's and auto-increment -- is typing 'null' necessary?
My question is straightforward. In the review, Chalkley says that using the NULL statement can trigger auto-incrementing columns. My question is, do you have to? Maybe it's different in SQLite, but I recall being able to just INSERT INTO the columns that didn't auto-increment, omitting the ID column in his example and it handles that automatically [since it inserts into the next row].
So do I have to write NULL into those insert statements, or will it auto-increment if I omit that column altogether?
Yes, you can omit the id column from the field list and NULL from the values list. The editor accepted this:
INSERT INTO products (name, description, price) VALUES ("x", "y", 23)
Boban Talevski24,791 Points
Just to add that in case you don't specify the column names, then you need to enter NULL for the id column.
So while this passes ok
INSERT INTO actors (name) VALUES ("John Smith");
INSERT INTO actors VALUES ("John Smith");
and you would have to use NULL like this
INSERT INTO actors VALUES (NULL, "John Smith");
In an example on W3schools.com, they state that you do not have to specify a value for the "ID" column if it is auto-incrementing.
Code example from them below.
INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen');
David Corrales4,698 Points
For some reason this isn't working, would someone be able to find out why?
INSERT INTO movies (id, title, year_released, genre) VALUES (NULL, E.T. the Extra Terrestrial, 1982, Sci-Fi);
writing the id-value sure is optional yet usefull if you want to insert test data with high ids , or are manually fiddeling around with the values inside the database