Learn Node SQLite

Serial Queries

By default, the commands we issue to our database run in parallel. Every request we make gets sent to the database — which processes them all as quickly as it can, regardless of the order in which they got sent. This is usually a good thing because it means that we can get results faster, but in our case, we don't want to try to INSERT data into a table that hasn't been created yet. One way to avoid this issue is to write all of our code in nested callbacks, let's take a look at how that might look:

db.run("DROP TABLE Dog", error => {
  db.run("CREATE TABLE Dog", error => {
    db.run("INSERT INTO Dog (breed, name, owner, fur_color, fur_length) VALUES ('Dachschund', 'Spike', 'Elizabeth', 'Brown', 'Short')", error => {

As you can see, with this technique every command gets increasingly indented, which becomes a bit of an eyesore if we want to guarantee multiple things run chronologically. Another way of accomplishing this task is by using the db.serialize() method like so:

db.serialize(() => {                                                                                                                          
  db.run("DROP TABLE Dog");
  db.run("CREATE TABLE Dog");
  db.run("INSERT INTO Dog (breed, name, owner, fur_color, fur_length) VALUES  ('Dachshund', 'Spike', 'Elizabeth', 'Brown', 'Short')");

In the previous example, we explicitly tell the database to:

  • First, remove the table Dog if it exists.
  • Second, create an empty table named Dog.
  • Third, insert a new row into the table. In exactly that order without running any command until the previous one completes.
Community Forums
Get help and ask questions in the Codecademy Forums
Report a Bug
If you see a bug or any other issue with this page, please report it here.