Welcome to the SQL Scenario-Based Questions lesson! In this tutorial, we'll dive deep into SQL (Structured Query Language) by solving various real-world scenarios. By the end of this lesson, you'll have a solid understanding of SQL, making you ready to work on your own projects! 💡
SQL is a language used to communicate with and manipulate databases. It's an essential skill for any developer, allowing us to create, read, update, and delete data efficiently. In this lesson, we'll explore SQL concepts from the ground up, and by the end, you'll be able to tackle more complex scenarios. 💡
Before we dive into the scenarios, let's set up a simple database to work with. In SQL, a database is a collection of tables, and we'll create a table to store books and their details.
CREATE DATABASE booksDB;
USE booksDB;
CREATE TABLE books (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255),
author VARCHAR(255),
publication_year INT,
pages INT
);Now that we have a table, let's insert some data:
INSERT INTO books (title, author, publication_year, pages) VALUES
('The Catcher in the Rye', 'J.D. Salinger', 1951, 277),
('To Kill a Mockingbird', 'Harper Lee', 1960, 323);In this first scenario, we'll learn how to select data from our table.
SELECT * FROM books;Output:
id title author publication_year pages
1 The Catcher in the Rye J.D. Salinger 1951 277
2 To Kill a Mockingbird Harper Lee 1960 323
Now, let's filter our data based on the author.
SELECT * FROM books WHERE author = 'J.D. Salinger';Output:
id title author publication_year pages
1 The Catcher in the Rye J.D. Salinger 1951 277
We can order our data by different columns. For example, let's sort our books by their publication year.
SELECT * FROM books ORDER BY publication_year;Output:
id title author publication_year pages
1 The Catcher in the Rye J.D. Salinger 1951 277
2 To Kill a Mockingbird Harper Lee 1960 323
In this scenario, we'll learn how to update data in our table. Let's update the author of 'The Catcher in the Rye' to 'Ernest Hemingway' (just kidding! 😉).
UPDATE books SET author = 'Ernest Hemingway' WHERE id = 1;Now, if you run the SELECT * FROM books; query, you'll notice that the author of 'The Catcher in the Rye' has been changed.
Finally, let's learn how to delete data from our table. For this scenario, let's delete a book with an id of 3 (we don't have one yet, so this will be an example).
DELETE FROM books WHERE id = 3;How do we create a new table in SQL?
That's it for our SQL Scenario-Based Questions lesson! Now that you've learned the basics, you can start exploring more complex SQL concepts and real-world projects. Happy coding! 🎉