WT - Nodesjs - SQL - Practise Session
WT - Nodesjs - SQL - Practise Session
Imagine you are developing a web application that manages a library's book
inventory. The application has a database with two tables: books and authors. The
books table has columns like id, title, author_id, published_year, and
quantity_available. The authors table has columns such as author_id,
author_name, and author_bio.
Your task is to create a Node.js server that interacts with the database using SQL
queries to perform the following operations:
1. Retrieve the list of all books in the inventory along with their authors' names.
2. Add a new book to the inventory, ensuring that the author already exists in the
authors table. If not, add the author first.
How would you structure the SQL queries in your Node.js application to achieve
these operations efficiently?
SOLUTION
1. Retrieve the list of all books in the inventory along with their authors' names:
2. Add a new book to the inventory, ensuring that the author already exists in the
authors table. If not, add the author first:
First, check if the author exists, and if not, add the author:
You are developing a blog application where users can create, view, and interact
with blog posts. The application has a database with three tables: users, posts, and
comments. The users table has columns like user_id, username, and email. The posts
table has columns such as post_id, title, content, user_id, and created_at. The
comments table has columns like comment_id, post_id, user_id, and comment_text.
Your task is to create a Node.js server that interacts with the database using SQL
queries to perform the following operations:
1. Retrieve the latest 5 blog posts, including the username of the user who
created each post.
3. Retrieve all comments for a specific blog post, including the username of the
user who posted each comment.
How would you structure the SQL queries in your Node.js application to achieve
these operations efficiently?
SOLUTION
1. Retrieve the latest 5 blog posts, including the username of the user who created each
post:
SELECT posts.post_id, posts.title, posts.content, users.username AS author, posts.created_at
FROM posts
JOIN users ON posts.user_id = users.user_id
ORDER BY posts.created_at DESC
LIMIT 5;
3. Retrieve all comments for a specific blog post, including the username of the user who
posted each comment:
SELECT comments.comment_id, comments.comment_text, users.username AS commenter
FROM comments
JOIN users ON comments.user_id = users.user_id
WHERE comments.post_id = 1;
-- Replace 1 with the post_id of the specific blog post