SQL task help request

Could You help me wit h this task, please?

You are working with the library books database.

The Books table has the columns id, name, year.

The library has new books whose information is stored in another table called "New", however they do not have a year column.

Write a query to select the books from both tables, Books and New, combining their data. For the year column of the New books use the value 2022.

Also, select only the books that are released after the year 1900.

The result set should contain the name and year columns only, ordered by the name column alphabetically.

My solution:

SELECT name, year AS str('2022')

FROM New

UNION

SELECT name, year

FROM Books

WHERE year > 1900

ORDER BY name ASC

hi

hope this helps

your query is absolutely right

no need for "order by"

UNION automatically does DISTINCT and ORDER BY

The order in which rows are returned in a result set are (sic) not guaranteed unless an ORDER BY clause is specified.

Thank You Ifor for pointing it out

:+1: :+1:

You can use the UNION operator to merge the data from the two tables and add a constant value indicating the year of the new book. Then, use the WHERE clause to filter out books with a release year after 1900, and use the ORDER BY clause to sort the books alphabetically by the name column. The following is the corresponding query:

SELECT name, year
FROM Books
WHERE year > 1900

UNION

SELECT name, 2022 as year
FROM New
ORDER BY name.

This query first selects books from the Books table with a year after 1900, and then uses UNION to merge them into the new books table New with the year set to 2022. Finally, use ORDER BY to sort the result set alphabetically by the name column.

Note that UNION removes duplicate rows by default; if you want to keep duplicate rows, you can use UNION ALL. In this scenario, I used UNION because you probably don't want the same book to appear twice.

I hope this helps you! If you have any other questions, please feel free to ask.