Nested queries

Nested queries, also known as subqueries, are queries placed inside other queries. They allow you to perform complex queries by using the result of one query as the input for another. Nested queries can appear in the SELECT, FROM, WHERE, or HAVING clauses of an SQL statement.

Example
CREATE TABLE Authors (
    AuthorID INT PRIMARY KEY,
    Name VARCHAR(100)
);

CREATE TABLE Books (
    BookID INT PRIMARY KEY,
    Title VARCHAR(100),
    AuthorID INT,
    Price DECIMAL(10, 2),
    FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);
INSERT INTO Authors (AuthorID, Name) VALUES
(1, 'Author One'),
(2, 'Author Two'),
(3, 'Author Three');

INSERT INTO Books (BookID, Title, AuthorID, Price) VALUES
(1, 'Book A', 1, 10.00),
(2, 'Book B', 2, 15.00),
(3, 'Book C', 1, 20.00),
(4, 'Book D', 3, 25.00);


Find the Titles of Books Written by the Author Who Wrote the Book with the Highest Price
SELECT Title
FROM Books
WHERE AuthorID = (
    SELECT AuthorID
    FROM Books
    ORDER BY Price DESC
    LIMIT 1
);

+--------+
| Title  |
+--------+
| Book D |
+--------+

Find the names of authors who have written at least one book priced above the average price of all books.
SELECT Name
FROM Authors
WHERE AuthorID IN (
    SELECT DISTINCT AuthorID
    FROM Books
    WHERE Price > (
        SELECT AVG(Price)
        FROM Books
    )
);
+--------------+
| Name         |
+--------------+
| Author One   |
| Author Three |
+--------------+
Find the Titles of Books Written by Authors Who Have Written More Than One Book
SELECT Title
FROM Books
WHERE AuthorID IN (
    SELECT AuthorID
    FROM Books
    GROUP BY AuthorID
    HAVING COUNT(BookID) > 1
);

+--------+
| Title  |
+--------+
| Book A |
| Book C |
+--------+
Find the Names of Authors Who Have Written Books with an Average Price Above $15
SELECT Name
FROM Authors
WHERE AuthorID IN (
    SELECT AuthorID
    FROM Books
    GROUP BY AuthorID
    HAVING AVG(Price) > 15
);

Output:

+--------------+
| Name         |
+--------------+
| Author Three |
+--------------+
Find the Titles of Books Written by Authors Who Have Written at Least One Book Priced Below the Average Price
SELECT Title
FROM Books
WHERE AuthorID IN (
    SELECT DISTINCT AuthorID
    FROM Books
    WHERE Price < (
        SELECT AVG(Price)
        FROM Books
    )
);

Find the Titles of Books Written by the Most Prolific Author
SELECT Title
FROM Books
WHERE AuthorID = (
    SELECT AuthorID
    FROM Books
    GROUP BY AuthorID
    ORDER BY COUNT(BookID) DESC
    LIMIT 1
);

Output:

+--------+
| Title  |
+--------+
| Book A |
| Book C |
+--------+

Comments

Popular posts from this blog

KTU DBMS LAB CSL 333 BTech S5 - Dr Binu V P

KTU DBMS LAB CSL 333 Syllabus and Experiments

Creating a Database and Table ,executing queries - MySQL Lab Exercise