









Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










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
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.
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
SELECT StudentName, Marks FROM Students WHERE Marks >= 80;
5. Creating and Changing Tables
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 Students ADD COLUMN City VARCHAR(50);
ALTER TABLE Students ADD COLUMN AdmissionDate DATE;
The exact syntax for altering columns differs across database systems.
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 * 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.
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.
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.
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.
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.
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
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.
-- 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.
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
18. Answer Key / Sample Solutions
-- 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.