EXERCICES ON SQL PROGRAMMING LANGUAGE
EXERCICES ON SQL PROGRAMMING LANGUAGE
Exercises on SQL
1. Basics of SQL
Write an SQL query to fetch all rows and columns from the Books table.
Write an SQL query to fetch only the Title and Author columns from the Books
table.
Write an SQL query to fetch all books published after the year 2000.
Write an SQL query to find books whose Genre is 'Science Fiction'.
Write an SQL query to fetch all books with a Price greater than 20, sorted by Price
in descending order.
Write an SQL query to find all books whose Title contains the word "Adventure"
(use the LIKE operator).
Write an SQL query to retrieve unique genres from the Books table.
4. Aggregate Functions
Write an SQL query to count the number of books in each Genre using the GROUP BY
clause.
Write an SQL query to fetch genres that have more than 2 books in the Books table
(use the HAVING clause).
6. Data Manipulation
Write an SQL query to update the Price of all books in the Science Fiction genre,
increasing it by 10%.
Write an SQL query to delete all books published before the year 1990.
Write an SQL query to add a new column Rating (Decimal) to the Books table.
7. Joins
Assume you have another table called Authors with the following columns:
o AuthorID (Primary Key, Integer)
o AuthorName (VARCHAR)
o Country (VARCHAR). Write an SQL query to fetch the Title of books along
with the Country of their authors using an INNER JOIN.
Write an SQL query to fetch all books and their authors, even if some books have no
matching authors in the Authors table (use LEFT JOIN).
8. Subqueries
Write an SQL query to fetch books whose price is greater than the average price of all
books.
Write an SQL query to find the details of the book(s) with the highest price.
Write an SQL query to fetch all authors who have written a book in the Books table.
9. Advanced Topics
Write an SQL query to create a view named ExpensiveBooks that contains all books
with a Price greater than 50.
Write an SQL query to create a stored procedure that takes a Genre as input and
returns all books belonging to that genre.
Write an SQL query to create a trigger that automatically updates the PublishedYear
of any book to the current year if it is inserted with a NULL value.
Additional Challenges
1. Write an SQL query to create a table Borrowers with the following fields:
o BorrowerID (Primary Key, Integer)
o Name (VARCHAR)
o BookID (Foreign Key referencing the Books table)
o BorrowDate (DATE). Insert sample data and write a query to fetch the details
of borrowers along with the books they borrowed.
2. Write an SQL query to simulate a library system where you calculate the overdue fee
for books borrowed for more than 30 days. Assume the fee is $1 per day.
3. Write a query to implement pagination for fetching books in batches of 3 (use LIMIT
or equivalent).
Bonus Challenge