0% found this document useful (0 votes)
45 views45 pages

My ISM Lab File Anirudh

Uploaded by

Manit Mittal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views45 pages

My ISM Lab File Anirudh

Uploaded by

Manit Mittal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Information Management System (BBA 307)

Submitted in partial fulfilment of the requirement of Bachelors of


Business Administration (BBA)

Guru Gobind Singh Indraprastha University, Delhi

Session 2023-24

under the Guidance of Submitted by

Mrs. Charu Anirudh Mahesh

(Assistant Professor) BBA-V Sem


04825501721

JIMS ENGINEERING MANAGEMENT TECHNICAL CAMPUS

48/4 Knowledge Park III, Greater Noida-201306 (U.P.)


ISM Lab File
1) INTRODUCTION TO SQL

 Definition of SQL

SQL, or Structured Query Language, is a domain-specific programming language


designed for managing and manipulating relational databases. It serves as the standard
language for relational database management systems (RDBMS) and is widely used for
tasks such as querying data, updating data, inserting data, and deleting data from
databases. Here's a detailed breakdown of the key aspects of SQL:

1. Relational Database Management System (RDBMS):

SQL is closely associated with relational database systems, which organize data into
tables with rows and columns.

Popular RDBMS include MySQL, PostgreSQL, SQLite, Microsoft SQL Server, and Oracle
Database.

2. Data Querying:

SQL is primarily used for querying data from databases. The SELECT statement is
fundamental for retrieving information.

3. Data Manipulation:

SQL allows users to modify and manipulate data in the database using statements like
INSERT, UPDATE, and DELETE.

4. Data Definition:

SQL includes statements for defining and managing the structure of the database, such
as creating and altering tables and indexes.

5. Data Constraints:

SQL supports the use of constraints to enforce rules on data in tables, ensuring data
integrity.
Examples include PRIMARY KEY for unique identifiers, FOREIGN KEY for relationships
between tables, CHECK constraints for specific conditions, etc.

6. Data Transactions:

SQL provides the COMMIT and ROLLBACK statements to manage transactions, ensuring
the consistency and integrity of data.

7. Data Security:

SQL includes features for managing database security, such as user authentication and
authorization. GRANT and REVOKE statements are used to assign or revoke privileges.

8. Data Aggregation:

SQL supports functions for aggregating data, such as SUM, AVG, COUNT, MIN, and MAX.

9. Joins:

SQL allows users to combine rows from two or more tables based on related columns
using JOIN operations.

10. Stored Procedures and Functions:

SQL supports the creation of stored procedures and functions, which are precompiled
and stored in the database for reuse.

SQL is a powerful and versatile language that plays a crucial role in managing and
interacting with relational databases, making it an essential tool for developers, database
administrators, and data analysts.

 Models Of SQL
1. Relational Model: Description: The relational model is the most widely used model for
database management. It represents data as tables with rows and columns, where each row
is a record and each column is an attribute. Relationships between tables are established
using keys. For example –
2. Insert Tab: Entity-Relationship Model (ER Model): Description: The ER model is a conceptual
model used to represent entities, attributes, and relationships between entities. It is often
used as a precursor to designing relational databases. For example – .

3. Object-Relational Model: Description: Combines elements of both the relational and


objectoriented models. It allows the use of objects, classes, and inheritance within the
relational database context. For example –
4. Key-Value Model: Description: In key-value stores, data is stored as key-value pairs. These
databases are optimized for simple retrieval and storage of data without the need for a complex
schema.SQL Database Management System (DBMS) Models:

Different relational database management systems implement SQL with some variations.
Common SQL-based DBMS include:

 MySQL: An open-source relational database management system.


 PostgreSQL: Another open-source RDBMS known for its extensibility and
standards compliance.
 SQLite: A self-contained, serverless, and zero-configuration database engine.
 Microsoft SQL Server: A comprehensive RDBMS developed by Microsoft.
 Oracle Database: A powerful and widely used RDBMS from Oracle Corporation.
 IBM Db2: A family of data management products, including database servers,
developed by IBM.
 MariaDB: A community-developed fork of MySQL, designed to be highly
