Code Editor
Learn Node SQLite

Retrieving A Single Row

db.all() is a useful tool to fetch all the data we have that meets certain criteria. But what if we only want to get a particular row? We could do something like this:

db.all("SELECT * FROM Dog", (error, rows) => { printQueryResults(rows.find(row => === 1)); });

In this example, we fetch all the rows from a database. Doing this populates a JavaScript variable, rows, that contains the results of our SELECT statement (all the rows from the database). We use JavaScript's .find() method to find the row with an ID of 1. Then print out that row.

With a tiny database, this might be OK, but it will be a considerable and unnecessary load if the database is large in any sense. Luckily, we have a different method that will fetch a single row from a database: db.get(). See it in action:

db.get("SELECT * FROM Dog WHERE owner_name = 'Charlie'", (error, row) => { printQueryResults(row); });

Sometimes all we need to know is whether a record matching our query exists (for instance: the code above would answer the question "Does Charlie own a dog?" depending on whether or not row is undefined). Sometimes we know that there's only a single row because we are searching for a specific ID. And sometimes we only want an example of a row that would match our description. In the code above we would only print information about one dog. To accomplish this, we use db.get() instead of db.all().

It's important to note that even if multiple rows match the query, db.get() will only return a single result. In the example above, if "Charlie" owns multiple dogs, the code provided will still only print information about one dog.

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.