1. For given scenario:
Scenario:
Entities:
- Book
- Member
- Borrow
ER Diagram:
The ER diagram will have the following entities and relationships:
- Book: Attributes: BookID (Primary Key), Title, Author, ISBN.
- Member: Attributes: MemberID (Primary Key), Name, Email.
- Borrow: Attributes: BorrowID (Primary Key), BookID (Foreign Key), MemberID (Foreign Key), BorrowDate, ReturnDate.
+--------------+ +------------------+ +------------------+ | Book | | Borrow | | Member | +--------------+ +------------------+ +------------------+ | BookID (PK) | 1 M| BorrowID (PK) |M 1| MemberID (PK) | | Title |-------| BookID (FK) |---------| Name | | Author | | MemberID (FK) | | Email | | ISBN | | BorrowDate | | | +--------------+ | ReturnDate | +------------------+ +------------------+
-- Create the database CREATE DATABASE LibraryDB; -- Use the database USE LibraryDB; -- Create the Book table CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255), Author VARCHAR(255), ISBN VARCHAR(13), PRIMARY KEY (BookID) ); -- Create the Member table CREATE TABLE Member ( MemberID INT AUTO_INCREMENT, Name VARCHAR(255), Email VARCHAR(255), PRIMARY KEY (MemberID) ); -- Create the Borrow table to handle the Many-to-Many relationship CREATE TABLE Borrow ( BorrowID INT AUTO_INCREMENT, BookID INT, MemberID INT, BorrowDate DATE, ReturnDate DATE, PRIMARY KEY (BorrowID), FOREIGN KEY (BookID) REFERENCES Book(BookID), FOREIGN KEY (MemberID) REFERENCES Member(MemberID) );
2. Write SQL query for given problem statement:
- Creating a Database. - Viewing all Tables in a Database. - Viewing all databases. This command creates a new database named LibraryDB.
Creating a DatabaseCREATE DATABASE LibraryDB;
This command lists all tables within the current database.
Viewing all Tables in a DatabaseSHOW TABLES;
These commands create three tables (Book, Member, and Borrow) in the LibraryDB database.
Creating Tables-- Use the database where you want to create tables USE LibraryDB; -- Create the Book table CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255), Author VARCHAR(255), ISBN VARCHAR(13), PRIMARY KEY (BookID) ); -- Create the Member table CREATE TABLE Member ( MemberID INT AUTO_INCREMENT, Name VARCHAR(255), Email VARCHAR(255), PRIMARY KEY (MemberID) ); -- Create the Borrow table to handle the Many-to-Many relationship CREATE TABLE Borrow ( BorrowID INT AUTO_INCREMENT, BookID INT, MemberID INT, BorrowDate DATE, ReturnDate DATE, PRIMARY KEY (BorrowID), FOREIGN KEY (BookID) REFERENCES Book(BookID), FOREIGN KEY (MemberID) REFERENCES Member(MemberID) );
-- Creating a Database CREATE DATABASE LibraryDB; -- Viewing all Databases SHOW DATABASES; -- Use the database to create tables USE LibraryDB; -- Create the Book table CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255), Author VARCHAR(255), ISBN VARCHAR(13), PRIMARY KEY (BookID) ); -- Create the Member table CREATE TABLE Member ( MemberID INT AUTO_INCREMENT, Name VARCHAR(255), Email VARCHAR(255), PRIMARY KEY (MemberID) ); -- Create the Borrow table CREATE TABLE Borrow ( BorrowID INT AUTO_INCREMENT, BookID INT, MemberID INT, BorrowDate DATE, ReturnDate DATE, PRIMARY KEY (BorrowID), FOREIGN KEY (BookID) REFERENCES Book(BookID), FOREIGN KEY (MemberID) REFERENCES Member(MemberID) ); -- Viewing all Tables in a Database SHOW TABLES;
3. Perform the following Operations:
Creates the Book table with constraints: Title and Author cannot be null, ISBN must be unique.
Creating Tables (With Constraints)-- Use the database USE LibraryDB; -- Create the Book table with constraints CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255) NOT NULL, Author VARCHAR(255) NOT NULL, ISBN VARCHAR(13) UNIQUE, PRIMARY KEY (BookID) );
Creates a SimpleBook table without any constraints.
Creating Tables (Without Constraints)-- Create a simple Book table without constraints CREATE TABLE SimpleBook ( BookID INT, Title VARCHAR(255), Author VARCHAR(255), ISBN VARCHAR(13) );
Creates the Book table with constraints: Title and Author cannot be null, ISBN must be unique.
Creating Tables (With Constraints)-- Use the database USE LibraryDB; -- Create the Book table with constraints CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255) NOT NULL, Author VARCHAR(255) NOT NULL, ISBN VARCHAR(13) UNIQUE, PRIMARY KEY (BookID) );
Inserts a new book record with the given title, author, and ISBN into the Book table.
Inserting Records into a Table-- Insert a record into the Book table INSERT INTO Book (Title, Author, ISBN) VALUES ('1984', 'George Orwell', '1234567890123');
Updates the title of the book with BookID 1 to 'Animal Farm'.
Updating Records in a Table-- Update a record in the Book table UPDATE Book SET Title = 'Animal Farm' WHERE BookID = 1;
Deletes the book record with BookID 1 from the Book table.
Deleting Records from a Table-- Delete a record from the Book table DELETE FROM Book WHERE BookID = 1;
Starts a transaction, inserts a new book, and commits the transaction to save changes.
Saving (Commit) and Undoing (Rollback) Transactions-- Start a transaction START TRANSACTION; -- Insert a new book INSERT INTO Book (Title, Author, ISBN) VALUES ('Brave New World', 'Aldous Huxley', '9876543210987'); -- Commit the transaction COMMIT;
-- Use the database USE LibraryDB; -- Create the Book table with constraints CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255) NOT NULL, Author VARCHAR(255) NOT NULL, ISBN VARCHAR(13) UNIQUE, PRIMARY KEY (BookID) ); -- Create a simple Book table without constraints CREATE TABLE SimpleBook ( BookID INT, Title VARCHAR(255), Author VARCHAR(255), ISBN VARCHAR(13) ); -- Insert a record into the Book table INSERT INTO Book (Title, Author, ISBN) VALUES ('1984', 'George Orwell', '1234567890123'); -- Update a record in the Book table UPDATE Book SET Title = 'Animal Farm' WHERE BookID = 1; -- Delete a record from the Book table DELETE FROM Book WHERE BookID = 1; -- Start a transaction START TRANSACTION; -- Insert a new book INSERT INTO Book (Title, Author, ISBN) VALUES ('Brave New World', 'Aldous Huxley', '9876543210987'); -- Commit the transaction COMMIT; -- Start another transaction START TRANSACTION; -- Insert a new book INSERT INTO Book (Title, Author, ISBN) VALUES ('The Catcher in the Rye', 'J.D. Salinger', '5678901234567'); -- Rollback the transaction ROLLBACK;
4. Perform the following Operations:
Altering a Book Table.
Book Table-- Create the Book table with constraints CREATE TABLE Book ( BookID INT AUTO_INCREMENT, Title VARCHAR(255) NOT NULL, Author VARCHAR(255) NOT NULL, ISBN VARCHAR(13) UNIQUE, PRIMARY KEY (BookID) );
Alter Book Table-- Add a new column to the Book table ALTER TABLE Book ADD COLUMN PublicationYear INT;
Adds a new column PublicationYear to the Book table.
Drop SimpleBook Table-- Drop the SimpleBook table DROP TABLE SimpleBook;
Delete the SimpleBook table completely from the database.
Renaming a Table-- T-- Rename the Book table to LibraryBook RENAME TABLE Book TO LibraryBook;
Renames the Book table to LibraryBook.
Truncating a Table-- Truncate the Book table TRUNCATE TABLE Book;
Removes all records from the Book table but keeps the table structure intact.
Backing up a Database-- Backup command (to be run in the command line, not in MySQL prompt) mysqldump -u [username] -p LibraryDB > LibraryDB_backup.sql
Creates a backup of the LibraryDB database and saves it to a file named LibraryDB_backup.sql
Restoring a Database-- Restore command (to be run in the command line, not in MySQL prompt) mysql -u [username] -p LibraryDB < LibraryDB_backup.sql
Restores the LibraryDB database from the backup file LibraryDB_backup.sql
5. Perform the following Operations:
-- Select all books by George Orwell SELECT * FROM LibraryBook WHERE Author = 'George Orwell';
-- Select all books published after 1950 and authored by George Orwell SELECT * FROM LibraryBook WHERE Author = 'George Orwell' AND PublicationYear > 1950;
-- Count the number of books in the LibraryBook table SELECT COUNT(*) AS TotalBooks FROM LibraryBook;
-- Get the number of books by each author and filter authors with more than one book SELECT Author, COUNT(*) AS BookCount FROM LibraryBook GROUP BY Author HAVING COUNT(*) > 1;
6. Perform Queries involving:
-- Select books borrowed in the last 30 days SELECT Title, BorrowDate FROM LibraryBook lb INNER JOIN Borrow b ON lb.BookID = b.BookID WHERE BorrowDate >= CURDATE() - INTERVAL 30 DAY;
-- Select books with the author's name in uppercase SELECT Title, UPPER(Author) AS AuthorUpper FROM LibraryBook;
-- Calculate the average year of publication of all books SELECT AVG(PublicationYear) AS AveragePublicationYear FROM LibraryBook;
7. Retrieving Data from Multiple Table:
Fetches book titles, authors, borrow dates, and return dates for all records where there is a matching BookID in both LibraryBook and Borrow.
Joining Tables (Inner Join)-- Retrieve data from LibraryBook and Borrow tables using Inner Join SELECT lb.Title, lb.Author, b.BorrowDate, b.ReturnDate FROM LibraryBook lb INNER JOIN Borrow b ON lb.BookID = b.BookID;
Fetches all book titles and authors from LibraryBook, including borrow dates and return dates if they exist, and shows null for books that haven't been borrowed.
Joining Tables (Left Outer Join)-- Retrieve data from LibraryBook and Borrow tables using Left Outer Join SELECT lb.Title, lb.Author, b.BorrowDate, b.ReturnDate FROM LibraryBook lb LEFT JOIN Borrow b ON lb.BookID = b.BookID;
Fetches all borrow records, including book titles and authors if they exist, and shows null for borrow records without matching books.
Joining Tables (Right Outer Join)-- Retrieve data from LibraryBook and Borrow tables using Right Outer Join SELECT lb.Title, lb.Author, b.BorrowDate, b.ReturnDate FROM LibraryBook lb RIGHT JOIN Borrow b ON lb.BookID = b.BookID;
Fetches all borrow records, including book titles and authors if they exist, and shows null for borrow records without matching books.
Aliases for Table Names-- Using aliases for tables SELECT lb.Title AS BookTitle, m.Name AS MemberName, b.BorrowDate, b.ReturnDate FROM LibraryBook lb INNER JOIN Borrow b ON lb.BookID = b.BookID INNER JOIN Member m ON b.MemberID = m.MemberID;
8. Sub queries:
Fetches book titles and authors for books that have been borrowed, using a subquery to get BookID's from the Borrow table.
Subquery with IN Clause-- Select all books borrowed by members SELECT Title, Author FROM LibraryBook WHERE BookID IN (SELECT BookID FROM Borrow);
Fetches names and emails of members who have borrowed books, using a subquery with the EXISTS clause to check for borrowing records.
Subquery with EXISTS Clause-- Select all members who have borrowed books SELECT Name, Email FROM Member m WHERE EXISTS (SELECT 1 FROM Borrow b WHERE b.MemberID = m.MemberID);
Fetches titles and authors of books that have not been borrowed, handling NULL by using NOT IN with a subquery to get BookIDs from the Borrow table.
Handling NULL-- Select all books that have not been borrowed SELECT Title, Author FROM LibraryBook WHERE BookID NOT IN (SELECT BookID FROM Borrow);
9. Views:
Creates a view named BorrowedBooks that shows titles and authors of borrowed books along with member names and borrow/return dates.
Creating Views-- Create a view to show borrowed books with member details CREATE VIEW BorrowedBooks AS SELECT lb.Title, lb.Author, m.Name AS MemberName, b.BorrowDate, b.ReturnDate FROM LibraryBook lb INNER JOIN Borrow b ON lb.BookID = b.BookID INNER JOIN Member m ON b.MemberID = m.MemberID;
Deletes the BorrowedBooks view if it exists.
Creating Views-- Drop the BorrowedBooks view DROP VIEW IF EXISTS BorrowedBooks;
Fetches all records from the BorrowedBooks view.
Selecting from View-- Select all records from the BorrowedBooks view SELECT * FROM BorrowedBooks;
10. DCL statements:
Grants SELECT and INSERT permissions on the LibraryBook table in the LibraryDB database to the user user1 connecting from localhost.
Granting Permissions-- Grant SELECT and INSERT permissions on LibraryBook table to user 'user1' GRANT SELECT, INSERT ON LibraryDB.LibraryBook TO 'user1'@'localhost';
Revokes the INSERT permission on the LibraryBook table in the LibraryDB database from the user user1 connecting from localhost.
Revoking Permissions-- Revoke INSERT permission on LibraryBook table from user 'user1' REVOKE INSERT ON LibraryDB.LibraryBook FROM 'user1'@'localhost';
GRANT SELECT, INSERT ON LibraryDB.LibraryBook TO 'user1'@'localhost';: Grants SELECT and INSERT permissions on the LibraryBook table to user1.
REVOKE INSERT ON LibraryDB.LibraryBook FROM 'user1'@'localhost';: Revokes the INSERT permission on the LibraryBook table from user1.
Granting and revoking permissions-- Use the database USE LibraryDB; -- Granting Permissions -- Grant SELECT and INSERT permissions on LibraryBook table to user 'user1' GRANT SELECT, INSERT ON LibraryDB.LibraryBook TO 'user1'@'localhost'; -- Revoking Permissions -- Revoke INSERT permission on LibraryBook table from user 'user1' REVOKE INSERT ON LibraryDB.LibraryBook FROM 'user1'@'localhost';