compatible with MySQL.
Each of these database systems implements the SQL language with its own extensions
and optimizations. While there is a common base defined by the SQL standards, users
often encounter differences in syntax, supported features, and performance
optimizations when working with different database systems.

2. ROADWAY TRAVELS ER DIAGRAM

 Definition of ER Diagram & symbols in ER Diagram (In detail)

An Entity Relationship Diagram (ER Diagram) pictorially explains the relationship between
entities to be stored in a database. Fundamentally, the ER Diagram is a structural design of
the database. It acts as a framework created with specialized symbols for the purpose of
defining the relationship between the database entities. ER diagram is created based on
three principal components: entities, attributes, and relationships.

The following diagram showcases two entities - Student and Course, and their relationship.
The relationship described between student and course is many-to-many, as a course can be
opted by several students, and a student can opt for more than one course. Student entity
possesses attributes - Stu_Id, Stu_Name & Stu_Age. The course entity has attributes such as
Cou_ID & Cou_Name.

An Entity-Relationship (ER) diagram is a visual representation of the data model that depicts
the entities within a system and the relationships between those entities. ER diagrams are
commonly used in database design to illustrate the structure of a database, providing a high-
level view of the relationships between entities. The main components of an ER diagram
include entities, attributes, relationships, and cardinality.

Basic Components of an ER Diagram:

1. Entity: An entity is a real-world object or concept that has data attributes and can be
uniquely identified. Examples of entities might include "Customer," "Product," or
"Employee."

2. Attribute: An attribute is a property or characteristic of an entity. For example, a


"Customer" entity might have attributes like "CustomerID," "Name," and "Email."
3. Relationship: A relationship represents an association between two or more entities.
Relationships can be one-to-one, one-to-many, or many-to-many.

4. Cardinality: Cardinality defines the number of instances of one entity that can be
associated with the number of instances of another entity. It is expressed as "one" or "many."

5. Key Attribute: A key attribute is an attribute that uniquely identifies an entity within an
entity set. For example, "CustomerID" might be a key attribute for the "Customer" entity.

Symbols used in ER Diagrams:

1. Entity (Rectangle):

Represents a real-world object, concept, or thing in the system.

Example: "Customer," "Product," "Employee."

Attribute (Oval or Ellipse):

Describes a property or characteristic of an entity.

Example: In the "Customer" entity, attributes might include "CustomerID," "FirstName,"


"LastName."

2. Relationship (Diamond):

Represents an association between two or more entities.

Example: A relationship between "Customer" and "Order" entities indicating that a


customer can place multiple orders.

3. Cardinality (Lines):

Indicates the number of instances of one entity that can be related to another entity.

Common cardinality notations include:

One (1) and Only One: Represented by a straight line.

Zero or One (0..1): Represented by a circle.

Zero or Many (0..N): Represented by a crow's foot (three lines).

One or Many (1..N): Represented by a straight line with a crow's foot.


Primary Key (Underlined Attribute):

Indicates the attribute or combination of attributes that uniquely identifies each instance
of an entity.

Example: Underlining "CustomerID" to show that it is the primary key for the "Customer"
entity.

4. Foreign Key (Dashed Underline):

Represents an attribute in one entity that refers to the primary key in another entity.

Example: If an "Order" entity has a foreign key "CustomerID," it refers to the primary key
"CustomerID" in the "Customer" entity.

5. Weak Entity (Double Rectangle):

Represents an entity that does not have a primary key attribute of its own and depends
on another entity (owner entity).

Example: "Address" might be a weak entity depending on the "Employee" entity for its
existence.

6. Associative Entity (Double Diamond):

Represents an entity that plays a role in a many-to-many relationship and usually has
attributes of its own.

Example: In a many-to-many relationship between "Student" and "Course," an


associative entity "Enrollment" might be introduced. ER diagrams provide a visual
representation of the data model, facilitating communication between stakeholders
involved in database design. They help in understanding the structure of the database
and serve as a blueprint for creating the actual database schema.

 ER Diagram of ROADWAY TRAVELS

Creating an ER diagram typically involves understanding the entities involved, their


attributes, and the relationships between them. Since "ROADWAY TRAVELS" is a bit
abstract and doesn't specify the exact nature of the business or system you're modeling, I'll
provide a generic example. Let's assume a simple scenario where we want to model a
database for a travel agency.

