0% found this document useful (0 votes)
71 views94 pages

Ism Lab File 1

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)
71 views94 pages

Ism Lab File 1

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/ 94

ISM LAB FILE

On

Introduction Of SQL
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

Ms.Charu Singh Adarsh Srivastava

(Faculty Guide ) Enrolment No. 08625501721

JIMS ENGINEERING MANAGEMENT TECHNICAL CAMPUS

48/4, Knowledge Park III, Greater Noida, Knowledge Park III, Noida, Uttar
Pradesh 201306

1
DECLARATION

I hereby declare that this ‘ISM LAB FILE (307)’ submitted by me to JEMTEC, Greater Noida is a
Bonafide work undertaken by me and has not been submitted to any other University or Institution for
the award of any degree diploma /certificate or published any time before.

Date: 14/12/2023

Name: Adarsh Srivastava

Enrolment No. 08625501721

(Signature of the Student)

2
TO WHOM SO EVER IT MAY CONCERN

This is to certify that MR. Adarsh Srivastava S/O Abhay Kumar Srivastava Batch-
2021-2024, Enrollment No. 01525501721 student of BBA, Vth Semester at JIMS
Engineering Management Technical Campus, Greater Noida affiliated to Guru
Gobind Singh Indraprastha University, New Delhi, has prepared and submitted
his/her SUMMER TRAINING REPORT on the topic,

" Information Management System." in the month of December 2023

I certify that the report is the original work done in the partial fulfillment of awarding
Degree of Bachelor of Business Administration (BBA).

Name of the Guide Ms. Charu Singh

Signature of the Guide

Date

3
ACKNOWLEDGEMENT

I offer my sincere thanks and humble regards to JEMTEC, Greater Noida for imparting us very
valuable professional training in BBA. I pay my gratitude and sincere regards to Ms. Charu Singh, my
project Guide, for giving me the cream of his knowledge. I am thankful to her as she has been a
constant source of advice, motivation and inspiration. I am also thankful to her for giving his
suggestions and encouragement throughout the project work.
I take the opportunity to express my gratitude and thanks to our computer Lab staff and library staff
for providing me the opportunity to utilize their resources for the completion of the project.
I am also thankful to my family and friends for constantly motivating me to complete the project and
providing me an environment, which enhanced my knowledge.

Date: 13/12/2023

Name: Adarsh Srivastava

Enrolment No. 08625501721

Course: BBA (V-SEM)

(Signature of the Student)

4
INDEX
S.NO. Particulars Page Signature
No.
1. Introduction Of SQL 1

2. Roadway travels ER Diagrams 6

3. Various Data Types 12

4. Key Constrains-Normalization 15

5. Part A: Implementation of DDL 18


commands of SQL with suitable
examples

 Create table

 Alter table

 Drop Table
6. Implementation of DML 21
commands of SQL with suitable
examples
 Insert

5
 Update

 Delete
7. Implementation of different types 26
of function with suitable
examples

 Number function

 Aggregate Function

 Character Function

 Conversion Function

 Date Function
8. Implementation of different types 31
of operators in SQL

 Arithmetic Operators

 Logical Operators

 Comparison Operator

 Special Operator
 Set Operation

6
9. Consider the following schema 36
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 jd


Branch Name, Address)

Write SQL queries to

1. Retrieve details of all books in


the library-id, title, name of
publisher, authors, number of
7
copies in each branch, etc.

2. Get the particulars of borrowers


who have borrowed more

than 3 books, but from Jan 2023 to


Jun 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.
10. Consider the following schema 57
for Order Database:

SALESMAN(Salesman id Name,
City, Commission)

CUSTOMER(Customer_id Cust
Name, City, Grade, Salesman_id)
8
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
9
11. Consider the scheme for Movie 71
Databa

ACTOR(Actid Act Name Act


Gender)

