Docsity

SQL and Database Management Complete Notes with Examples and 100 Practice Questions, Study notes of Computer science

Toggle sidebar
bg1
SQL & DATABASE
MANAGEMENT
Complete Beginner-to-Exam Notes
Concepts • Syntax • Worked Examples • Practice Queries • MCQs • Viva Questions
STUDY GUIDE LEVEL FORMAT
Computer Science / Programming Beginner • School & College Lecture Notes + Practice
Learning outcome: Understand databases, design simple tables, write SQL queries, connect related tables, and
revise key DBMS concepts for assignments and examinations.
Prepared as a student-friendly learning resource. Examples use standard SQL; some syntax may vary slightly between MySQL,
PostgreSQL, SQLite, SQL Server, and Oracle.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download SQL and Database Management Complete Notes with Examples and 100 Practice Questions and more Study notes Computer science in PDF only on Docsity!

SQL & DATABASE

MANAGEMENT

Complete Beginner-to-Exam Notes

Concepts • Syntax • Worked Examples • Practice Queries • MCQs • Viva Questions

STUDY GUIDE LEVEL FORMAT Computer Science / Programming Beginner • School & College Lecture Notes + Practice

Learning outcome: Understand databases, design simple tables, write SQL queries, connect related tables, and revise key DBMS concepts for assignments and examinations.

Prepared as a student-friendly learning resource. Examples use standard SQL; some syntax may vary slightly between MySQL, PostgreSQL, SQLite, SQL Server, and Oracle.

Contents

  1. Database Fundamentals
  2. DBMS and Relational Model
  3. Keys and Constraints
  4. Introduction to SQL
  5. Creating and Changing Tables
  6. INSERT, SELECT, UPDATE and DELETE
  7. Filtering, Sorting and Operators
  8. SQL Functions and GROUP BY
  9. Joins and Subqueries
  10. Database Design and Normalization
  11. Transactions, Indexes and Views
  12. ER Diagrams and Relationships
  13. Worked Mini Project: Student Database
  14. 100 Practice Questions / Query Prompts
  15. Multiple-Choice Questions
  16. Viva Questions
  17. Quick Revision Sheet
  18. Answer Key / Sample Solutions

Relational database

A relational database organises data into tables. Tables can be connected through keys. For example, a Students table may contain each student's details, while a Marks table stores multiple marks linked to a student ID.

Advantages and limitations

  • Advantages: structured data, querying, consistency rules, security controls, backup options, and relationships.
  • Limitations: planning and maintenance require skill; poorly designed queries can be slow; setup and administration may add cost or complexity. 3. Keys and Constraints

Term Meaning Example Primary key Uniquely identifies each row; cannot be NULL StudentID Candidate key A minimal field or field set that could uniquely identify a rowEmail, if unique Foreign key References a key in another table Marks.StudentID → Students.StudentID Composite key Key made from multiple columns StudentID + SubjectID UNIQUE Prevents duplicate values in a column or column set Email NOT NULL Requires a value StudentName CHECK Requires a condition to be true Marks >= 0 DEFAULT Uses a value when none is supplied Status DEFAULT 'Active'

A primary key should be stable and unique. A foreign key helps preserve referential integrity, meaning a child record cannot reference a missing parent record when the relevant constraint is enforced.

4. Introduction to SQL

SQL stands for Structured Query Language. It is used to define database structures, manipulate records, retrieve information, and manage permissions.

SQL category Purpose Common commands DDL — Data Definition LanguageDefine structures CREATE, ALTER, DROP, TRUNCATE DML — Data Manipulation LanguageChange records INSERT, UPDATE, DELETE DQL — Data Query Language Retrieve records SELECT DCL — Data Control LanguagePermissions GRANT, REVOKE TCL — Transaction Control LanguageManage transactions COMMIT, ROLLBACK, SAVEPOINT

SQL writing rules

  • SQL keywords are commonly written in uppercase for readability, but SQL is usually case-insensitive for keywords.
  • Text values are placed inside single quotes, such as 'Kirti'.
  • A semicolon commonly ends a statement.
  • Use clear table and column names.
  • Avoid UPDATE or DELETE without a WHERE clause unless every row is intended to change.

SELECT StudentName, Marks FROM Students WHERE Marks >= 80;

5. Creating and Changing Tables

CREATE DATABASE and CREATE TABLE

