Files and Databases
File and database questions test how data is stored, retrieved and protected in files and relational tables.
Files and records
A file is a named collection of related data stored on secondary storage. Text files store characters (often ASCII/Unicode) and can be opened in a text editor; binary files store data in the machine’s internal representation and need the correct program to interpret them. CSV files store rows as lines and fields separated by commas; fields containing commas are quoted. In Python, open(path, mode) uses modes such as 'r', 'w', 'a' and 'rb'; always close a file or use a with block.
Databases
A database is an organised collection of related data managed by a DBMS. A relational table has rows (records) and columns (fields). A primary key uniquely identifies each row and cannot be NULL; a foreign key references a primary key in another table and enforces referential integrity. SQL retrieves and manipulates data.
Worked example
Table Student(roll PRIMARY KEY, name, marks). Query: SELECT name FROM Student WHERE marks > 80 ORDER BY name ASC; This returns only names, filters rows by marks, and sorts alphabetically. SELECT * would return every column. DELETE FROM Student WHERE roll = 5 removes one row; DROP TABLE Student removes the table structure and all rows.
Traps that cost marks
- Forgetting quotes around text values in SQL; numbers do not need them.
- Confusing DELETE (rows) with DROP (table/structure).
- Assuming a primary key may contain duplicates or NULL.
- Opening a file in 'w' mode when existing data must be preserved; 'w' truncates.