DIRECTOR(Dir id, Dir Name, Dir


Phone) MOVIES(Mov_id, Mov
Title, Mov Year, Mov Lang, Dir jd)
MOVIE CAST(Act id, Movid
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


10
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
12. Part B: Mini project 87

 For any problem selected,


write the ER Diagram apply
ER-mapping rules normalize
the relations, and follow the
application development
process

 Make sure that the


application should have five
or more tables, at least

 Indicative areas include


health care, education,
industry, transport, supply
chain, etc.

11
xii
CHAPTER 1-
INTRODUCTION TO
SQL

1
Definition : SQL, which stands for Structured Query Language, is a domain-specific language used
for managing and manipulating relational databases. It provides a standardized way to interact with
relational database management systems (RDBMS) by defining, querying, and manipulating the data
stored in these databases. Here's a detailed breakdown of SQL:

1. Structured Query Language (SQL):

 SQL is a standardized programming language specifically designed for managing and


manipulating relational databases.

 It is a declarative language, meaning that users specify what they want to achieve, and
the database management system (DBMS) determines the most efficient way to carry
out the request.

2. Key Components of SQL:

 Data Definition Language (DDL): Used to define and manage the structure of the
database.

 CREATE: Used to create database objects like tables, indexes, and views.

 ALTER: Modifies the structure of the existing database objects.

 DROP: Deletes database objects like tables and databases.

 Data Manipulation Language (DML): Used to manipulate the data stored in the
database.

 SELECT: Retrieves data from one or more tables.

 INSERT: Adds new records to a table.

 UPDATE: Modifies existing records in a table.

 DELETE: Removes records from a table.

 Data Control Language (DCL): Manages access to data within the database.

 GRANT: Provides specific privileges to database users.

 REVOKE: Removes specific privileges from database users.

 Transaction Control Language (TCL): Manages transactions within a database.

2
 COMMIT: Saves all the changes made during the current transaction.

 ROLLBACK: Undoes the changes made during the current transaction.

3. SQL Database Objects:

 Tables: Store data in rows and columns.

 Indexes: Improve the speed of data retrieval operations on a table.

 Views: Virtual tables that are based on the result of a SELECT query.

 Stored Procedures: Precompiled collection of one or more SQL statements.

4. SQL Syntax:

 SQL uses a standardized syntax to ensure consistency across different database


systems. However, there may be slight variations between database vendors.

5. SQL Queries:

 A SQL query is a request for information from a database. The SELECT statement is
commonly used to retrieve data.

6. Normalization:

 SQL databases follow the principles of normalization to organize data efficiently,


reduce redundancy, and improve data integrity.

7. Relationships:

 SQL supports relationships between tables, including one-to-one, one-to-many, and


many-to-many relationships.

8. ACID Properties:

 SQL databases are designed to follow ACID (Atomicity, Consistency, Isolation,


Durability) properties to ensure the reliability of transactions.

9. Popular SQL Database Management Systems:

 Examples include MySQL, PostgreSQL, Oracle Database, Microsoft SQL Server, and
SQLite.

3
In summary, SQL is a powerful language for managing relational databases, providing a standardized
and efficient way to define database structures, manipulate data, and control access to the data. Its
widespread adoption has made it a fundamental skill for database administrators, developers, and data
analysts.

Models of SQ

1. SQL Standards:

 SQL-86, SQL-89, SQL-92, SQL:1999, SQL:2003, SQL:2008, SQL:2011,


SQL:2016, and SQL:2019: These are different versions of the SQL standard released
by the American National Standards Institute (ANSI) and the International
Organization for Standardization (ISO). Each version introduces new features,
enhancements, and improvements.

2. Database Management Systems (DBMS):

 MySQL: A popular open-source relational database management system. It uses SQL


for querying and managing databases.

 PostgreSQL: Another open-source relational database management system known for


its advanced features and extensibility. It also uses SQL.

 Microsoft SQL Server: Developed by Microsoft, it's a comprehensive relational


database management system that uses Transact-SQL (T-SQL), a proprietary extension
of SQL.

 Oracle Database: A powerful and widely used relational database management


system developed by Oracle Corporation. It uses PL/SQL, a procedural language
extension to SQL.

 SQLite: A lightweight, file-based relational database management system that uses a


subset of SQL.

 IBM Db2: A family of data management products, including a relational database


management system that uses SQL.

3. SQL Variants:
4
 Some database systems may implement their own variations or extensions of SQL. For
example, MySQL has its own specific syntax for certain operations, and Transact-SQL
(T-SQL) used by Microsoft SQL Server includes additional features beyond standard
SQL.

4. SQL Models for NoSQL Databases:

 While traditional relational databases use SQL, NoSQL databases (like MongoDB,
Cassandra, or CouchDB) often have their own query languages and models. They may
not strictly adhere to the relational model or SQL standards.

5
CHAPTER 2- ROADWAY
TRAVELS ER DIAGRAM

6
Definition of ER Diagram & symbols in ER Diagram

An Entity-Relationship (ER) diagram is a visual representation of a database that illustrates the


relationships between entities and the structure of the data within those entities. This powerful tool is
employed in the field of database design to create a conceptual model that developers and
stakeholders can use to understand the data flow and relationships within a system. In this detailed
exploration, we will discuss the fundamental components, purpose, and symbols used in ER diagrams.

Key Components of ER Diagrams:

1. Entity:

 At the core of ER diagrams are entities, which are objects or concepts in the real world
that can be identified and distinguished. Entities are represented by rectangles in the
diagram and often correspond to tables in a relational database. For instance, in a
library database, entities could include "Book," "Author," and "Borrower."

2. Attribute:

 Entities are characterized by attributes, which are properties or characteristics


describing an entity. Attributes provide details about the entity and are represented by
ovals connected to their respective entities. Taking the "Book" entity as an example,
attributes could include "Title," "ISBN," and "PublicationYear."

3. Key Attribute:

 A key attribute is an attribute that uniquely identifies each instance of an entity within
the entity set. It is denoted by underlining the attribute name. In the "Author" entity, for
instance, "AuthorID" could be a key attribute.

4. Relationship:

 Relationships in ER diagrams depict how entities are connected or associated with


each other. They are represented by diamond shapes. Relationships help define the
logical connections between different entities. For instance, there might be a
relationship between the "Book" and "Author" entities in a library database to show
which author wrote which book.

7
5. Cardinality:

 Cardinality describes the number of instances of one entity that can be related to the
number of instances of another entity. It is often expressed as "one" (1), "many" (*), or
specific numeric values. Cardinality helps in understanding the nature of relationships,
such as whether it's a one-to-one, one-to-many, or many-to-many relationship.

6. Weak Entity:

 A weak entity is an entity that cannot be uniquely identified by its attributes alone and
depends on the existence of another related entity. It is represented by a double
rectangle. For example, in a university database, a "Room" entity might be weak if it
depends on another entity, such as "Building."

7. Associative Entity:

 An associative entity is an entity that associates the entities involved in a many-to-


many relationship. It has its own attributes in addition to the foreign key attributes
from the connected entities. It is represented by a diamond shape connected to the
relationship line.

8. Recursive Relationship:

 A recursive relationship occurs when an entity is related to itself. This could represent
hierarchical structures or relationships where an entity is connected to other entities of
the same type. A common example is an "Employee" entity with a recursive
relationship for a manager-subordinate hierarchy.

9. Relationship Attribute:

 A relationship attribute is an attribute that is associated with a relationship rather than


with any one participating entity. It is represented by an oval and connected to the
relationship line. For instance, in a "Teaches" relationship between "Professor" and
"Course" entities, the relationship attribute might be "Horseweed."

Symbols Used in ER Diagrams:

1. Rectangle:

8
 Represents an entity. Each entity in the ER diagram corresponds to a table in the
database.

2. Ellipse (Oval):

 Represents an attribute. Attributes provide details about entities and contribute to the
overall understanding of the data.

3. Diamond:

 Represents a relationship between entities. The diamond shape is used to visually


connect entities and illustrate how they relate to each other.

4. Lines:

 Connect entities with relationships and attributes. Lines show the connections and
associations between different components in the ER diagram.

5. Underline:

 Indicates a key attribute. Key attributes are crucial for uniquely identifying instances of
an entity.

6. Crow's Foot Notation:

 A common notation for representing cardinality. The crow's foot at the end of a line
indicates the "many" side of the relationship.

7. Double Rectangle:

 Represents a weak entity. Weak entities depend on another entity for identification.

8. Double Diamond:

 Represents an associative entity. Associative entities are used in many-to-many


relationships to introduce additional attributes.

9. Loop:

 Represents a recursive relationship. Recursive relationships are used when an entity is


related to itself.

9
ER Diagram of ROADWAY TRAVELS
The attributes identified for entities in “Roadway Travels” are:

CREATION OF BUS ENTITY SET:

BUS (BUS_NO, SOURCE, DESTINATION)

Each BUS is identified by a unique identification bus number that acts as a Primary
Key.

o CREATION OF PASSENGER ENTITY SET:

PASSENGER (PNR_NO, NAME, AGE, GENDER, PPNO)

Each passenger is identified by a Unique Identification passenger number that is considered as


a Primary Key.

o CREATION OF TICKET ENTITY SET:

TICKET (TICKET _NO, BUS_NO, JOURNEY_DATE, SOURCE, DESTINATION,


DEP_TIME)

Each Ticket issued is identified by Unique Identification ticket number and it is considered as a
Primary Key.

o CREATION OF RESERVATION ENTITY SET:

RESERVATION (PNR _NO, TICKET_NO, JOURNEY_DATE, NO_OF_SEATS,


ADDRESS, CONTACT_NO, STATUS)

Each reservation done is identified by unique identification passenger number which is


considered as a Primary Key to the Reservation Relation and also acts as a Foreign Key
Relationship with the Passenger relation.

10
o CREATION OF CANCELLATION ENTITY SET:

CANCELLATION (PNR _NO, TICKET_NO, JOURNEY_DATE,


NO_OF_SEATS, ADDRESS, CONTACT_NO, STATUS)

Each cancellation done is identified by unique identification passenger number which is


considered as a Primary Key to the Relation Cancellation and also acts as a Foreign Key
Relationship with the Passenger relation?

ER DIAGRAM:

11
CHAPTER 3- VARIOUS
DATA TYPES

12
VARIOUS DATA TYPES:

1. Integer: Integers are whole numbers, either positive or negative, without any decimal places.
They are commonly used for counting and indexing, such as 42 or -17 in mathematical and
programming contexts.

2. Float (Floating-point): Floats represent real numbers and include decimal points. They are
suitable for more precise mathematical calculations, like 3.14 or -0.05 in scientific and
engineering applications.

3. String: Strings are sequences of characters, either letters, numbers, or symbols, enclosed in
single or double quotes. Examples include "Hello, World!" and '123', and they are fundamental
for handling textual data.

4. Boolean: Booleans have only two possible values: True or False. They are crucial for logical
operations and decision-making in programming, providing a basis for conditional statements.

5. List: Lists are ordered collections of items, enclosed in square brackets. They are mutable,
allowing for dynamic changes in size and content. For instance, [1, 2, 3] represents a list of
integers.

6. Tuple: Tuples are similar to lists but immutable, meaning their size and content cannot be
changed after creation. Tuples use parentheses for notation, like (1, 2, 3), making them
suitable for fixed data structures.

7. Dictionary: Dictionaries store data in key-value pairs, enclosed in curly braces. They are
unordered and provide efficient data retrieval based on keys. For example, {'key': 'value'}
represents a dictionary entry with a specific key-value association.

8. Set: Sets are unordered collections of unique elements, denoted by curly braces. They are
useful for mathematical operations like union and intersection. For instance, {1, 2, 3}
represents a set containing distinct integers.

9. Complex: Complex numbers consist of a real part and an imaginary part, expressed as a sum
of the form a+bi, where a and b are real numbers, and i is the imaginary unit. These are
employed in various mathematical and engineering applications.

10. None Type: None is a special object in Python, representing the absence of a value or a null
value. It is commonly used to denote that a variable or a function returns no meaningful result.
13
11. Bytes and Bytearray: Bytes represent a sequence of immutable 8-bit values, often used for
binary data, while bytearray is a mutable counterpart. They are essential for handling raw data,
such as encoding and decoding files or network communication.

12. Range: Range represents an immutable sequence of numbers, commonly used in loops for
iterating a specific number of times. It is memory-efficient as it generates values on the fly,
saving resources compared to creating a list of numbers.

13. Frozen set: Similar to a set, a frozen set is an immutable collection of unique elements. Once
created, its content cannot be modified, making it suitable for situations where immutability is
desired.

14. Decimal: The decimal data type represents floating-point numbers with fixed precision,
helping to avoid issues with floating-point arithmetic. It is useful in financial and decimal-
based applications where precision is critical.

15. Enum: Enums (enumerations) provide a way to create named constant values, improving code
readability by assigning meaningful names to specific values. They are often used to define
sets of related constants or options.

14
CHAPTER4-KEY
CONSTRAINT
NORMALIZATION

15
KEY CONSTRAINTS & NORMALIZATION
Key Constraints:
1. Primary Key: A primary key uniquely identifies each record in a database table.
It must be unique for each row and cannot contain null values.
2. Foreign Key: A foreign key establishes a link between two tables. It refers to
the primary key in another table, creating a relationship. This ensures referential
integrity.
3. Unique Key: Similar to a primary key, a unique key ensures that each value in a
column is unique. However, unlike a primary key, a table can have multiple
unique keys.
Normalization:
1. First Normal Form (1NF): Ensures that data in a table is organized, with no
repeating groups or arrays. Each column contains atomic values, and each cell
has a single value.
2. Second Normal Form (2NF): Builds on 1NF by ensuring that no partial
dependencies exist. All non-key attributes are fully functionally dependent on
the primary key.
3. Third Normal Form (3NF): Extends normalization by eliminating transitive
dependencies. No non-key attribute depends on another non-key attribute.
4. Boyce-Codd Normal Form (BCNF): A more stringent form of 3NF, ensuring
that for every non-trivial functional dependency, the determinant is a super key.
5. Fourth Normal Form (4NF): Deals with multi-valued dependencies. It ensures
that no non-trivial multi-valued dependency exists between candidate keys and
non-prime attributes.
Normalization aims to reduce redundancy, improve data integrity, and maintain a
clear structure in a relational database. It involves breaking down large tables
into smaller, related tables and establishing relationships between them.

16
PART A

17
 IMPLEMENTATION OF DDL COMMANDS OF SQL WITH
SUITABLE EXAMPLES:
a) Create Table:
 Definition: The CREATE TABLE statement is used in SQL to define and create a new table in