CREATE DATABASE SchoolDB;

CREATE TABLE Students ( StudentID INT PRIMARY KEY, StudentName VARCHAR(60) NOT NULL, ClassName VARCHAR(10), Age INT CHECK (Age >= 3), Email VARCHAR(100) UNIQUE );

INT stores whole numbers. VARCHAR(n) stores variable-length text up to a defined limit. DATE stores dates. DECIMAL(p,s) is useful for exact decimal values such as prices. Data types and constraint support vary by database system.

ALTER TABLE

ALTER TABLE Students ADD COLUMN City VARCHAR(50);

ALTER TABLE Students ADD COLUMN AdmissionDate DATE;

The exact syntax for altering columns differs across database systems.

DROP and TRUNCATE

  • DROP TABLE Students removes the table definition and its data.
  • TRUNCATE TABLE Students removes all rows while retaining the table structure in systems that support it.
  • These operations can be difficult or impossible to reverse without a backup; practise them only in a test database. 6. INSERT, SELECT, UPDATE and DELETE

INSERT

INSERT INTO Students (StudentID, StudentName, ClassName, Age, Email) VALUES (101, 'Asha', 'XI', 16, '[email protected]');

INSERT INTO Students (StudentID, StudentName, ClassName, Age) VALUES (102, 'Rohan', 'XI', 17);

SELECT

SELECT * FROM Students; SELECT StudentName, ClassName FROM Students; SELECT DISTINCT ClassName FROM Students;

The asterisk (*) returns all columns. In production queries, naming the required columns is often clearer and may reduce unnecessary data retrieval.

GROUP BY ClassName;

SELECT ClassName, AVG(Marks) AS AverageMarks FROM Results GROUP BY ClassName HAVING AVG(Marks) >= 70;

WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY. Every selected column that is not aggregated generally needs to be included in GROUP BY.

Scalar functions

  • UPPER(text) / LOWER(text): change letter case.
  • LENGTH(text) or a system-specific equivalent: count characters/bytes.
  • ROUND(number, digits): round a numeric value.
  • CURRENT_DATE: current date in systems that support this standard form.
  • COALESCE(a, b, ...): return the first non-NULL expression.

Function names and details can differ between database systems, so check the documentation for the system being used.

9. Joins and Subqueries

A JOIN combines rows from related tables. Suppose Students(StudentID, StudentName) and Results(StudentID, Subject, Marks) are related by StudentID.

INNER JOIN

SELECT s.StudentName, r.Subject, r.Marks FROM Students AS s INNER JOIN Results AS r ON s.StudentID = r.StudentID;

Returns rows with matching keys in both tables.

LEFT JOIN

SELECT s.StudentName, r.Subject, r.Marks FROM Students AS s LEFT JOIN Results AS r ON s.StudentID = r.StudentID;

Returns every row from the left table and matching rows from the right. If no match exists, right-side columns are NULL.

Other joins

  • RIGHT JOIN returns all rows from the right table plus matching left-side rows; not all systems use the same support.
  • FULL OUTER JOIN returns matched rows and unmatched rows from both sides; support varies.
  • CROSS JOIN returns every possible combination of rows from both tables.

Subquery

SELECT StudentName FROM Students WHERE StudentID IN ( SELECT StudentID FROM Results WHERE Marks >= 90 );

A subquery is a query nested inside another query. It can appear in WHERE, FROM, SELECT, or other locations depending on the query and database system.

10. Database Design and Normalization

Good database design aims to avoid unnecessary duplication and update anomalies.

Common anomalies

  • Insertion anomaly: a fact cannot be added without adding unrelated information.
  • Update anomaly: the same fact must be changed in several places.
  • Deletion anomaly: removing one record accidentally removes another useful fact.

Normalization

Form Basic idea 1NF Each cell holds a single value; no repeating groups; rows can be identified. 2NF In 1NF, and each non-key attribute depends on the whole candidate key, not just part of a composite key. 3NF In 2NF, and non-key attributes do not depend transitively on a key.

Example: instead of storing a student's name repeatedly in every subject mark row, store student details in Students and subject marks in Results, linked by StudentID. This reduces repetition and makes updates safer.

Normalization requires examining functional dependencies and candidate keys. A simple rule of thumb is useful for beginners, but real schemas should be checked carefully.

11. Transactions, Indexes and Views

ACID properties

