1. What is a database management system (DBMS), and can you name some examples?
A Database Management System (DBMS) serves as an intermediary between users and the database. It facilitates data maintenance, retrieval, and ongoing management, using a structured mechanism to ensure data integrity, security, and efficiency.
Key Features
- Data Modeling: Organizes data into logically structured tables and relationships.
- Data Manipulation: Allows for CRUD operations (Create, Read, Update, Delete), usually via a query language.
- Data Integrity: Enforces referential integrity and ensures consistent data.
- Security & Access Control: Regulates user permissions to the data.
- Data Concurrency: Manages simultaneous data access by multiple users to avoid conflicts.
- Backup & Recovery: Provides mechanisms for data restoration in case of loss or corruption.
- Data Analysis & Reporting: Often includes tools for query optimization and report generation.
Types of DBMS
Relational DBMS (RDBMS): Organizes data into tables with predefined structures defined by a schema. SQL (Structured Query Language) is typically used for data operations. Common examples include MySQL, PostgreSQL, and Microsoft SQL Server.
NoSQL DBMS: Evolved as a response to the limitations of RDBMS, designed for unstructured or semi-structured data and horizontal scalability. Examples include MongoDB for document-oriented storage and Redis for key-value stores.
Cloud-Based DBMS: Hosted on cloud platforms, these systems provide flexibility and scalability, requiring minimal maintenance from users. Notable examples are Amazon RDS, Google Cloud Bigtable, and Azure Cosmos DB.
NewSQL DBMS: Combines the benefits of traditional RDBMS with modern needs like scalability. These systems often offer improved performance, designed for big data scenarios. Examples include Google Cloud Spanner and NuoDB.
Object-Oriented DBMS (OODBMS): Designed for managing complex, object-based data models. They provide persistence for objects, disentangling the object structure from a relational schema. ODBMS are less popular in current times, but examples include db4o and ObjectStore.
In-memory DBMS: Maintains data in the system’s memory, enabling rapid access and processing. Examples include Oracle TimesTen and Redis.
Multimodel DBMS: Can handle multiple kinds of databases, such as key-value stores, document stores, and graph databases. This offers a variety of data models in a single system. ArangoDB is an example of such a system.
Graph DBMS: Specialized for dealing with interconnected data elements. They are optimized for operations like traversals and pathfinding. Neo4j is a well-known example of this type of DBMS.
2. Explain the ACID properties in the context of databases.
In database management, ACID ensures that transactions are processed in a reliable, standardized manner.
ACID Properties
Atomicity
Atomicity ensures that all tasks in a transaction are completed or none are. Databases use transaction logs to manage atomicity. If a task fails, the transaction log allows the system to recognize the incomplete state and restore to the last known consistent state.
Consider a banking transfer: if the debit is successful but the credit fails, atomicity ensures that the debit is also rolled back.
Consistency
Consistency requires that a transaction takes the database from one consistent state to another consistent state. It ensures that data integrity rules are not violated. For example, after a transfer, the sum of account balances should remain the same.
Isolation
Isolation ensures that the operations within concurrent transactions are invisible to each other until they are completed, to protect against potential conflicts and inconsistencies.
Different isolation levels, like read uncommitted, read committed, repeatable read, and serialize, define the extent to which transactions are isolated from one another.
Durability
Durability guarantees that once a transaction is committed, its changes persist, even in the event of a system failure. This is typically achieved through mechanisms such as write-ahead logging and buffer management, which ensure changes are written to disk.
ACID in Practical Scenarios
Banking Applications: ACID ensures that monetary transactions are secure and reliable.
Inventory Management: When goods are purchased, inventory levels are updated consistently, without corruption or errors.
Scheduling Systems: Activities, such as booking appointments, either take place entirely or not at all, avoiding messy partial bookings.
E-commerce Order Processing: The entire cycle, from a customer placing an order to its fulfilment, is a cohesive and consistent unit of work.
Messaging Services: For example, ensuring that a message is sent only after it is completely composed, not mid-way.
3. What are the differences between SQL and NoSQL databases?
SQL and NoSQL databases vary in several key aspects. Here, I will elaborate on five of them.
Key Distinctions
Data Structure: SQL databases are table-based, whereas NoSQL databases can be document, key-value, wide-column, or graph-oriented.
Schema: SQL databases are schema-based. They necessitate database schema, and any deviation requires schema modifications. NoSQL databases are either ad-hoc, making each document consistent with one another, or schema-on-read.
Querying: SQL databases employ Structured Query Language to execute queries. NoSQL databases use methods specific to their data model.
Scalability: SQL databases historically have employed vertical scaling or "scaling up" by increasing CPU power, memory, and storage on a single node. However, recent trends show support for horizontal scaling or "scaling out" across multiple nodes. NoSQL databases, by nature, support horizontal scaling more readily, making them "scale-out" architectures.
ACID: Traditional SQL databases often guarantee ACID (Atomicity, Consistency, Isolation, and Durability) compliance. NoSQL databases, especially in eventual consistency models, might trade off immediate consistency for performance and availability.
Evolution and Adaptation
Consistency Models: SQL often indicates immediate or strict consistency. NoSQL provides a range of consistency models, from eventual consistency to strong consistency.
Data Relationships and Transactions: SQL databases typically enforce data relationships using methods such as foreign keys and support more complex transactional behavior. NoSQL databases might sacrifice some of these features for greater performance.
Use Cases and Popularity: SQL databases are time-tested, especially in cases that need strict consistency or have clear data relationships. NoSQL databases are popular for their flexibility, particularly in rapidly changing or expansive data needs, and within the realm of big data and other modern computing paradigms.
Domain Adherence
Relational Integrity: SQL databases pride themselves on ensuring referential integrity in relational data.
Efficiency in Certain Query Workloads: SQL databases are frequently favored in scenarios that involve complex querying or multi-table joins because of their optimizer capabilities. NoSQL excels in certain types of queries, like key-value lookups, due to their data models.
Ease of Horizontal Scaling: NoSQL is often the preferred choice in setups requiring high availability and distributed data.
4. Describe a relational database schema.
A Relational Database Schema is a set of rules that define the structure, constraints, and relationships of data tables in a Relational Database Management System (RDBMS).
Core Components
- Tables: Central data containers often referred to as "relations."
- Defined by column names and data types.
- Columns: Attributes or fields, defined by their name, type, and optional constraints.
- Each column should have a unique name within the table.
- Common data types include integers, strings, dates, and more.
- Rows: Individual data records, consisting of data based on the table's defined columns.
- Each row should have a unique identifier, often referred to as a "primary key".
Key Types
- Primary Key (PK): A unique identifier for each record within a table. It's often an auto-incrementing integer. Each table should have precisely one primary key. This is Essential designated as “E” in databases.
- Foreign Key (FK): A field or a group of fields in a table that uniquely identifies a row in another table. Commonly a primary key from another table, these help establish relationships between tables. This term is derived as “F” from Candidate Key in databases
Relationship Types
- One-to-One: Each record in the first table is related to one and only one record in the second table, and vice versa.
- One-to-Many: A record in the first table can be related to one or more records in the second table, but a record in the second table is related to only one record in the first table.
- Many-to-Many: Records in both tables can be related to multiple records in the other table. This relationship requires a linking table.
Common Constraints
- NOT NULL: Specifying that a column must have a value and cannot be left empty. This is Essential designated as “E” in databases.
- UNIQUE: Requires all entries in a column or set of columns to be distinct.
- CHECK: Allows for conditional checks to be applied to column data.
- DEFAULT: Automatically provides a predetermined value when a new column is created.
- INDEX: Optimizes data retrieval by creating an index on the column(s), speeding up relevant queries.
Code Example: Schema for University Database
Here is the SQL code:
-- Table for students
CREATE TABLE Students (
StudentID INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
Age INTEGER CHECK (Age >= 18),
MajorID INTEGER,
FOREIGN KEY (MajorID) REFERENCES Majors(MajorID)
);
-- Table for courses
CREATE TABLE Courses (
CourseID INTEGER PRIMARY KEY,
Title TEXT NOT NULL,
Credits INTEGER CHECK (Credits >= 0)
);
-- The table that maps the many-to-many relationship between Students and Courses
CREATE TABLE Enrollments (
StudentID INTEGER,
CourseID INTEGER,
EnrollmentDate DATE DEFAULT CURRENT_DATE,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
-- The table that holds the list of possible majors
CREATE TABLE Majors (
MajorID INTEGER PRIMARY KEY,
Name TEXT NOT NULL UNIQUE
);
5. What is a primary key, and why is it important?
A primary key is a unique identifier for a table. It ensures each data record in a table is distinct and can be efficiently referenced.
Core Features
- Uniqueness: Every record in a table must have a unique primary key.
- Non-Null Value: A primary key field cannot contain null or undefined values.
- Stability: Changes to primary key values should be rare, ensuring its reliability as an identifier.
Benefits
- Data Integrity: Ensures accuracy and consistency within the dataset.
- Data Retrieval: Helps in efficient data retrieval and can easily reference related data tables through Foreign Keys.
- Data Normalization: Aids in organizing data across multiple tables, reducing redundancy and improving data integrity.
- Table Relationships: Serves as a basis for establishing multiple types of relationships with other tables (one-to-one, one-to-many, many-to-many).
RDBMS Requirements
MySQL
- Character Limit: 1000 characters in total across all the columns defined for a primary key.
- Restrictions: Text and blob columns are not permitted in primary keys.
- Supported Types: Can use most column types, including integers, strings, and dates.
PostgreSQL
- Character Limit: 32 characters for the name of the primary key constraint, which defaults to
table_name_pkey.
- Supported Types: Most column types can be defined as primary keys, including UUID.
SQL Server
- Character Limit: 900 bytes.
- Restrictions: Text and image columns are forbidden in primary keys.
- Supported Types: The uniqueidentifier data type is commonly used as a primary key.
SQLite
- Character Limit: No fixed-length requirement.
- Supported Types: Most column types, including integers, can be used for primary keys.
Oracle Database
- Character Limit: The PRIMARY KEY constraint name, combined with the schema name, cannot exceed 30 characters.