a database. It specifies the table name, along with the names and data types of each column the
table will contain.

 SQL Query:

CREATE TABLE Products (


ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Category VARCHAR(50),
Price DECIMAL(8, 2)
);

Example: the created table.

18
b) Alter Table:
 Definition: The ALTER TABLE statement in SQL is used to modify an existing table
structure. It can add, modify, or drop columns, as well as alter constraints associated with the
table.

 SQL Query:

ALTER TABLE Products


ADD DiscountPercentage DECIMAL(5, 2);

Example: newly added column.

19
c) Drop Table:
 Definition: The DROP TABLE statement is used in SQL to remove an existing table and all
its data from the database. It permanently deletes the table structure and its associated data.

 SQL Query:

DROP TABLE Products;

Example: Removing all data from the table.


20
 IMPLEMENTATION OF DML COMMANDS OF SQL WITH
SUITABLE EXAMPLES
a). INSERT:
 Definition: The INSERT statement in SQL is a DML command used to add new records to a
table, specifying values for each column.

 SQL Query:

INSERT INTO Products (ProductID, ProductName, Category, Price)


VALUES
21
(1, 'Product1', 'Category1', 10.99),
(2, 'Product2', 'Category2', 20.49),
Example: -- Inserting Values

b). UPDATE:
 Definition: The UPDATE statement in SQL is a DML command used to modify existing
