My ISM Lab File Anirudh
My ISM Lab File Anirudh
Session 2023-24
Definition of SQL
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.
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 – .
Different relational database management systems implement SQL with some variations.
Common SQL-based DBMS include:
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.
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."
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.
1. Entity (Rectangle):
2. Relationship (Diamond):
3. Cardinality (Lines):
Indicates the number of instances of one entity that can be related to another entity.
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.
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.
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.
Represents an entity that plays a role in a many-to-many relationship and usually has
attributes of its own.
Entities:
Relationships:
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.
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.
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.
Collection Types:
Arrays:
Represents a fixed-size collection of elements of the same type. Array elements are accessed
by their index.
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:
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:
3. Unique Constraint:
4. Check Constraint:
Normalization:
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.
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
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
Gender CHAR(1),
DateOfBirth DATE,
Major VARCHAR(50)
);
select * from Student;
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;
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;
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)
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)
);
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)
Salesman_id)
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)
);
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
RATING(Mov_id, Rev_Stars)
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.
Act_Gender VARCHAR(10)
);
Dir_Name VARCHAR(255),
Dir_Phone VARCHAR(20)
);
Mov_Title VARCHAR(255),
Mov_Year INT,
Mov_Lang VARCHAR(50),
Dir_id INT,
);
Act_id INT,
Mov_id INT,
Role VARCHAR(255),
);
Rev_Stars INT,
);
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'
);