Entities:

1. Customer: Attributes: CustomerID (Primary Key), Name, Email, Phone, etc.

2. Booking: Attributes: BookingID (Primary Key), Date, Time, TotalCost, etc.

3. Trip: Attributes: TripID (Primary Key), Destination, DepartureDate, ReturnDate, etc.

4. Vehicle: Attributes: VehicleID (Primary Key), Type, Capacity, LicensePlate, etc.

Relationships:

1. Books (Relationship between Customer and Booking):

 One customer can make many bookings.


 One booking is made by one customer.
 Attributes: BookingDate, PaymentStatus, etc.

2. Includes (Relationship between Booking and Trip):

 One booking includes one or more trips.


 One trip can be included in multiple bookings.
 Attributes: SeatNumber, SpecialRequests, etc.

3. Uses (Relationship between Booking and Vehicle):

 One booking uses one vehicle.


 One vehicle can be used in multiple bookings.
 Attributes: PickupLocation, DropOffLocation, etc.

4.Vehicle is driven by Driver:


 Relationship between Vehicle and Driver entities.
 Cardinality: One Vehicle is driven by One Driver.

These relationships indicate how entities are connected in the "ROADWAY TRAVELS" system.
For example, a customer can make multiple bookings, each booking can include one or more
trips, and each trip uses a specific vehicle driven by a driver.

3. VARIOUS DATA TYPES

Numeric Types:

 Integer Types:

int: This data type is used to store integer values. The size of int can vary between
programming languages and systems.

short, long, byte: These are variations of integer types that have different sizes, allowing you
to choose a data type based on the range of values you need to represent.

 Floating-Point Types:

float: Represents single-precision floating-point numbers. These are suitable for a wide
range of real numbers.

double: Represents double-precision floating-point numbers, providing higher precision than


float.

 Decimal Types:

decimal (or numeric): Used for fixed-point decimal numbers, ideal for financial calculations
or situations where precision is crucial.

Character Types:

char: Represents a single character. In some languages, char is a fixed-size data type, while in
others, it can represent a character string of length one.

string (or str): Represents a sequence of characters. The size of a string can vary, and it's
often used to store text or words.

Boolean Types:
bool (boolean): Represents a binary value, typically true or false. Booleans are often used in
conditional statements and logical operations.

Date and Time Types:

 date: Represents a date without a time component.


 time: Represents a time of day without a date component.
 datetime (or timestamp): Represents both date and time. It is useful for storing
moments in time.
 timedelta: Represents a duration or the difference between two dates or times.

Collection Types:

 Arrays:

Represents a fixed-size collection of elements of the same type. Array elements are accessed
by their index.

 Lists, Sets, and Dictionaries:

Collections that can dynamically grow or shrink. Lists store ordered sequences, sets store
unique elements, and dictionaries store key-value pairs.

Composite Types:

 Structures or Records:

Used to group together variables of different types under a single name. Each variable within
the structure is referred to as a field or member.

Null/Undefined:

 Represents the absence of a value.

Examples: `None` in Python, `null` in JavaScript

In programming and database design, understanding and choosing the right data types are
crucial for efficient and accurate data storage and manipulation. The choice of data type
depends on factors such as the nature of the data, the range of values it can take, and the
operations you intend to perform on it.
4. KEY CONSTRAINTS & NORMALIZATION

Key Constraints:

1. Primary Key (PK):

 Uniquely identifies each record in a table.


 Ensures data integrity and provides a reference for relationships.
 Example: `PRIMARY KEY (ID)`.

2. Foreign Key (FK):

 Links a field in one table to the primary key of another table.


 Establishes relationships between tables.
 Example: `FOREIGN KEY (CustomerID) REFERENCES
Customers(CustomerID)`.

3. Unique Constraint:

 Ensures that all values in a column are unique.


 Similar to a primary key but allows for NULL values.
 Example: `UNIQUE (Email)`.

4. Check Constraint:

 Enforces a condition on values entered into a column.


 Restricts the range of allowed values.
 Example: `CHECK (Age >= 18)`.

Normalization:

1. First Normal Form (1NF):

 Eliminates duplicate columns in a table.


 Each column holds atomic (indivisible) values.
 Example: Splitting a "Full Name" column into "First Name" and "Last Name."

2. Second Normal Form (2NF):

 Meets 1NF criteria and removes partial dependencies.


 All non-prime attributes are fully functionally dependent on the primary key.
 Example: Creating a separate table for attributes functionally dependent on a part of
the primary key.

3. Third Normal Form (3NF):

 Meets 2NF criteria and removes transitive dependencies.


 No non-prime attribute depends on another non-prime attribute.
 Example: Moving attributes that depend on another non-prime attribute to a new
table.

4. Boyce-Codd Normal Form (BCNF):

 A stricter form of 3NF, ensuring that all determinants are candidate keys.
 Reduces redundancy further by eliminating overlapping candidate keys.
 Example: Decomposing tables to eliminate overlapping candidate keys.

5. Fourth Normal Form (4NF):

 Addresses multi-valued dependencies.


 Ensures that multi-valued attributes are stored in separate tables.
 Example: Splitting tables to handle multi-valued attributes.

6. Fifth Normal Form (5NF):

 Addresses cases where a table has overlapping multi-valued dependencies.


 Further eliminates redundancy by decomposing tables based on multi-valued
dependencies.
 Example: Splitting tables to handle overlapping multi-valued dependencies.

Normalization helps design efficient and flexible databases by minimizing redundancy and
dependency issues, ensuring data integrity and making the database less prone to anomalies.

PART-A
5) IMPLEMENTATION OF DDL COMMANDS OF SQL WITH SUITABLE EXAMPLES
DDL is the short name for Data Definition Language, which deals with database schemas and
descriptions, of how the data should reside in the database.
• CREATE: to create a database and its objects like (table, index, views, store procedure,
function, and triggers)
• ALTER: alters the structure of the existing database
• DROP: delete objects from the database
• TRUNCATE: remove all records from a table, including all spaces allocated for the records
are removed
• COMMENT: add comments to the data dictionary
• RENAME: rename an object
i. Create table

CREATE TABLE Student (

StudentID INT PRIMARY KEY,

FirstName VARCHAR(50),

LastName VARCHAR(50),

Age INT,

Gender CHAR(1),

DateOfBirth DATE,

Major VARCHAR(50)

);
select * from Student;

ii. Alter table


ALTER TABLE student

ADD address VARCHAR(100);

iii. Drop table

Drop table student;


6) IMPLEMENTATION OF DML COMMANDS OF SQL WITH SUITABLE EXAMPLES
DML is the short name for Data Manipulation Language which deals with data manipulation and
includes most common SQL statements such SELECT, INSERT, UPDATE, DELETE, etc., and it is used to
store, modify, retrieve, delete, and update data in a database.

• SELECT: retrieve data from a database

• INSERT: insert data into a table

• UPDATE: updates existing data within a table

• DELETE: Delete all records from a database table

• MERGE: UPSERT operation (insert or update)

• CALL: call a PL/SQL or Java subprogram

• EXPLAIN PLAN: interpretation of the data access path.

• LOCK TABLE: concurrency Control

i. Insert
INSERT INTO Student
VALUES
(1, 'Rishabh', 'Gupta', 21, 'M', '2002-05-15', 'Computer Science'),
(2, 'Mangesh', 'Pandey', 20, 'M', '2003-02-28', 'Mathematics');
select * from Student;

ii.

Update
UPDATE student
SET age = 18
WHERE StudentID = 1;
Select * from student;
iii. Delete
DELETE FROM Student
Where StudentID = 2
select * from student;

7) IMPLEMENTATION OF DIFFERENT TYPES OF FUNCTIONS WITH SUITABLE


EXAMPLES
i. Number function:

SQL numeric functions are used primarily for numeric manipulation and/or mathematical
calculations.
SELECT ABS(-10) AS AbsoluteValue;
ii. Aggregate function:

An aggregate function performs a calculation on a set of values, and returns a single value.
Except for COUNT(*), aggregate functions ignore null values. Aggregate functions are often
used with the GROUP BY clause of the SELECT statement.
SELECT
Major,
AVG(Age) AS AverageAge,
COUNT(*) AS NumberOfStudents
FROM
Student
GROUP BY
Major;