records in a table based on specified conditions.

 SQL Query:
-- Update the price of a product with ProductID 1
UPDATE Products
SET Price = 12.99

Example: -- Updating salary for employee with ID 4

-- Before UPDATE
22
-- After UPDATE

23
c). DELETE:
 Definition: The DELETE statement in SQL is a DML command used to remove records from
a table based on specified conditions.

 SQL Query:

-- Delete a specific product with ProductID 2


DELETE FROM Products
WHERE ProductID = 2;

Example: -- Deleting employee with ID 5

24
-- Before DELETE

-- After DELETE

25
 IMPLEMENTATION OF DIFFERENT TYPES OF FUNCTIONS
WITH SUITABLE EXAMPLES
a). Number Function:
 Explanation: Number functions in SQL perform operations on numeric data types. In this
example, we use the ABS() function to get the absolute value of an employee's salary and
SQRT() to calculate the square root of the salary.

 Example Code: -- Number function example: ROUND

SELECT SUM(Price) AS TotalPrice


FROM Products;

26
b). Aggregate Function:
 Explanation: Aggregate functions operate on sets of values and return a single result. The
AVG() function calculates the average salary, and MAX() finds the maximum salary in the
'employees' table.

 Example Code: -- Aggregate function example: AVG (Average)

SELECT AVG(Price) AS AveragePrice


FROM Products;

27
c). Character Function:
 Explanation: Character functions manipulate string data in SQL. The CONCAT() function
combines the employee's name and salary into a sentence, while UPPER() converts the
employee's name to uppercase.

 Example Code: -- Character function example: (Concatenation)

SELECT CONCAT(ProductName, ' - ', Category) AS ProductInfo


FROM Products;

28
d). Conversion Function:
 Explanation: Conversion functions change the data type of a value. In this example, we use
CAST() to convert the salary to an integer and CONVERT() to transform the employee ID
into a string.

 Example Code: -- Conversion function example: CAST (Convert)

SELECT ProductName, CAST(Price AS INT) AS PriceInteger


