SQL Database Concepts
SQL Database Concepts Interview with follow-up questions
1. What is a schema in SQL and how is it used?
A schema in SQL is a named namespace that organizes database objects — tables, views, indexes, stored procedures, sequences, and functions — into logical groups within a database.
Structure hierarchy:
Database Server
└── Database (or catalog)
└── Schema
├── Tables
├── Views
├── Stored Procedures
├── Functions
└── Indexes
Creating and using schemas:
-- Create a schema
CREATE SCHEMA finance;
CREATE SCHEMA hr;
-- Create objects within a schema
CREATE TABLE finance.accounts (id INT PRIMARY KEY, balance DECIMAL(12,2));
CREATE TABLE hr.employees (id INT PRIMARY KEY, name VARCHAR(100));
-- Query with schema-qualified names
SELECT * FROM finance.accounts;
SELECT * FROM hr.employees;
Default schema: Each database system has a default schema when none is specified:
- PostgreSQL:
public - SQL Server:
dbo - MySQL: schema and database are synonymous (no sub-schema concept)
- Oracle: the user's own schema is the default
Why schemas are used:
- Organization: Separate objects by domain, team, or application module
- Access control: Grant permissions at the schema level instead of per-table
sql GRANT SELECT ON ALL TABLES IN SCHEMA finance TO finance_reader; - Multi-tenant applications: Each tenant gets their own schema in one database
- Namespace isolation: Two schemas can have tables with the same name without conflict
Interview note: In MySQL, CREATE DATABASE and CREATE SCHEMA are synonymous — MySQL does not support sub-schemas. This is a common point of confusion when candidates move between MySQL and PostgreSQL/SQL Server.
Follow-up 1
Can you explain the difference between a database and a schema?
In SQL, a database is a collection of related data that is organized and stored. It includes tables, views, indexes, and other database objects. A database is typically managed by a database management system (DBMS).
On the other hand, a schema is a logical container within a database. It is used to organize and manage database objects. A database can have multiple schemas, and each schema can contain its own set of tables, views, and other objects.
In simple terms, a database is the overall container for data, while a schema is a way to organize and manage the objects within that container.
Follow-up 2
How would you create a new schema in SQL?
To create a new schema in SQL, you can use the CREATE SCHEMA statement. Here is an example:
CREATE SCHEMA schema_name;
Replace schema_name with the desired name for your schema. This statement will create a new schema with the specified name.
You can also specify additional options such as the owner of the schema and the default character set. Here is an example with additional options:
CREATE SCHEMA schema_name
AUTHORIZATION owner_name
DEFAULT CHARACTER SET character_set_name;
Replace owner_name with the desired owner of the schema and character_set_name with the desired character set.
Follow-up 3
What are the benefits of using schemas in SQL?
Using schemas in SQL provides several benefits:
Organization and management: Schemas help in organizing and managing database objects. They provide a logical structure for grouping related tables, views, and other objects.
Security: Schemas allow different users or roles to have different levels of access to different schemas. This helps in enforcing security and access control.
Abstraction: Schemas provide a level of abstraction by separating database objects. This makes it easier to understand and work with large databases.
Scalability: By dividing a database into multiple schemas, it becomes easier to scale and manage the database. Each schema can be managed independently, allowing for better performance and maintenance.
Overall, using schemas in SQL improves the organization, security, and scalability of databases.
2. What are the different types of keys in SQL?
SQL databases use several types of keys, each serving a specific role in data organization and relationship modeling:
Primary Key
Uniquely identifies every row. Non-null, unique, one per table. Usually auto-generated (SERIAL, AUTO_INCREMENT, IDENTITY).
CREATE TABLE employees (employee_id INT PRIMARY KEY, ...);
Foreign Key References a primary (or unique) key in another table, enforcing referential integrity.
FOREIGN KEY (department_id) REFERENCES departments(id)
Unique Key Like a primary key in terms of uniqueness, but allows NULL (one NULL per column in most databases) and a table can have multiple.
UNIQUE (email)
Candidate Key Any minimal set of columns that could serve as a primary key — unique and not null. The primary key is the chosen candidate key; others become alternate keys.
Composite Key A key (primary, foreign, or unique) that spans multiple columns:
PRIMARY KEY (order_id, product_id)
Super Key Any set of columns that uniquely identifies rows — a superset of candidate keys. May include redundant columns.
Surrogate Key A system-generated, meaningless identifier used as a primary key when no natural key exists or when the natural key is unstable.
id BIGSERIAL PRIMARY KEY -- surrogate key
Natural Key A key that exists in the business domain — like email, SSN, or ISBN. Can work as a primary key when values are stable and unique.
Alternate Key
A candidate key that was not chosen as the primary key. Enforced with a UNIQUE NOT NULL constraint.
Interview focus: Most commonly tested — primary key vs unique key, foreign key behavior with cascades, and when to use a surrogate vs natural key.
Follow-up 1
Can you explain what a composite key is?
A composite key is a combination of two or more columns that uniquely identifies a record in a table. It is used when a single column cannot uniquely identify a record. Each column in a composite key contributes to the uniqueness of the key. For example, in a table that stores information about students, a composite key may consist of the student's first name and last name. This combination of columns ensures that each student is uniquely identified in the table.
Follow-up 2
What is the difference between a primary key and a foreign key?
The main difference between a primary key and a foreign key is their purpose and the relationship they establish between tables.
Primary Key: A primary key is a unique identifier for each record in a table. It ensures that each record in the table is uniquely identified and provides a way to access and manipulate the data in the table. A table can have only one primary key, and it cannot contain null values.
Foreign Key: A foreign key is a field in one table that refers to the primary key in another table. It establishes a link between two tables and enforces referential integrity. A table can have multiple foreign keys, and they can contain null values.
Follow-up 3
What is the purpose of a unique key in SQL?
The purpose of a unique key in SQL is to ensure that each value in a column or a combination of columns is unique. It is similar to a primary key, but it allows null values. A unique key can be used to enforce data integrity by preventing duplicate values in a column or a combination of columns. It can also be used to improve query performance by creating an index on the unique key, which allows for faster searching and retrieval of data.
3. What are the different types of constraints in SQL?
SQL constraints enforce data integrity rules on tables and columns. The standard constraint types (with 2026-accurate notes):
NOT NULL Prevents NULL values. Applied per column.
name VARCHAR(100) NOT NULL
UNIQUE All values must be distinct. Allows one NULL per column (in most databases). Multiple UNIQUE constraints allowed per table.
UNIQUE (email)
UNIQUE (country_code, phone_number) -- composite unique
PRIMARY KEY Combines UNIQUE + NOT NULL. One per table. Auto-creates an index.
PRIMARY KEY (id)
PRIMARY KEY (order_id, line_number) -- composite
FOREIGN KEY Enforces referential integrity. Value must exist in the referenced table or be NULL.
FOREIGN KEY (dept_id) REFERENCES departments(id) ON DELETE CASCADE ON UPDATE CASCADE
CHECK Enforces a custom condition. Evaluated on INSERT and UPDATE.
CHECK (salary > 0)
CHECK (end_date >= start_date)
CHECK (status IN ('active','inactive'))
Note: MySQL silently ignored CHECK constraints before version 8.0.16. Since 8.0.16, they are enforced. Always verify behavior for the database version in use.
DEFAULT Provides an automatic fallback value when INSERT omits the column.
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
is_active BOOLEAN DEFAULT TRUE
EXCLUSION (PostgreSQL only) Prevents overlapping values using an operator — useful for preventing double-booking time slots:
EXCLUDE USING GIST (room WITH =, period WITH &&)
-- Prevents two bookings for the same room with overlapping time periods
Note on "INDEX" as a constraint: indexes are not constraints. An index is a performance structure; constraints are integrity rules. A PRIMARY KEY and UNIQUE constraint both auto-create indexes, but indexes themselves are not constraints.
Follow-up 1
How would you use a NOT NULL constraint in SQL?
To use a NOT NULL constraint in SQL, you need to specify it when creating a table or altering an existing table. Here's an example:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT NOT NULL
);
In this example, the name and age columns are defined with the NOT NULL constraint, which means that these columns cannot have NULL values.
Follow-up 2
Can you explain the purpose of a CHECK constraint?
The purpose of a CHECK constraint in SQL is to ensure that all values in a column satisfy a specific condition. It allows you to define a condition that must be true for every row in a table. Here's an example:
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
grade CHAR(1) CHECK (grade IN ('A', 'B', 'C', 'D', 'F'))
);
In this example, the CHECK constraint is used to ensure that the grade column can only have values 'A', 'B', 'C', 'D', or 'F'. Any other value will violate the constraint and result in an error.
Follow-up 3
What is the difference between a UNIQUE constraint and a PRIMARY KEY constraint?
The main difference between a UNIQUE constraint and a PRIMARY KEY constraint is that a UNIQUE constraint allows NULL values, while a PRIMARY KEY constraint does not.
A UNIQUE constraint ensures that all values in a column are unique, but it allows NULL values. This means that you can have multiple rows with NULL values in a column that has a UNIQUE constraint.
On the other hand, a PRIMARY KEY constraint also ensures that all values in a column are unique, but it does not allow NULL values. This means that every row in a table must have a non-NULL value in the column that has the PRIMARY KEY constraint.
In summary, a UNIQUE constraint allows NULL values, while a PRIMARY KEY constraint does not.
4. What are the different data types in SQL?
SQL supports a rich set of data types. The exact names vary by database, but the categories are consistent:
Numeric types:
| Type | Storage | Range / Precision |
|---|---|---|
TINYINT |
1 byte | 0–255 (unsigned) / -128–127 |
SMALLINT |
2 bytes | ±32,767 |
INT / INTEGER |
4 bytes | ±2.1 billion |
BIGINT |
8 bytes | ±9.2 × 10¹⁸ |
DECIMAL(p,s) / NUMERIC(p,s) |
Variable | Exact; use for money |
FLOAT / REAL |
4–8 bytes | Approximate; avoid for money |
Character / String:
| Type | Notes |
|---|---|
CHAR(n) |
Fixed-length, padded with spaces |
VARCHAR(n) |
Variable-length, up to n characters |
TEXT |
Unlimited-length string (PostgreSQL, MySQL) |
NVARCHAR(n) |
Unicode (SQL Server) |
Date / Time:
| Type | Notes |
|---|---|
DATE |
Date only (YYYY-MM-DD) |
TIME |
Time only |
TIMESTAMP / DATETIME |
Date + time |
TIMESTAMPTZ |
Timestamp with time zone (PostgreSQL) |
INTERVAL |
Duration (PostgreSQL, Oracle) |
Boolean:
BOOLEAN/BOOL— TRUE/FALSE/NULL (SQL Server usesBIT: 0/1)
Binary:
BYTEA(PostgreSQL) /BLOB(MySQL) /VARBINARY(SQL Server)
Semi-structured / modern:
JSON/JSONB(PostgreSQL) — native JSON with indexing supportARRAY(PostgreSQL) — arrays of any typeUUID— 128-bit universally unique identifier
Interview tip: Know that DECIMAL/NUMERIC is exact (safe for money) while FLOAT/REAL is approximate (unsafe for money). Know the difference between CHAR (fixed, padded) and VARCHAR (variable length).
Follow-up 1
What is the difference between CHAR and VARCHAR data types?
The main difference between CHAR and VARCHAR data types in SQL is that:
CHAR is a fixed-length character data type, which means it always occupies a fixed amount of storage space regardless of the actual length of the data. For example, if you define a CHAR(10) column, it will always occupy 10 characters of storage space, even if you store a shorter string.
VARCHAR is a variable-length character data type, which means it only occupies the necessary amount of storage space based on the actual length of the data. For example, if you define a VARCHAR(10) column and store a string of length 5, it will only occupy 5 characters of storage space.
In summary, CHAR is suitable for storing fixed-length strings, while VARCHAR is suitable for storing variable-length strings.
Follow-up 2
How would you use the DATE data type in SQL?
The DATE data type in SQL is used to store dates without any time component. It allows you to store dates in the format 'YYYY-MM-DD'. Here's an example of how you can use the DATE data type in SQL:
CREATE TABLE employees (
id INT,
name VARCHAR(50),
hire_date DATE
);
INSERT INTO employees (id, name, hire_date)
VALUES (1, 'John Doe', '2022-01-01');
SELECT * FROM employees;
In this example, we create a table called 'employees' with columns for 'id', 'name', and 'hire_date'. The 'hire_date' column is defined as the DATE data type. We then insert a row into the table with the hire date '2022-01-01'. Finally, we retrieve all rows from the 'employees' table to see the stored data.
Follow-up 3
Can you explain the purpose of the BOOLEAN data type in SQL?
The BOOLEAN data type in SQL is used to store boolean values, which can be either true or false. It is commonly used to represent logical conditions or binary states. Here's an example of how you can use the BOOLEAN data type in SQL:
CREATE TABLE students (
id INT,
name VARCHAR(50),
is_active BOOLEAN
);
INSERT INTO students (id, name, is_active)
VALUES (1, 'John Doe', true);
SELECT * FROM students;
In this example, we create a table called 'students' with columns for 'id', 'name', and 'is_active'. The 'is_active' column is defined as the BOOLEAN data type. We then insert a row into the table with the value 'true' for the 'is_active' column. Finally, we retrieve all rows from the 'students' table to see the stored data.
5. What is denormalization in SQL?
Denormalization is the deliberate introduction of redundancy into a database schema — the intentional reversal of normalization — to improve read performance by reducing or eliminating costly joins.
What denormalization looks like:
-- Normalized (3NF): customer_name in customers table, not in orders
orders: order_id, customer_id, total
customers: customer_id, name, email
-- Denormalized: customer_name duplicated into orders
orders: order_id, customer_id, customer_name, total
-- Eliminates the JOIN for queries that need customer_name with order data
Other denormalization techniques:
- Pre-aggregated columns: Storing a
total_orderscount on thecustomerstable rather than computing it withCOUNT(*)each time - Flattened tables: Merging multiple normalized tables into one wide table for analytics
- Materialized views: A database-managed form of denormalized data that is auto-refreshed
When denormalization is appropriate:
- Read-heavy OLAP / data warehouse workloads: BigQuery, Redshift, Snowflake — these are optimized for wide, flat tables not normalized schemas
- High-frequency aggregations: If
total_ordersper customer is queried millions of times per day, pre-computing it is justified - Latency-sensitive reads: When join overhead is measurably hurting response time and cannot be resolved with indexing or caching
- Immutable historical records: An invoice should capture the customer's name and price at the time of the transaction, even if those change later
The trade-off: Denormalization shifts complexity from reads to writes. Every update to the original data must also update every denormalized copy. This is typically managed through:
- Application-layer logic
- Triggers (with care)
- Batch ETL jobs
- Materialized views (database-managed)
Interview framing: Denormalization is a deliberate optimization decision made after profiling, not the starting point for schema design.
Follow-up 1
Why would you choose to denormalize a database?
There are several reasons why you might choose to denormalize a database:
Improved query performance: Denormalization can significantly improve the performance of read-heavy applications by reducing the number of joins required to retrieve data.
Simplified data model: Denormalization can simplify the data model by eliminating the need for complex joins and reducing the number of tables in the database.
Better scalability: Denormalization can improve the scalability of a database by reducing the load on the database server, as fewer joins and database operations are required to retrieve data.
Easier maintenance: Denormalization can make the database easier to maintain by reducing the complexity of the queries and eliminating the need for frequent updates to maintain data consistency.
Follow-up 2
What are the potential drawbacks of denormalization?
While denormalization can provide performance benefits, it also has some potential drawbacks:
Data redundancy: Denormalization introduces data redundancy, as the same data is stored in multiple places. This can lead to data inconsistency if updates are not properly managed.
Increased storage requirements: Denormalization can increase the storage requirements of a database, as redundant data needs to be stored. This can be a concern for large databases with limited storage capacity.
Increased complexity: Denormalization can make the database schema more complex, as it involves duplicating data and adding additional columns. This can make the database harder to understand and maintain.
Decreased update performance: Denormalization can negatively impact the performance of write operations, as updates to denormalized data may require updating multiple copies of the same data.
Follow-up 3
Can you give an example of a situation where denormalization would be beneficial?
One example of a situation where denormalization would be beneficial is in a reporting application that requires fast and efficient retrieval of data. By denormalizing the database, redundant data can be added to the reporting tables, eliminating the need for complex joins and improving query performance. This can be particularly useful when dealing with large datasets or complex queries that involve multiple tables. Additionally, denormalization can be beneficial in scenarios where the database server is under heavy load and needs to handle a high volume of concurrent queries efficiently.
Live mock interview
Mock interview: SQL Database Concepts
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.