iii.Character function:

Character functions accept character inputs and can return either characters or number
values as output. SQL provides a number of different character datatypes which includes –
CHAR, VARCHAR, VARCHAR2, LONG, RAW, and LONG RAW.
SELECT CONCAT(FirstName, ' ', LastName) AS FullName FROM Student;
iv. Conversion function:

When you define expressions and local variables then you should specify what type of data will be
stored in those objects such as text data, money, dates, numbers, or characters.
SELECT CAST('2023-12-04' AS DATE);

v. Date function:

In SQL, dates are complicated for newbies, since while working with a database, the format of the
data in the table must be matched with the input data to insert. In various scenarios instead of date,
datetime (time is also involved with date) is used.
SELECT
StudentID,
FirstName,
LastName,
DateOfBirth,
DATEDIFF(YEAR, DateOfBirth, GETDATE()) AS Age
FROM
Student;

8) IMPLEMENTATION OF DIFFERENT TYPES OF OPERATORS IN SQL


1. Arithmetic Operators:
+ (Addition): Adds two numeric values.
- (Subtraction): Subtracts the right-hand operand from the left-hand operand.
* (Multiplication): Multiplies two numeric values.
/ (Division): Divides the left-hand operand by the right-hand operand.
% (Modulus): Returns the remainder of the division of the left-hand operand by
the right-hand operand
CODE: SELECT 10 + 5 AS Sum, 10 * 5 AS Product, 15 % 4 AS Modulus;
2. Comparison Operators:
= (Equal to): Tests if two values are equal.
<> or != (Not equal to): Tests if two values are not equal.
> (Greater than): Tests if the left operand is greater than the right operand.
< (Less than): Tests if the left operand is less than the right operand.
>= (Greater than or equal to): Tests if the left operand is greater than or equal
to the right operand.
<= (Less than or equal to): Tests if the left operand is less than or equal to the
right operand.
CODE: SELECT * FROM Student WHERE Age > 21 AND Gender = 'M';
3. Logical Operators:
AND: Returns true if both conditions are true.
OR: Returns true if at least one condition is true.
NOT: Negates the result of a condition.
CODE: SELECT * FROM Student WHERE (Major = 'Computer Science' AND Age >
20) OR Gender = 'F';

4. Concatenation Operator:
+: Concatenates two strings.
CODE: SELECT FirstName + ' ' + LastName AS FullName FROM Student;
5. IN Operator:
Tests whether a value matches any value in a list.
CODE: SELECT * FROM Student WHERE Major IN ('Computer Science',
'Mathematics', 'Physics');

6. LIKE Operator:
Used for pattern matching with strings.
% represents zero or more characters, and _ represents a single character.
CODE: SELECT * FROM Student WHERE FirstName LIKE 'J%';
9. CONSIDER THE FOLLOWING SCHEMA FOR A LIBRARY DATABASE:
 BOOK (Book_id, Title, Publisher_Name, Pub_Year)

 BOOK_AUTHORS (Book_id, Author_Name)

 PUBLISHER (Name, Address, Phone)

 BOOK_COPIES (Book_id, Branch_id, No-of_Copies)

 BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date)

 LIBRARY_BRANCH (Branch_id, Branch_Name, Address)


Write SQL queries to

1. Retrieve details of all books in the library – id, title, name of publisher, authors, number of copies
in each branch, etc.

2. Get the particulars of borrowers who have borrowed more than 3 books, but from Jan 2023 to
June 2023 3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.

4. Partition the BOOK table based on year of publication. Demonstrate its working with a simple
query.

5. Create a view of all books and its number of copies that are currently available in the library.