FROM Products;

29
e). Date Function:
 Explanation: Date functions manipulate date and time values in SQL. The CURRENT_DATE
function retrieves the current date, and DATEADD() adds three months to the current date for
the employee with ID 4.

 Example Code: -- Date function example: GETDATE

-- Select data from the Products table and include the current date
SELECT ProductID, ProductName, Category, Price, GETDATE() AS Today
FROM Products;

30
 IMPLEMENTATION OF DIFFERENT TYPES OF
OPERATORS IN SQL
a). Arithmetic Operators:
 Explanation: Perform mathematical operations on values.

 Example Code: -- Increase the age of all students by 1

UPDATE Products
SET Date = GETDATE()
WHERE ProductID = 1;

31
b). Comparison Operators:

 Explanation: Compare values and return true or false.

 Example Code: -- -- Select Products where price less than 20.00

SELECT * FROM Products


WHERE Price > 20.00;

32
c). Logical Operators:

 Explanation: Combine conditions in queries.

 Example Code: -- Select products that are either in 'Electronics' category or


have a price less than $50.00

-- Select products that are either in 'Electronics' category or have a price greater than $50.00
SELECT *
FROM Products
WHERE Category = 'Electronics' OR Price < 50.00;

33
d). SPECIAL OPERATOR:

 Explanation: used for pattern matching in string comparisons.


Example: -- -- Select products whose product name starts with Product1'

SELECT *
FROM Products
WHERE ProductName LIKE 'Product1%';

34
5. SET OPERATOR:

 Explanation: Combines the results of two or more SELECT statements and


removes duplicate rows.
 Example: -- -- Combine the list of products in 'Electronics' with the list of
products with a price less than $50.00
-- Combine the list of products in 'Electronics' with the list of products with a price less than
$50.00
SELECT *
FROM Products
WHERE Category = 'Electronics'

UNION

SELECT *
FROM Products

Q9. 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)

35
 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.

36
SOL:

ER DIAGRAM:

37
Table Creation:
I. PUBLISHER
SQL Query

CREATE TABLE PUBLISHER (


Name VARCHAR(15) PRIMARY KEY,
Address VARCHAR(15),
Phone VARCHAR(20)
);

Insert Values:

INSERT INTO PUBLISHER VALUES


('Rupa Publications', '789 Pine St, Villageland', '111-222-3333'),
('Sahitya Akademi', '303 Birch St, Suburbia', '000-111-2222'),
('Orient BlackSwan', '202 Maple St, Ruralville', '777-888-9999'),
('Penguin India', '123 Main St, Cityville', '123-456-7890'),
('Random House India', '101 Cedar St, Countryside', '444-555-6666'),
('Navakarnataka Publications', '505 Elm St, Hamlet', '666-777-8888'),
('Hindi Sahitya Sadan', '404 Redwood St, Metropolis', '333-444-5555'),
('Jaico Publishing House', '456 Oak St, Townsville', '987-654-3210');

38
II. BOOK
SQL Query

CREATE TABLE BOOK (


Book_id INT PRIMARY KEY,
Title VARCHAR(15),
Publisher_Name VARCHAR(15),
Pub_Year INT
);

39
Insert Values:

INSERT INTO BOOK VALUES


III.
(1, 'The Guide', 'Penguin India', 2000),
(2, 'The Immortals of Meluha', 'Jaico Publishing House', 2010),
(3, 'The White Tiger', 'Rupa Publications', 2008),
(4, 'The God of Small Things', 'Random House India', 1997),
(5, 'My Experiments with Truth', 'Sahitya Akademi', 1927),
(6, 'The Alchemist', 'Orient BlackSwan', 1988),
(7, 'A Suitable Boy', 'Hindi Sahitya Sadan', 1993),
(8, 'Discovery of India', 'Navakarnataka Publications', 1946);

BOOK AUTHORS
SQL Query:

CREATE TABLE BOOK_AUTHORS (


Book_id INT,
Author_Name VARCHAR(15)
);

Insert Values:

INSERT INTO BOOK_AUTHORS VALUES


(1, 'Rajnish Kumar Nayan'),
40
(2, 'Amish Tripathi'),
(3, 'Aravind Adiga'),
IV. LIBRARY BRANCH
SQL Query :

CREATE TABLE LIBRARY_BRANCH (


Branch_id INT PRIMARY KEY,
Branch_Name VARCHAR(15),
Address VARCHAR(15)
);

41
Insert Values:
INSERT INTO LIBRARY_BRANCH VALUES
(1, 'City Library', '123 Main St, Cityville'),
(2, 'Town Library', '456 Oak St, Townsville'),
(3, 'Village Library', '789 Pine St, Villageland'),
(4, 'Countryside Library', '101 Cedar St, Countryside');

42
BOOK COPIES

SQL Query:

CREATE TABLE BOOK_COPIES (


Book_id INT,
Branch_id INT,
No_of_Copies INT,
PRIMARY KEY (Book_id, Branch_id)
);

Insert Values :

INSERT INTO BOOK_COPIES VALUES


(1, 1, 5),
(2, 1, 3),
(3, 2, 2),
(4, 2, 4),
(5, 3, 1),
(6, 3, 6),
(7, 4, 3),
(8, 4, 2);

V. BOOK LENDING
SQL Query:

CREATE TABLE BOOK_LENDING (


Book_id INT, 43

Branch_id INT,
Insert Values:

INSERT
VI. INTO BOOK_LENDING VALUES
(1, 1, 101, '2023-02-15', '2023-03-15'),
(2, 1, 101, '2023-04-20', '2023-05-20'),
(3, 2, 103, '2023-06-10', '2023-07-10'),
(4, 2, 104, '2023-01-05', '2023-02-05'),
(5, 3, 105, '2023-03-01', '2023-04-01'),
(6, 3, 101, '2023-05-15', '2023-06-15'),
(7, 4, 101, '2023-01-20', '2023-02-20'),
(8, 4, 103, '2023-04-05', '2023-05-05');

CARD
SQL Query:

-- CARD
CREATE TABLE CARD (
Card_No INT PRIMARY KEY
);
INSERT INTO CARD VALUES
(101),
(102),
(103),
(104),
(105);

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

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;

2. Get the particulars of borrowers who have borrowed more than 3 books,

45
but from Jan 2023 to June 2023.
Sol:

SELECT CARD_NO, COUNT(*) AS BooksBorrowed


FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN '2023-01-01' AND '2023-06-30'
GROUP BY CARD_NO
HAVING COUNT(*) > 3;

46
3. Delete a book in BOOK table. Update the contents of other tables to reflect
this data manipulation operation.
Sol:

-- Delete from BOOK_LENDING first to avoid foreign key constraints


DELETE FROM BOOK_LENDING WHERE BOOK_ID = 1;

-- Delete from BOOK_AUTHORS table


DELETE FROM BOOK_AUTHORS WHERE Book_id = 1;

-- Delete from BOOK_COPIES table


DELETE FROM BOOK_COPIES WHERE Book_id = 1;

-- Delete from BOOK table


DELETE FROM BOOK WHERE Book_id = 1;

47
48
49
4. Partition the BOOK table based on year of publication. Demonstrate its
working with a simple query.
Sol:

-- Create range partitions for BOOK table based on the year of publication
CREATE PARTITION FUNCTION YearPartitionFunction (INT)
AS RANGE RIGHT FOR VALUES (1950, 1960, 1970, 1980, 1990, 2000, 2010, 2020);

-- Create a scheme to associate with the partition function


CREATE PARTITION SCHEME YearPartitionScheme
AS PARTITION YearPartitionFunction
ALL TO ([PRIMARY]);

-- Simple query to demonstrate partitioning


SELECT *
FROM BOOK
WHERE Pub_Year >= 1990 AND Pub_Year < 2000;

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

CREATE VIEW AvailableBooks AS


SELECT B.Book_id, B.Title, BC.No_of_Copies
FROM BOOK B
JOIN BOOK_COPIES BC ON B.Book_id = BC.Book_id
WHERE BC.No_of_Copies > 0;
-- Query to select from the view
SELECT * FROM AvailableBooks;

Q10.CONSIDER THE FOLLOWING SCHEMA FOR ORDER DATABASE:

I. SALESMAN (Salesman_id, Name, City, Commission)


II. CUSTOMER (Customer_id, Cust_Name, City, Grade, Salesman_id)
III. 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 salesmen and indicate those who have and don’t have customers in their
cities

(Use UNION operation.)

51
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.

ER DIAGRAM:

52
53
Table Creation:

1. SALESMAN
Sql Query:

CREATE TABLE SALESMAN (


Salesman_id INT PRIMARY KEY,
Name VARCHAR(15),
INSERT INTO SALESMAN VALUES
City VARCHAR(15),
(1001, 'John',DECIMAL(5,
Commission 'Bangalore', 0.12),
2)
); (2001, 'Michael', 'Delhi', 0.10),
(3001, 'Sarah', 'Mumbai', 0.08),
Insert Values:
(4001, 'Alex', 'Chennai', 0.15),
(5001, 'Emily', 'Kolkata', 0.18),
(6001, 'David', 'Hyderabad', 0.14),
(7001, 'Jessica', 'Bangalore', 0.20),
(8001, 'Chris', 'Delhi', 0.15);

54
55
2. CUSTOMER
Sql Query:

CREATE TABLE CUSTOMER (


Customer_id INT PRIMARY KEY,
Cust_Name VARCHAR(15),
INSERT INTO CUSTOMER VALUES
City VARCHAR(15),
(1002,
Grade 'Alice
INT, Sharma', 'Bangalore', 2, 1001),
(2002, 'Raj Kumar',
Salesman_id INT, 'Delhi', 1, 2001),
(3002, 'Sara KEY
FOREIGN Singh', 'Mumbai', 3, REFERENCES
(Salesman_id) 3001), SALESMAN(Salesman_id)
); (4002, 'Gupta Anil', 'Chennai', 2, 2001),
(5002, 'Verma Neha', 'Kolkata', 1, 5001),
(6002, 'Saxena Rahul', 'Hyderabad', 3, 2001),
(7002, 'Kumar Vikas', 'Bangalore', 2, 7001),
(8002, 'Verma Suresh', 'Delhi', 1, 8001);

Insert Values:

56
57
3. ORDERS
Sql Query:

CREATE TABLE ORDERS (


Ord_No INT PRIMARY KEY,
Purchase_Amt DECIMAL(8, 2),
INSERT INTODATE,
Ord_Date ORDERS VALUES
(109, 4500.00,INT,
Customer_id '2023-01-01', 1002, 1001),
(110, 2800.75,INT,
Salesman_id '2023-01-02', 2002, 2001),
(111, 7500.50,
FOREIGN KEY'2023-01-02', 3002,REFERENCES
(Customer_id) 3001), CUSTOMER(Customer_id),
(112, 1100.25,
FOREIGN KEY'2023-01-03', 4002,
(Salesman_id) 2001),
REFERENCES SALESMAN(Salesman_id)
);(113, 5500.50, '2023-01-03', 5002, 5001),
(114, 3700.00, '2023-01-04', 6002, 6001),
Insert
(115,Values:
6500.25, '2023-01-04', 7002, 2001),
(116, 1400.75, '2023-01-05', 8002, 8001);

Queries:

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


Sol:

58
SELECT COUNT(*) AS AboveAvgCustomers
FROM CUSTOMER
WHERE Grade > (SELECT AVG(Grade) FROM CUSTOMER WHERE City = 'Bangalore');

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

SELECT S.SALESMAN_ID, S.NAME, COUNT(C.CUSTOMER_ID) AS CustomerCount


FROM SALESMAN S
JOIN CUSTOMER C ON S.SALESMAN_ID = C.SALESMAN_ID
GROUP BY S.SALESMAN_ID, S.NAME
HAVING COUNT(C.CUSTOMER_ID) > 1;
59
3. List all salesmen and indicate those who have and don’t have customers in
their cities (Use UNION operation.)
Sol:

SELECT Name, 'Has Customers' AS Status


FROM SALESMAN
WHERE Salesman_id IN (SELECT DISTINCT Salesman_id FROM CUSTOMER)
UNION
SELECT Name, 'No Customers' AS Status
FROM SALESMAN
60
WHERE Salesman_id NOT IN (SELECT DISTINCT Salesman_id FROM CUSTOMER);
4. . Create a view that finds the salesman who has the customer with the
highest order of a day.
Sol:

CREATE VIEW MaxOrderSalesman AS


SELECT
S.SALESMAN_ID,
S.NAME AS SALESMAN_NAME,
C.CUSTOMER_ID,
MAX(O.PURCHASE_AMT) AS MAX_ORDER_AMOUNT,
O.ORD_DATE
FROM
SALESMAN S
JOIN
CUSTOMER1 C ON S.SALESMAN_ID = C.SALESMAN_ID
JOIN
-- Delete orders
ORDERS O ON associated with salesman
C.CUSTOMER_ID 1000
= O.CUSTOMER_ID
DELETE
GROUP BY FROM ORDERS
WHERE SALESMAN_ID
S.SALESMAN_ID, = 1000;
S.NAME, C.CUSTOMER_ID, O.ORD_DATE;

5. Demonstrate the DELETE operation by removing salesman with id 1000.


All his orders must also be deleted.
Sol:

61
Q11. CONSIDER THE FOLLOWING SCHEMA FOR MOVIE DATABASE:

I. ACTOR(Act_id, Act_Name, Act_Gender)


II. DIRECTOR(Dir_id, Dir_Name, Dir_Phone)
III. MOVIES(Mov_id, Mov_Title, Mov_Year, Mov_Lang, Dir_id)
IV. MOVIE_CAST(Act_id, Mov_id, Role)

62
V. 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.

ER DIAGRAM:

63
Table Creation

64
1. ACTOR
Sql Query:

CREATE TABLE ACTOR (


Act_id INT PRIMARY KEY,
Act_Name VARCHAR(50),
Act_Gender VARCHAR(10)
);

Insert Values:

INSERT INTO ACTOR VALUES


(1, 'Rajat Kapoor', 'Male'),
(2, 'Vidya Balan', 'Female'),
(3, 'Ranveer Singh', 'Male'),
(4, 'Kangana Ranaut', 'Female'),
(5, 'Ranbir Kapoor', 'Male'),
(6, 'Priyanka Chopra', 'Female'),
(7, 'Deepika Padukone', 'Female'),
(8, 'Shahid Kapoor', 'Male');

2. DIRECTOR
Sql Query:

CREATE TABLE DIRECTOR (


Dir_id INT PRIMARY KEY,
Dir_Name VARCHAR(50),
Dir_Phone VARCHAR(15)
);

65
Insert Values:

INSERT INTO DIRECTOR VALUES


(1, 'Anurag Kashyap', '123-456-7890'),
(2, 'Zoya Akhtar', '987-654-3210'),
(3, 'Rajkumar Hirani', '234-567-8901'),
(4, 'Imtiaz Ali', '876-543-2109'),
(5, 'Sanjay Leela Bhansali', '345-678-9012'),
(6, 'Sriram Raghavan', '210-987-6543'),
(7, 'Ayan Mukerji', '789-012-3456'),
(8, 'Gauri Shinde', '456-789-0123');

3. MOVIES
Sql Query:

CREATE TABLE MOVIES (


Mov_id INT PRIMARY KEY,
Mov_Title VARCHAR(100),
INSERT INTO
Mov_Year INT,MOVIES VALUES
(1, 'Gangs ofVARCHAR(20),
Mov_Lang Wasseypur', 2012, 'Hindi', 1),
(2, 'Zindagi
Dir_id INT,Na Milegi Dobara', 2011, 'Hindi', 2),
(3, 'PK', 2014,
FOREIGN KEY'Hindi', 3), REFERENCES DIRECTOR(Dir_id)
(Dir_id)
); (4, 'Jab We Met', 2007, 'Hindi', 4),
(5, 'Padmaavat', 2018, 'Hindi', 5),
Insert Values:
(6, 'Andhadhun', 2018, 'Hindi', 6),
(7, 'Yeh Jawaani Hai Deewani', 2013, 'Hindi', 7),
(8, 'Dear Zindagi', 2016, 'Hindi', 8);

66
4. MOVIE_CAST
Sql Query:

CREATE TABLE MOVIE_CAST ( 67

Act_id INT,
Insert Values:

INSERT INTO MOVIE_CAST VALUES


(1, 1, 'Sardar Khan'),
(2, 2, 'Arjun Saluja'),
(3, 3, 'PK'),
(4, 4, 'Aditya Kashyap'),
(5, 5, 'Alauddin Khilji'),
(6, 6, 'Akash'),
(7, 7, 'Naina Talwar'),
(8, 8, 'Dr. Jehangir Khan');

5. RATING
Sql Query:

CREATE TABLE RATING (


Mov_id INT PRIMARY KEY,
Rev_Stars INT,
INSERT INTO RATING
FOREIGN VALUES
KEY (Mov_id) REFERENCES MOVIES(Mov_id)
(1,);4),
(2, 5),
(3, 4),
(4, 5),
(5, 4),
(6, 5),
(7, 3),
(8, 4);

Insert Values:

68
69
Queries:

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


Sol:

SELECT Mov_Title
FROM MOVIES
WHERE Dir_id = (SELECT Dir_id FROM DIRECTOR WHERE Dir_Name = 'Anurag
Kashyap');

70
2. Find the movie names where one or more actors acted in one or more
movies.
Sol:

SELECT Mov_Title
FROM MOVIES
WHERE Mov_id IN (
SELECT Mov_id
FROM MOVIE_CAST
GROUP BY Mov_id
HAVING COUNT(Act_id) >= 1
);

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

SELECT DISTINCT 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;

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.
Sol:

SELECT M.Mov_Title, R.Rev_Stars


FROM MOVIES M
JOIN RATING R ON M.Mov_id = R.Mov_id 71
ORDER BY M.Mov_Title;
5. Update rating of all movies directed by ‘Steven Spielberg’ to 5 KL
Sol:

UPDATE RATING
SET Rev_Stars = 5
WHERE Mov_id IN (SELECT Mov_id FROM MOVIES WHERE Dir_id = (SELECT
Dir_id FROM DIRECTOR WHERE Dir_Name = 'Steven Spielberg'));

72
PART – B
MINI PROJECT

1. Entities:
 PRODUCTS:

73
 Attributes: ProductID (Primary Key), ProductName, SupplierID (Foreign
Key), Price, StockQuantity
 SUPPLIERS:
 Attributes: SupplierID (Primary Key), SupplierName, ContactPerson,
ContactNumber
 CUSTOMERS:
 Attributes: CustomerID (Primary Key), CustomerName, ContactNumber,
Address
 ORDERS:
 Attributes: OrderID (Primary Key), CustomerID (Foreign Key),
OrderDate
 ORDER_DETAILS:
 Attributes: OrderID (Foreign Key), ProductID (Foreign Key), Quantity
(Primary Key)
2. Relationships:
 SUPPLIERS - PRODUCTS:
 One-to-Many relationship: A supplier can supply multiple products, but
each product is supplied by one supplier.
 PRODUCTS - ORDERS:
 Many-to-Many relationship: A product can be part of multiple orders, and
an order can contain multiple products. This relationship is resolved by the
ORDER_DETAILS table.
 SUPPLIERS - ORDERS:
 Many-to-Many relationship: A supplier can be associated with multiple
orders, and an order can have multiple suppliers through the products it
contains.
 CUSTOMERS - ORDERS:
 One-to-Many relationship: A customer can place multiple orders, but each
order is placed by one customer.
 ORDERS - ORDER_DETAILS:
 One-to-Many relationship: An order can have multiple order details, but
each order detail is associated with one order.
3. Cardinalities:
 PRODUCTS - SUPPLIERS:

74
 Supplier (1) ----< Supplies >---- (Many) Products
 PRODUCTS - ORDERS:
 Order (Many) ----< Contains >---- (Many) Products
 SUPPLIERS - ORDERS:
 Supplier (Many) ----< Supplies >---- (Many) Orders
 CUSTOMERS - ORDERS:
 Customer (1) ----< Places >---- (Many) Orders
 ORDERS - ORDER_DETAILS:
 Order (1) ----< Contains >---- (Many) Order Details

1. Suppliers:

75
CREATE TABLE SUPPLIERS (
SupplierID INT PRIMARY KEY,
SupplierName VARCHAR(50),
ContactPerson VARCHAR(50),
ContactNumber VARCHAR(15)
);

2.. Customers
CREATE TABLE CUSTOMERS (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
ContactNumber VARCHAR(15),
Address VARCHAR(100)
);

76
3. ORDER DETAILS

CREATE TABLE ORDER_DETAILS (


OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (OrderID) REFERENCES ORDERS(OrderID),
FOREIGN KEY (ProductID) REFERENCES PRODUCTS(ProductID)
);

77
4.orders
CREATE TABLE ORDERS (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES CUSTOMERS(CustomerID)
);

78
5.products
CREATE TABLE PRODUCTS (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50),
SupplierID INT,
Price DECIMAL(10, 2),
StockQuantity INT,
FOREIGN KEY (SupplierID) REFERENCES SUPPLIERS(SupplierID)
);

79
80
Application Development Process:
4. Choose a programming language (e.g., Python, Java) and a database management system
(e.g., MySQL, PostgreSQL).
5. Establish a connection between the application and the database.
6. Implement functions or methods to interact with the database, such as adding new products,
processing orders, etc.
7. Develop a user interface to input data and display information.
8. Test the application to ensure proper functionality.
9. Deploy the application for use in a real-world setting.

81

You might also like