Property Meaning Atomicity A transaction succeeds as a unit or is rolled back. Consistency A transaction preserves defined rules and constraints. Isolation Concurrent transactions are controlled to reduce interference. Durability Committed changes persist despite failures, subject to system guarantees.

START TRANSACTION; UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1; UPDATE Accounts SET Balance = Balance + 500 WHERE AccountID = 2; COMMIT;

Transaction-start syntax varies by system. If an error occurs before commit, ROLLBACK can undo uncommitted work in transactional systems.

Step 3 — Useful queries

-- 1. List all students SELECT * FROM Students;

-- 2. Maths results of 80 or more SELECT * FROM Results WHERE Subject = 'Maths' AND Marks >= 80;

-- 3. Student names with their results SELECT s.StudentName, r.Subject, r.Marks FROM Students s JOIN Results r ON s.StudentID = r.StudentID;

-- 4. Average marks by subject SELECT Subject, AVG(Marks) AS AverageMarks FROM Results GROUP BY Subject;

-- 5. Highest mark SELECT MAX(Marks) AS HighestMark FROM Results;

Project extension ideas: add a Teachers table, create an Enrolments table, store attendance, build a view for high scorers, and practise safe updates inside transactions.

14. 100 Practice Questions / Query Prompts

Use the tables Students(StudentID, StudentName, ClassName, Age, City), Results(ResultID, StudentID, Subject, Marks), and Books(BookID, Title, Author, Price, Available). Some prompts require you to create or extend a table first.

  1. Create a database named SchoolDB.
  2. Create a Students table with StudentID as primary key.
  3. Add StudentName as a NOT NULL column.
  4. Add a City column to Students.
  5. Create a Results table with ResultID as primary key.
  6. Add a foreign key from Results.StudentID to Students.StudentID.
  7. Insert one student record.
  8. Insert three student records.
  9. Display all students.
  10. Display only StudentName and City.
  11. List distinct cities.
  12. Find students in Class XI.
  13. Find students aged 16 or above.
  14. Find students younger than 18.
  15. Find students from Lucknow.
  16. Find students from either Lucknow or Varanasi.
  17. Find students whose names start with A.
  18. Find names containing 'an'.
  19. Find students whose City is NULL.
  1. Sort students alphabetically by name.
  2. Sort students by age from highest to lowest.
  3. Display the first five students using syntax supported by your DBMS.
  4. Count all students.
  5. Count students in each class.
  6. Count students in each city.
  7. Find the minimum age.
  8. Find the maximum age.
  9. Find the average age.
  10. Find students aged between 15 and 17 inclusive.
  11. Find students not in Class XI.
  12. Update one student's city.
  13. Change a student's class using StudentID.
  14. Delete a test student by StudentID.
  15. Display results with marks above 75.
  16. Find marks between 60 and 90.
  17. Find all Maths results.
  18. Find all results except English.
  19. Sort results from highest mark to lowest.
  20. Find the highest mark.
  21. Find the lowest mark.
  22. Calculate average marks by subject.
  23. Count results by subject.
  24. Show subjects whose average is at least 70.
  25. Join Students and Results to show student names with marks.
  26. Use LEFT JOIN to include students without results.
  27. Find names of students who have a result of 90 or above.
  28. Find students who have a Maths result.
  29. Find students who have no matching result record.
  30. Display each student and their number of result records.
  31. Display each student's average marks.
  32. Find the student ID with the highest result mark.
  33. Create a Books table with a primary key.
  34. Insert three books.
  35. Display books costing less than 500.
  36. Display books costing 200 to 800.
  1. Describe a deletion anomaly.
  2. Explain all four ACID properties.
  3. Explain why indexes can improve SELECT performance.
  4. Name one disadvantage of too many indexes.
  5. Start a transaction, make a test update, then roll it back.
  6. Demonstrate COMMIT using a safe test table.
  7. Write a query to find the second-highest mark (state your DBMS syntax).
  8. Write a query to find duplicate city values.
  9. Write a query to list students with no city recorded.
  10. Design an ER model for a small library.
  11. Describe two security practices for a student database.
  12. Back up a practice database using your DBMS's supported method. **15. Multiple-Choice Questions
  13. Which command retrieves data?** A. SELECT B. UPDATE C. DROP D. GRANT 2. Which key uniquely identifies a row? A. Foreign key B. Primary key C. Duplicate key D. Sort key 3. Which clause filters rows before grouping? A. HAVING B. ORDER BY C. WHERE D. GROUP BY 4. Which clause sorts query output? A. SORT B. ORDER BY C. ARRANGE D. GROUP 5. Which function counts rows? A. SUM B. AVG C. COUNT D. MAX 6. Which JOIN keeps all rows from the left table? A. INNER JOIN B. LEFT JOIN C. CROSS JOIN D. SELF JOIN 7. Which constraint prevents NULL values? A. UNIQUE B. DEFAULT C. NOT NULL D. INDEX 8. Which SQL category includes CREATE TABLE? A. DDL B. DML C. DCL D. TCL 9. Which command changes existing records? A. INSERT B. UPDATE C. CREATE D. SELECT 10. Which expression tests for missing values? A. = NULL B. IS NULL C. NULL = D. LIKE NULL 11. Which ACID property means committed changes persist? A. Atomicity B. Consistency C. Isolation D. Durability 12. A many-to-many relationship is commonly implemented using: A. A junction table B. One text column C. A view only D. An index only 13. Which command removes rows matching a condition? A. DELETE B. DROP DATABASE C. CREATE D. GRANT