ANS
create database library_database;
use library_database;
CREATE TABLE PUBLISHER (
NAME VARCHAR(20) PRIMARY KEY,
ADDRESS VARCHAR(20),
PHONE FLOAT
);
CREATE TABLE BOOK (
BOOK_ID INT PRIMARY KEY,
TITLE CHAR(10),
PUBLISHER_NAME VARCHAR(20),
PUBLISHER_YEAR INT,
FOREIGN KEY (PUBLISHER_NAME) REFERENCES PUBLISHER
(NAME) ON DELETE CASCADE
);
CREATE TABLE LIBRARY_BRANCH (
BRANCH_ID INT PRIMARY KEY,
BRANCH_NAME CHAR(10),
ADDRESS VARCHAR(15)
);
CREATE TABLE BOOK_AUTHORS (
BOOK_ID INT,
AUTHOR_NAME CHAR(10),
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON
DELETE CASCADE
);
CREATE TABLE BOOK_LENDING (
BOOK_ID INT,
BRANCH_ID INT,
CARD_NO INT,
DATE_OUT DATE,
DUE_DATE DATE,
PRIMARY KEY (BOOK_ID, BRANCH_ID, CARD_NO),
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON
DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH
(BRANCH_ID) ON DELETE CASCADE
);
CREATE TABLE BOOK_COPIES (
BOOK_ID INT,
BRANCH_ID INT,
NO_OF_COPIES INT,
FOREIGN KEY (BOOK_ID) REFERENCES BOOK (BOOK_ID) ON
DELETE CASCADE,
FOREIGN KEY (BRANCH_ID) REFERENCES LIBRARY_BRANCH
(BRANCH_ID) ON DELETE CASCADE,
PRIMARY KEY (BOOK_ID, BRANCH_ID)
);

-- Insert data into BOOK table


INSERT INTO BOOK (Book_id, Title, Publisher_Name, Pub_Year) VALUES
(1, 'Book1', 'Publisher1', 2020),
(2, 'Book2', 'Publisher2', 2021),
(3, 'Book3', 'Publisher3', 2022);

-- Insert data into BOOK_AUTHORS table


INSERT INTO BOOK_AUTHORS (Book_id, Author_Name) VALUES
(1, 'Author1'),
(2, 'Author2'),
(3, 'Author3');

-- Insert data into PUBLISHER table


INSERT INTO PUBLISHER (Name, Address, Phone) VALUES
('Publisher1', 'Address1', '123-456-7890'),
('Publisher2', 'Address2', '987-654-3210'),
('Publisher3', 'Address3', '555-555-5555');

-- Insert data into BOOK_COPIES table


INSERT INTO BOOK_COPIES (Book_id, Branch_id, No_of_Copies) VALUES
(1, 1, 5),
(2, 1, 3),
(3, 2, 2);

-- Insert data into BOOK_LENDING table


INSERT INTO BOOK_LENDING (Book_id, Branch_id, Card_No, Date_Out, Due_Date) VALUES
(1, 1, 101, '2023-01-02', '2023-01-30'),
(2, 1, 102, '2023-02-15', '2023-03-15'),
(3, 2, 103, '2023-04-10', '2023-05-10');

-- Insert data into LIBRARY_BRANCH table


INSERT INTO LIBRARY_BRANCH (Branch_id, Branch_Name, Address) VALUES
(1, 'Main Branch', 'Main St, City1'),
(2, 'Branch 2', 'Second St, City2');

Query 1
SELECT B.Book_id, B.Title, B.Publisher_Name, BA.Author_Name, BC.Branch_id,
BC.No_of_Copies
FROM BOOK B
JOIN BOOK_AUTHORS BA ON B.Book_id = BA.Book_id
JOIN BOOK_COPIES BC ON B.Book_id = BC.Book_id;
Query 2
SELECT BL.Card_No, COUNT(*) AS Books_Borrowed
FROM BOOK_LENDING BL
WHERE BL.Date_Out BETWEEN '2023-01-01' AND '2023-06-30'
GROUP BY BL.Card_No
HAVING COUNT(*) > 3;
Query 3
-- Assuming you want to delete a book with Book_id = 123
DELETE FROM BOOK WHERE Book_id = 123;
SELECT * FROM BOOK;
SELECT * FROM BOOK_COPIES;

Query 4
Query 5
CREATE VIEW AVAILABLE_BOOKS AS
SELECT B.Book_id, B.Title, BC.Branch_id, BC.No_of_Copies
FROM BOOK B
JOIN BOOK_COPIES BC ON B.Book_id = BC.Book_id
WHERE BC.No_of_Copies > 0;
10) CONSIDER THE FOLLOWING SCHEMA FOR ORDER DATABASE
 SALESMAN(Salesman_id, Name, City, Commission)

 CUSTOMER(Customer_id, Cust_Name, City, Grade, Salesman_id)

 ORDERS(Ord_No, Purchase_Amt, Ord_Date, Customer_id,

 Salesman_id)

