DBMS TT2
SQL Practice Queries
Database Schema Overview
Q1: Retrieve the names of all students in the CSE department.
SELECT name
FROM Students
WHERE department = 'CSE';
Q2: Find the course names and credits for all courses offered by the ECE department.
SELECT course_name, credits
FROM Courses
WHERE department = 'ECE';
Q3: Get the student IDs and names of students who have scored an A grade in any course.
SELECT S.student_id, S.name
FROM Students S
JOIN Grades G ON S.student_id = G.student_id
WHERE G.grade = 'A';
Q4: List the course IDs and names of courses that have more than 3 credits.
SELECT course_id, course_name
FROM Courses
WHERE credits > 3;
Q5: Find the average grade of students in the MECH department.
SELECT AVG(CASE G.grade
WHEN 'A' THEN 10
WHEN 'B' THEN 8
WHEN 'C' THEN 6
WHEN 'D' THEN 4
WHEN 'F' THEN 0
END) AS average_grade
FROM Students S
JOIN Grades G ON S.student_id = G.student_id
WHERE S.department = 'MECH';
Q6: Retrieve the student IDs and names of students who have not scored any grade.
SELECT student_id, name
FROM Students
WHERE student_id NOT IN (SELECT student_id FROM Grades);
Q7: Find the course IDs and names of courses that have been taken by more than 5 students.
SELECT C.course_id, C.course_name
FROM Courses C
JOIN Grades G ON C.course_id = G.course_id
GROUP BY C.course_id, C.course_name
HAVING COUNT(DISTINCT G.student_id) > 5;
Q8: Get the department-wise count of students.
SELECT department, COUNT(*) AS student_count
FROM Students
GROUP BY department;
Q9: List the student IDs and names of students who have scored an A grade in a course offered by the CSE department.
SELECT S.student_id, S.name
FROM Students S
JOIN Grades G ON S.student_id = G.student_id
JOIN Courses C ON G.course_id = C.course_id
WHERE G.grade = 'A' AND C.department = 'CSE';
Q10: Find the course IDs and names of courses that have the highest credits.
SELECT course_id, course_name
FROM Courses
WHERE credits = (SELECT MAX(credits) FROM Courses);
💻 Extra SQL Practice Problems – Q&A Format
🔹 Database: mxsales
Q1. How many customers bought a dartboard?
SELECT COUNT(*)
FROM m0sales.retail_sales_feb
WHERE product = 'Dartboard';
Q2. How many customers bought a treadmill?
SELECT COUNT(*)
FROM m0sales.retail_sales_feb
WHERE product = 'Treadmill';
Q3. How many customers bought something from the Computer department?
SELECT COUNT(DISTINCT customer)
FROM m0sales.retail_sales_feb
WHERE department = 'Computer';
Q4. What were the names of customers who bought an Organizer?
SELECT DISTINCT Customer
FROM m0sales.retail_sales_feb
WHERE product='Organizer';
Smith Ben
Martin Dan
Jones Mathew
Rose Clair
Lopez Maria
Q5. What are the names of customers who had Dakic as a sales rep?
SELECT DISTINCT Customer
FROM m0sales.retail_sales_feb
WHERE sales_rep='Dakic';
Sweet Mary
Rose Clair
Martin Dan
Jovanovic Robert
Smith Ben
Q6. Which sales rep had the highest total sales?
SELECT Sales_Rep, SUM(Total)
FROM m0sales.retail_sales_feb
GROUP BY Sales_Rep
ORDER BY SUM(Total) DESC;
Jenkin: 9158.00
Dakic: 7874.70
Salt: 6429.85
Q7. Which sales rep sold the most laser printers?
SELECT Sales_Rep, SUM(Quantity)
FROM m0sales.retail_sales_feb
WHERE Product='Laser Printer'
GROUP BY Sales_Rep
ORDER BY SUM(Quantity) DESC;
Dakic: 14
Jenkin: 9
Salt: 3
Q8. How many total items were sold overall?
SELECT SUM(Quantity)
FROM m0sales.retail_sales_feb;
Q9. What is the least expensive product in the database?
SELECT Product
FROM m0sales.retail_sales_feb
WHERE Price = (SELECT MIN(Price) FROM m0sales.retail_sales_feb);
Q10. What is the name of the customer who had Sheedy as a sales rep and bought a Color Scanner?
SELECT Customer
FROM m0sales.retail_sales_feb
WHERE Sales_Rep='Sheedy' AND Product='Color Scanner';
Q11. Which customers bought products more than $1000 and what were the names of those products?
SELECT Customer, Product
FROM m0sales.retail_sales_feb
WHERE Price > 1000;
Nelson Mary – Walkman
Dinh Tran – Walkman
Rose Clair – Digital Camera
🔹 Database: moviedb
Q12. Which customer lives at the address “1531 Sal Drive?”
SELECT customer.first_name, customer.last_name
FROM moviedb.customer, moviedb.address
WHERE customer.address_id = address.address_id
AND address='1531 Sal Drive';
Q13. How many customers live in Canada?
SELECT COUNT(*)
FROM moviedb.customer, moviedb.address, moviedb.city, moviedb.country
WHERE customer.address_id = address.address_id
AND address.city_id = city.city_id
AND city.country_id = country.country_id
AND country.country='Canada';
Q14. Which country has the most customers?
SELECT Country, COUNT(*)
FROM moviedb.customer, moviedb.address, moviedb.city, moviedb.country
WHERE customer.address_id = address.address_id
AND address.city_id = city.city_id
AND city.country_id = country.country_id
GROUP BY Country
ORDER BY COUNT(*) DESC;
Q15. What is the postal code of Cape Coral?
SELECT postal_code
FROM moviedb.address, moviedb.city
WHERE address.city_id = city.city_id
AND city.city='Cape Coral';
Q16. What is the largest single payment made by Emily Diaz?
SELECT payment.amount
FROM moviedb.payment, moviedb.rental, moviedb.customer
WHERE payment.rental_id=rental.rental_id
AND rental.customer_id=customer.customer_id
AND customer.first_name='Emily'
AND customer.last_name='Diaz'
AND payment.amount = (
SELECT MAX(payment.amount)
FROM moviedb.payment, moviedb.rental, moviedb.customer
WHERE payment.rental_id=rental.rental_id
AND rental.customer_id=customer.customer_id
AND customer.first_name='Emily'
AND customer.last_name='Diaz'
);
Q17. Which customers made the largest single payment in India? What was the amount?
SELECT payment.amount, customer.first_name, customer.last_name
FROM moviedb.payment, moviedb.rental, moviedb.customer,
moviedb.address, moviedb.city, moviedb.country
WHERE payment.rental_id=rental.rental_id
AND rental.customer_id=customer.customer_id
AND customer.address_id=address.address_id
AND address.city_id=city.city_id
AND city.country_id=country.country_id
AND country.country='India'
AND payment.amount = (
SELECT MAX(payment.amount)
FROM moviedb.payment, moviedb.rental, moviedb.customer,
moviedb.address, moviedb.city, moviedb.country
WHERE payment.rental_id=rental.rental_id
AND rental.customer_id=customer.customer_id
AND customer.address_id=address.address_id
AND address.city_id=city.city_id
AND city.country_id=country.country_id
AND country.country='India'
);
Adam Gooch
Sherri Rhodes
Erik Guillen
Tim Cary
Lena Jensen
Anita Morales
John Farnsworth
Bradley Motley (x2)
Lori Wood
Joshua Mark
Nancy Thomas
Module 4
reference : Module 4.pptx - Google Drive
CREATE TABLE Emp (
Emp_ID int NOT NULL,
Name varchar(20) NOT NULL,
Age int,
Address varchar(100) DEFAULT 'INDIA',
PRIMARY KEY(Emp_ID)
);
This creates the Emp table with columns and constraints.
ALTER TABLE Emp
ADD Email varchar(100);
This adds an Email column to the Emp table.
DROP TABLE Emp;
This removes the Emp table and all its data.
1.
SELECT department, CONCAT(name, ' has id-', id) AS employee_code
FROM employee;
Here, employee_code is an alias for the concatenated result.
1.
SELECT e.id, e.name, d.dept_name
FROM employee e
INNER JOIN department d ON e.dept_id = d.dept_id;
Simplifies complex queries.
Avoids ambiguity in multi-table joins.
Improves output readability.
1.
SELECT id, name, salary, dept_name
FROM employee LEFT JOIN department
ON employee.dept_id = department.dept_id;
Includes all employees, even those without a department.
1.
SELECT id, name, dept_name
FROM employee RIGHT JOIN department
ON employee.dept_id = department.dept_id;
Includes all departments, even those without employees.
1.
-- Simulated in MySQL using UNION:
SELECT * FROM employee LEFT JOIN department ON ...
UNION
SELECT * FROM employee RIGHT JOIN department ON ...;
SELECT * FROM employee FULL JOIN department ON ...;
SQL can be integrated into procedural programming languages (e.g., Python, Java, C#) using APIs like JDBC, ODBC, or libraries such as SQLAlchemy.
1.
import sqlite3
conn = sqlite3.connect("company.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM Emp WHERE Salary > 5000")
results = cursor.fetchall()
Here, Python executes SQL queries to fetch data.
1.
String sql = "INSERT INTO Emp VALUES (" + id + ", '" + name + "')";
statement.executeUpdate(sql);
1.
CREATE PROCEDURE GetEmployees()
AS
BEGIN
SELECT * FROM Emp;
END;
Called via cursor.callproc("GetEmployees") in Python.
CREATE TRIGGER backup_trigger
AFTER DELETE ON Main
FOR EACH ROW
INSERT INTO Backup VALUES (OLD.id, OLD.salary);
1.
2.
3.
Overheads due to automatic execution.
Hard to debug.
1.
SQL verifies user identities via credentials.
CREATE LOGIN User1 WITH PASSWORD = 'Secure123';
1.
SQL controls access using GRANT/REVOKE .
GRANT SELECT ON Emp TO User1; -- Allows read access
REVOKE DELETE ON Emp FROM User1; -- Blocks deletes
CREATE ROLE Manager;
GRANT INSERT, UPDATE TO Manager;
1.
SQL enforces data integrity via constraints (Page 3-5, 99):
1.
CREATE TABLE Emp (Age INT CHECK (Age >= 18));
2.
CREATE TABLE Emp (Emp_ID INT PRIMARY KEY);
3.
CREATE TABLE Emp (
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Dept(Dept_ID)
);
4.
CREATE TABLE Emp (Email VARCHAR(100) UNIQUE);
Module 5
Insertion, updation, and deletion anomalies arise due to improper database design, particularly when there is redundancy and lack of normalization in a relation.
Occurs when certain data cannot be inserted into a table without the presence of other data. For example, if instructor and department data are stored in the same relation ( inst_dept ), we cannot insert a new department unless we also insert an instructor.
➤ Reference implied from Page 16.8
Happens when the same data is stored at multiple places, and updating it in one place but not in others leads to inconsistency. For instance, changing the budget of a department in one tuple and forgetting in others leads to inconsistency.
➤ Reference implied from Page 16.8
Occurs when deletion of data about one entity results in unintentional loss of data about another. For example, deleting the only instructor in a department may remove all data about that department if both are stored in one table.
➤ Reference implied from Page 16.8-16.9
These anomalies indicate the need for decomposition and normalization to achieve a better relational design.
A relation is in 1NF if all its attribute domains are atomic — meaning each field contains only indivisible values. This prevents multi-valued or composite attributes. For example, a customer should not have a set of phone numbers in one attribute.
➤ Reference: Page 16.12-16.14
A relation is in 2NF if it is in 1NF and all non-prime attributes are fully functionally dependent on the entire candidate key. It removes partial dependencies — i.e., no non-prime attribute should depend on a part (subset) of a composite key.
➤ Not found in document; based on standard DBMS definition.
A relation is in 3NF if for every functional dependency α → β , one of the following holds:
1.
It is a trivial dependency (β ⊆ α),
2.
α is a superkey , or
3.
Every attribute in β – α is a prime attribute (i.e., part of some candidate key).
3NF relaxes BCNF slightly to preserve dependencies.
➤ Reference: Page 17.9
Two key properties of a good relational schema decomposition are:
1.
This ensures that the original relation can be perfectly reconstructed by joining the decomposed relations. It avoids loss of information and maintains data integrity.
Example: Decomposing a relation R(A, B, C) into R1(A, B) and R2(B, C) is lossless if B is a key for either R1 or R2.
➤ Reference: Page 16.10, also concept supported on Page 17.7
2.
A decomposition is dependency-preserving if all functional dependencies in the original relation can be enforced without needing to recombine relations. This helps in efficient constraint checking on individual tables.
➤ Reference: Page 17.8
Both properties are essential to ensure the decomposition is practical and does not lead to anomalies or inefficiencies.
Sure! Here's the next set of answers, written in an exam-friendly format , each detailed enough for 4 marks , with page references when found in the document, and clear notes for generated content.
The major aim of denormalization is to improve the performance of a database by reducing the number of joins required during data retrieval. In highly normalized databases, data is spread across many tables. While this design minimizes redundancy and anomalies, it can lead to complex queries and slower performance due to multiple joins.
Denormalization introduces some controlled redundancy by combining tables or adding derived attributes to reduce query time. It is especially useful in read-heavy applications such as data warehousing or reporting systems.
However, it comes at the cost of increased storage and the potential for data anomalies during updates.
➤ Not found in attached document; based on standard DBMS knowledge.
A Multivalued Dependency (MVD) occurs in a relation when one attribute in a table uniquely determines another set of attributes , independently of other attributes.
Formally, in a relation R, an MVD X ↠ Y holds if, for each value of X, there exists a set of values for Y that is independent of the values in the rest of the attributes (Z = R - X - Y).
Example:
If a person can have multiple phone numbers and multiple email addresses, but these are independent of each other, then:
MVDs are used to detect and resolve redundancy beyond functional dependencies and lead to Fourth Normal Form (4NF) decomposition.
➤ Not found in attached document; based on standard DBMS knowledge.
A Functional Dependency (FD) is a constraint between two sets of attributes in a relation. Given a relation R, a functional dependency α → β means that if two tuples agree on attributes α, they must also agree on attributes β.
In other words, the value of α uniquely determines the value of β.
For example, in a student relation:
This means that a particular Roll_No determines a unique combination of Name and Department.
Functional dependencies are fundamental for:
They form the theoretical basis for normal forms and relational schema design .
➤ Reference: Page 16.20–16.22 (Definition and Examples)
The closure of a set of functional dependencies (F) , denoted as F⁺ , is the set of all functional dependencies that can be logically inferred from F using inference rules such as Armstrong’s Axioms (reflexivity, augmentation, transitivity).
Similarly, attribute closure (α⁺) refers to all attributes functionally determined by a set of attributes α.
➤ Reference: Page 17.16–17.18
A minimal cover is a simplified version of a set of functional dependencies that is:
1.
2.
Has no redundant dependencies ,
3.
And has no extraneous attributes in any dependency.
It is used to optimize and simplify the set of dependencies while ensuring that no necessary constraints are lost.
➤ Reference: Page 17.13–17.14
Certainly! Here are detailed, exam-ready answers for questions 8 to 10, each tailored for a 4-mark response. I've included references to the attached PDF where applicable and supplemented with information from reliable external sources when necessary.
Consider the following unnormalized table:
StudentID
Name
Courses
Institute
101
Naveen Kumar
DBMS, OS
IIT Delhi
102
Utkarsh Tiwari
CN, COA
IIT Bombay
102
Utkarsh Tiwari
OS
IIT Kanpur
To address these issues, we apply normalization:
1.
StudentID
Name
Course
Institute
101
Naveen Kumar
DBMS
IIT Delhi
101
Naveen Kumar
OS
IIT Delhi
102
Utkarsh Tiwari
CN
IIT Bombay
102
Utkarsh Tiwari
COA
IIT Bombay
102
Utkarsh Tiwari
OS
IIT Kanpur
2.
StudentID
Name
101
Naveen Kumar
102
Utkarsh Tiwari
CourseID
CourseName
C1
DBMS
C2
OS
C3
CN
C4
COA
StudentID
CourseID
Institute
101
C1
IIT Delhi
101
C2
IIT Delhi
102
C3
IIT Bombay
102
C4
IIT Bombay
102
C2
IIT Kanpur
Reference: Normalization Process in DBMS
In the context of database normalization and decomposition:
Ensures that all original attributes of a relation are present in the decomposed relations.
No attribute from the original schema is lost during decomposition.
Essential for reconstructing the original relation from its decomposed parts.
Ensures that all functional dependencies from the original relation are still enforceable in the decomposed relations without the need to recombine them.
Important for maintaining data integrity and enforcing constraints efficiently.
Consider a relation R(A, B, C) with functional dependencies:
A → B
B → C
Decomposing R into:
R1(A, B)
R2(B, C)
A → B is preserved in R1.
B → C is preserved in R2.
Therefore, the decomposition preserves dependencies.
Reference: Properties of Relational Decomposition
Consider a relation R(StudentID, Course, Instructor) where:
A student can enroll in multiple courses.
Each course has a single instructor.
If this relation is not decomposed:
Instructor information is repeated for every student enrolled in the course.
By decomposing R into:
R1(Course, Instructor)
R2(StudentID, Course)
We achieve:
Reference: Decomposition In DBMS
Module 6
ref doc : Lesson11-Transactions.pdf - Google Drive
Sure, I can expand each answer with more detail:
1) Explain the ACID properties of a transaction.
Answer:
The ACID properties are fundamental principles that ensure reliable transaction processing in database systems. They are as follows:
The ACID properties are fundamental principles that ensure reliable transaction processing in database systems. They are as follows:
Additional Insight from Internet Sources:
Modern databases, including those used in NoSQL systems like MongoDB, extend ACID compliance to handle scenarios such as multi-document transactions. These databases support atomicity at the document level and ensure consistency through mechanisms like snapshot isolation. However, distributed systems often struggle with full ACID compliance due to challenges like network latency, failure recovery, and partitioning. To address these, systems may rely on protocols like the two-phase commit protocol, which is designed to ensure consistency in distributed transactions.
Modern databases, including those used in NoSQL systems like MongoDB, extend ACID compliance to handle scenarios such as multi-document transactions. These databases support atomicity at the document level and ensure consistency through mechanisms like snapshot isolation. However, distributed systems often struggle with full ACID compliance due to challenges like network latency, failure recovery, and partitioning. To address these, systems may rely on protocols like the two-phase commit protocol, which is designed to ensure consistency in distributed transactions.
2) What concurrency anomalies (lost update, inconsistent retrievals, uncommitted dependency) are possible if there is no concurrency control?
Answer:
Without concurrency control, various anomalies can arise that disrupt the consistency and correctness of the database. The most common anomalies include:
Without concurrency control, various anomalies can arise that disrupt the consistency and correctness of the database. The most common anomalies include:
1.
2.
3.
Additional Insight from Internet Sources:
Other concurrency anomalies include:
Other concurrency anomalies include:
Concurrency control techniques such as locking, timestamp ordering, and optimistic concurrency control are designed to prevent these anomalies. Methods like two-phase locking (2PL) and multi-version concurrency control (MVCC) help serialize access to shared data, ensuring consistency while allowing transactions to run concurrently.
3) What is a recoverable schedule?
Answer:
Arecoverable schedule is one in which transactions are scheduled in such a way that no transaction commits before all the transactions whose data it has read have committed. This ensures that, in the event of a failure, no transaction’s commit will be invalidated by the rollback of another transaction on which it depends. The key property of a recoverable schedule is that it prevents cascading rollbacks, which could otherwise propagate the effects of a failure across multiple transactions.
A
Additional Insight from Internet Sources:
A schedule can be serializable but still not recoverable. For example, in a non-recoverable schedule, T2 might commit before T1, even though T2 reads data written by T1. Acascadeless schedule , which is a stricter form of recoverability, prevents transactions from reading uncommitted data altogether. Cascadeless schedules are often enforced in practical systems to avoid the need for cascading rollbacks in case of failures.
A schedule can be serializable but still not recoverable. For example, in a non-recoverable schedule, T2 might commit before T1, even though T2 reads data written by T1. A
4) What is final state serializability?
Answer:
Final state serializability is a weaker form of serializability where the database’s final state after executing a schedule must match the final state of some serial execution, regardless of the intermediate states. This property does not require the schedule to be serializable at every intermediate step, only that the end result of the transactions is the same as if the transactions were executed serially.
Additional Insight from Internet Sources:
While conflict serializability is easier to implement and verify through methods like two-phase locking, final-state serializability allows for more flexibility and concurrency in schedules. However, it is computationally expensive to verify, as it requires checking all possible serial execution orders. This makes it less commonly used in practice, especially in large-scale databases where performance is critical.
While conflict serializability is easier to implement and verify through methods like two-phase locking, final-state serializability allows for more flexibility and concurrency in schedules. However, it is computationally expensive to verify, as it requires checking all possible serial execution orders. This makes it less commonly used in practice, especially in large-scale databases where performance is critical.
5) What is serializability?
Answer:
Serializability is the property that ensures the concurrent execution of transactions yields the same results as if the transactions were executed serially in some order, one after the other, without any interleaving. Serializability guarantees that the database remains in a consistent state, avoiding issues such as lost updates, dirty reads, and inconsistent retrievals.
VSR, or View Serializability (from internet source), is a form of serializability that defines equivalence between schedules based on their views of the data. Two schedules are view equivalent if they meet specific conditions related to how transactions read the initial values of data items, read values written by other transactions, and perform the final writes on data items.
The conditions for View Serializability are as follows (from internet source):
1.
Both schedules must perform the same set of actions.
2.
If transaction Ti reads the initial value of a data item in one schedule, it must also do so in the other schedule.
3.
If transaction Ti reads a value written by transaction Tj in one schedule, it must also do so in the other schedule.
4.
If transaction Ti performs the final write on a data item in one schedule, it must also do so in the other schedule.
View Serializability is less restrictive than Conflict Serializability. This means that some schedules that are view serializable are not conflict serializable. Determining whether a schedule is view serializable can be complex.
CSR, or Conflict Serializability (from internet source), is a type of serializability that focuses on conflicting operations between transactions. Two operations are considered to be in conflict if they belong to different transactions, operate on the same data item, and at least one of them is a write operation. A schedule is conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations.
In simpler terms, if a schedule can be reordered through a series of swaps of non-conflicting operations to match a serial schedule, then it is conflict serializable. Conflict Serializability ensures that the concurrent execution of transactions does not lead to any inconsistencies caused by conflicting operations. Conflict Serializability is stricter than View Serializability.
2PL, or Two-Phase Locking Protocol (Page 2, Lesson 11), is a concurrency control protocol designed to ensure serializability in database transactions. It operates by dividing a transaction's execution into two distinct phases: a growing phase and a shrinking phase.
1.
2.
By adhering to these two phases, 2PL ensures that the resulting schedule is conflict serializable, thereby preventing concurrency anomalies and maintaining data consistency. The strict enforcement of lock acquisition and release helps avoid issues such as lost updates, dirty reads, and inconsistent retrievals. (from internet source) There are variations of 2PL, such as strict 2PL, which releases locks only after the transaction has either committed or aborted, providing an even higher level of data integrity.
Locks are mechanisms used in database management systems to control concurrent access to data items (Page 2, Lesson 11).
A precedence graph (not explicitly found in the attached document, but related to serializability on Page 2, Lesson 11) is a directed graph used to determine the serializability of a schedule.
Consider the following schedule with transactions T1, T2, and T3:
1.
T1: Write(A)
2.
T2: Write(B)
3.
T3: Write(C)
4.
T2: Read(A)
5.
T3: Read(B)
6.
T1: Read(C)
T1 writes A, and T2 reads A, so there is an edge from T1 to T2.
T2 writes B, and T3 reads B, so there is an edge from T2 to T3.
T3 writes C, and T1 reads C, so there is an edge from T3 to T1.
This creates a cycle: T1 -> T2 -> T3 -> T1, indicating the schedule is not conflict serializable.
The main feature of timestamping concurrency control (not explicitly found in the attached document, but related to concurrency control on Page 2, Lesson 11) is the assignment and use of unique timestamps to order transaction execution (from internet source).
One example of deadlock prevention (Page 2, Lesson 11) is to impose a total ordering of all lockable data items and require that a transaction can only request locks in increasing order (from internet source).
If data item A has ID 1 and data item B has ID 2, a transaction that needs to lock both A and B must first lock A before attempting to lock B.
This prevents a scenario where transaction T1 holds a lock on A and is waiting for B, while transaction T2 holds a lock on B and is waiting for A, thus avoiding a deadlock.
PYQ


SELECT DISTINCT Age
FROM patients
ORDER BY Age ASC;
SQL
SELECT FName, LName
FROM patients
WHERE allergies IS NULL;
SQL
UPDATE patients
SET allergies = 'NKA'
WHERE allergies IS NULL;
SQL
SELECT patient_id, FName
FROM patients
WHERE FName LIKE 'S%S' AND LENGTH(FName) = 6;
v) Show the city and the total number of patients in the city. Order from most to least patients and then by city name ascending.
SQL
SELECT City, COUNT(patient_id) AS TotalPatients
FROM patients
GROUP BY City
ORDER BY TotalPatients DESC, City ASC;