14. Which aggregate returns the mean? A. SUM B. AVG C. COUNT D. MIN 15. Which normal form removes partial dependency on part of a composite candidate key? A. 1NF B. 2NF C. 3NF D. No form 16. Which operator matches a pattern? A. BETWEEN B. LIKE C. IS D. JOIN 17. What does a foreign key reference? A. A related key in another or the same table B. A file name C. A password D. A chart 18. Which command can undo uncommitted transaction work? A. COMMIT B. ROLLBACK C. SELECT D. CREATE 19. What is a view? A. A saved query presented like a table B. A physical keyboard C. A primary key D. A backup only 20. Which is a likely disadvantage of an index? A. It always deletes data B. It uses storage and can slow writes C. It prevents SELECT D. It replaces all constraints 16. Viva Questions

  1. What is data? What is information?
  2. Define a database and DBMS.
  3. Give three examples of DBMS software.
  4. What is a table?
  5. Differentiate a row and a column.
  6. What is a schema?
  7. What is SQL?
  8. Differentiate DDL and DML.
  9. What is a primary key?
  10. What is a foreign key?
  11. What is a candidate key?
  12. What is a composite key?
  13. Why are constraints useful?
  14. What is the purpose of SELECT?
  15. What does DISTINCT do?
  16. What is the role of WHERE?
  17. Differentiate WHERE and HAVING.
  18. What is GROUP BY?
  19. What is an aggregate function?
  20. Differentiate COUNT(*) and COUNT(column) in handling NULL values.
  21. What does ORDER BY do?
  22. What is a JOIN?

18. Answer Key / Sample Solutions

MCQ answer key

1-A, 2-B, 3-C, 4-B, 5-C, 6-B, 7-C, 8-A, 9-B, 10-B, 11-D, 12-A, 13-A, 14-B, 15-B, 16-B, 17-A, 18-B, 19-A, 20-B.

Sample solutions for selected practice prompts

-- Students in Class XI SELECT * FROM Students WHERE ClassName = 'XI';

-- Students whose names begin with A SELECT * FROM Students WHERE StudentName LIKE 'A%';

-- Number of students in each city SELECT City, COUNT(*) AS Total FROM Students GROUP BY City;

-- Results above the overall average SELECT * FROM Results WHERE Marks > (SELECT AVG(Marks) FROM Results);

-- Find duplicate city values (NULL values are excluded here) SELECT City, COUNT() AS Total FROM Students WHERE City IS NOT NULL GROUP BY City HAVING COUNT() > 1;

-- Students with no results SELECT s.StudentID, s.StudentName FROM Students s LEFT JOIN Results r ON s.StudentID = r.StudentID WHERE r.StudentID IS NULL;

Practice prompt 99 (second-highest mark) has several valid solutions depending on whether ties count as one rank and on the DBMS. One portable approach for the second-highest distinct mark is:

SELECT MAX(Marks) AS SecondHighest FROM Results WHERE Marks < (SELECT MAX(Marks) FROM Results);

This returns NULL if there is no lower distinct mark. For full solutions, execute each practice query against your own sample schema and verify the output. Database-specific syntax may be required for pagination, backup, transaction start, and certain schema changes.