Write SQL queries to

1. Count the customers with grades above Bangalore’s average.

2. Find the name and numbers of all salesmen who had more than one customer.

3. List all the salesman and indicate those who have and don’t have customers in their cities (Use
UNION operation.)

4. Create a view that finds the salesman who has the customer with the highest order of a day.

5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders must also
be deleted.
create database order_database
-- Create SALESMAN table
CREATE TABLE SALESMAN (
Salesman_id INT PRIMARY KEY,
Name VARCHAR(255),
City VARCHAR(255),
Commission DECIMAL(5, 2)
);

-- Create CUSTOMER table


CREATE TABLE CUSTOMER (
Customer_id INT PRIMARY KEY,
Cust_Name VARCHAR(255),
City VARCHAR(255),
Grade INT,
Salesman_id INT,
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

-- Create ORDERS table


CREATE TABLE ORDERS (
Ord_No INT PRIMARY KEY,
Purchase_Amt DECIMAL(10, 2),
Ord_Date DATE,
Customer_id INT,
Salesman_id INT,
FOREIGN KEY (Customer_id) REFERENCES CUSTOMER(Customer_id),
FOREIGN KEY (Salesman_id) REFERENCES SALESMAN(Salesman_id)
);

-- Insert data into SALESMAN table


INSERT INTO SALESMAN (Salesman_id, Name, City, Commission) VALUES
(1, 'John Doe', 'New York', 0.1),
(2, 'Jane Smith', 'Los Angeles', 0.12),
(3, 'Bob Johnson', 'Chicago', 0.08);
-- Insert data into CUSTOMER table
INSERT INTO CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
VALUES
(101, 'Customer1', 'New York', 1, 1),
(102, 'Customer2', 'Los Angeles', 2, 2),
(103, 'Customer3', 'Chicago', 3, 3);
-- Insert data into ORDERS table
INSERT INTO ORDERS (Ord_No, Purchase_Amt, Ord_Date, Customer_id,
Salesman_id) VALUES
(1001, 1000.00, '2023-01-15', 101, 1),
(1002, 1500.50, '2023-02-20', 102, 2),
(1003, 800.75, '2023-03-10', 103, 3);

Query 1
SELECT COUNT(*) AS Above_Avg_Grades_Customers
FROM CUSTOMER
WHERE Grade > (SELECT AVG(Grade) FROM CUSTOMER WHERE City = 'Bangalore');
Query 2
SELECT S.Name, S.Salesman_id
FROM SALESMAN S
JOIN CUSTOMER C ON S.Salesman_id = C.Salesman_id
GROUP BY S.Name, S.Salesman_id
HAVING COUNT(C.Customer_id) > 1;
Query 3
-- Salesmen with customers in their cities
SELECT S.Salesman_id, S.Name, S.City, 'Has Customers' AS Status
FROM SALESMAN S
WHERE EXISTS (SELECT 1 FROM CUSTOMER C WHERE C.Salesman_id =
S.Salesman_id AND C.City = S.City)
UNION
-- Salesmen without customers in their cities
SELECT S.Salesman_id, S.Name, S.City, 'No Customers' AS Status
FROM SALESMAN S
WHERE NOT EXISTS (SELECT 1 FROM CUSTOMER C WHERE C.Salesman_id =
S.Salesman_id AND C.City = S.City);

Query 4
CREATE VIEW MaxOrderSalesman AS
SELECT S.Salesman_id, S.Name, MAX(O.Purchase_Amt) AS
Max_Order_Amount
FROM SALESMAN S
JOIN CUSTOMER C ON S.Salesman_id = C.Salesman_id
JOIN ORDERS O ON C.Customer_id = O.Customer_id
GROUP BY S.Salesman_id, S.Name;

Query 5
-- Delete orders related to the salesman
DELETE FROM ORDERS
WHERE Salesman_id = 1000;
-- Delete the salesman
DELETE FROM SALESMAN
WHERE Salesman_id = 1000;
11) CONSIDER THE FOLLOWING SCHEMA ForR MOVIE DATABASE

 ACTOR(Act_id, Act_Name, Act_Gender)

 DIRECTOR(Dir_id, Dir_Name, Dir_Phone)

 MOVIES(Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)

 MOVIE_CAST(Act_id, Mov_id, Role)

 RATING(Mov_id, Rev_Stars)

