Question: Create a STUDENT table and insert records.
Answer (SQL / Python Code):
CREATE TABLE Student (
RollNo INT PRIMARY KEY,
Name VARCHAR(30),
Class INT,
Marks INT
);
INSERT INTO Student VALUES
(1,'Aman',12,85),
(2,'Riya',12,90),
(3,'Karan',11,78),
(4,'Simran',12,92),
(5,'Neha',11,88);
Output:
Table created successfully
5 rows inserted
Question: Perform ALTER TABLE operations.
Answer (SQL / Python Code):
ALTER TABLE Student ADD Age INT;
ALTER TABLE Student MODIFY Name VARCHAR(40);
ALTER TABLE Student DROP Age;
Output:
Table altered successfully
Question: Update marks of a student using UPDATE command.
Answer (SQL / Python Code):
UPDATE Student
SET Marks = 95
WHERE RollNo = 2;
Output:
1 row updated
Question: Display records using ORDER BY in ascending and descending order.
Answer (SQL / Python Code):
SELECT * FROM Student ORDER BY Marks ASC;
SELECT * FROM Student ORDER BY Marks DESC;
Output:
Records displayed in ascending and descending order
Question: Delete records from table using DELETE command.
Answer (SQL / Python Code):
DELETE FROM Student
WHERE Class = 11;
Output:
2 rows deleted
Question: Use GROUP BY with aggregate functions.
Answer (SQL / Python Code):
SELECT
Class,
MIN(Marks),
MAX(Marks),
SUM(Marks),
COUNT(*),
AVG(Marks)
FROM Student
GROUP BY Class;
Output:
Grouped result displayed with MIN, MAX, SUM, COUNT and AVG
Question: Integrate SQL with Python using MySQL connector.
Answer (SQL / Python Code):
import [Link]
con = [Link](
host="localhost",
user="root",
password="root",
database="school"
)
cur = [Link]()
[Link]("SELECT * FROM Student")
for row in cur:
print(row)
[Link]()
Output:
(1, 'Aman', 12, 85)
(2, 'Riya', 12, 95)
(4, 'Simran', 12, 92)