Write SQL queries to

1. List the titles of all movies directed by ‘Hitchcock’.

2. Find the movie names where one or more actors acted in two or more movies.

3. List all actors who acted in a movie before 2000 and in a movie after 2015 (use JOIN operation).

4. Find the title of movies and number of stars for each movie that has at least one rating and find
the highest number of stars that movie received. Sort the result by movie title.

5. Update rating of all movies directed by ‘Steven Spielberg’ to 5.

-- Create ACTOR table

CREATE TABLE ACTOR (

Act_id INT PRIMARY KEY,


Act_Name VARCHAR(255),

Act_Gender VARCHAR(10)

);

CREATE TABLE DIRECTOR (

Dir_id INT PRIMARY KEY,

Dir_Name VARCHAR(255),

Dir_Phone VARCHAR(20)

);

CREATE TABLE MOVIES (

Mov_id INT PRIMARY KEY,

Mov_Title VARCHAR(255),

Mov_Year INT,

Mov_Lang VARCHAR(50),

Dir_id INT,

FOREIGN KEY (Dir_id) REFERENCES DIRECTOR(Dir_id)

);

CREATE TABLE MOVIE_CAST (

Act_id INT,

Mov_id INT,

Role VARCHAR(255),

PRIMARY KEY (Act_id, Mov_id),

FOREIGN KEY (Act_id) REFERENCES ACTOR(Act_id),

FOREIGN KEY (Mov_id) REFERENCES MOVIES(Mov_id)

);

CREATE TABLE RATING (

Mov_id INT PRIMARY KEY,

Rev_Stars INT,

FOREIGN KEY (Mov_id) REFERENCES MOVIES(Mov_id)

);
INSERT INTO ACTOR (Act_id, Act_Name, Act_Gender) VALUES
(1, 'Actor1', 'Male'),
(2, 'Actor2', 'Female'),
(3, 'Actor3', 'Male');
INSERT INTO DIRECTOR (Dir_id, Dir_Name, Dir_Phone) VALUES
(1, 'Hitchcock', '123-456-7890'),
(2, 'Spielberg', '987-654-3210');
INSERT INTO MOVIES (Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)
VALUES
(101, 'Movie1', 1990, 'English', 1),
(102, 'Movie2', 2005, 'Spanish', 2),
(103, 'Movie3', 2018, 'French', 1);
INSERT INTO MOVIE_CAST (Act_id, Mov_id, Role) VALUES
(1, 101, 'Lead'),
(2, 101, 'Supporting'),
(3, 102, 'Lead'),
(1, 103, 'Lead'),
(2, 103, 'Supporting');
INSERT INTO RATING (Mov_id, Rev_Stars) VALUES
(101, 4),
(102, 3),
(103, 5);

Query 1
SELECT Mov_Title
FROM MOVIES
WHERE Dir_id = (SELECT Dir_id FROM DIRECTOR WHERE Dir_Name =
'Hitchcock');
Query 2
Query 3
SELECT A.Act_Name
FROM ACTOR A
JOIN MOVIE_CAST MC ON A.Act_id = MC.Act_id
JOIN MOVIES M ON MC.Mov_id = M.Mov_id
WHERE M.Mov_Year < 2000 OR M.Mov_Year > 2015;
Query 4
SELECT M.Mov_Title, R.Rev_Stars
FROM MOVIES M
JOIN RATING R ON M.Mov_id = R.Mov_id
ORDER BY M.Mov_Title;

Query 5
UPDATE RATING
SET Rev_Stars = 5
WHERE Mov_id IN (
SELECT M.Mov_id
FROM MOVIES M
JOIN DIRECTOR D ON M.Dir_id = D.Dir_id
WHERE D.Dir_Name = 'Spielberg'
);

You might also like