Skip to main content

SQL Server Interview Questions

Every question has a short model answer and a link to the lesson example that shows it in code. Levels: F = Fresher (0-2 yrs), M = Mid (3-5 yrs), S = Senior (6-9 yrs), A = Architect / Lead (10+ yrs).

Tools

FWhat is the difference between SQL Server and SSMS?concept

SQL Server is the database server: a service that stores the data and runs queries. SSMS (SQL Server Management Studio) is a client tool that connects to SQL Server so you can write queries and manage objects. Uninstalling SSMS does not touch your data.

FWhat is LocalDB, and when would you use it instead of the Developer edition?concept

LocalDB is a lightweight version of SQL Server that starts on demand and needs no service setup; its server name is (localdb)\MSSQLLocalDB. It suits laptops with little memory and simple development. The Developer edition is a full server with every feature, such as SQL Server Agent, so it is better for realistic development and testing.

SWhich SQL Server edition would you use for development, testing, and the school's live server?design

Developer edition for development and testing: it has every feature and is free, but it is licensed only for non-production use. For the live server, Express is free but limited (for example, 10 GB per database). Most real schools need Standard edition, or a managed cloud database, depending on size, availability needs, and budget.

How to answer:

Separate the three environments and the licensing rule first. Size the SMS: one school's data fits Express for years, but 1,000 schools does not. Then weigh the trade-off: Express saves cost but has no SQL Server Agent for scheduled backups, so you would need another way to schedule them; Standard or a managed service costs more but handles backups and availability for you.

Scripts

MHow do you write a database script that can run more than once without errors?coding

Check before you create or change anything. Use IF DB_ID(N'SchoolDb') IS NULL before CREATE DATABASE, IF OBJECT_ID(N'dbo.Students') IS NULL before CREATE TABLE, and CREATE OR ALTER for views and procedures. Such scripts are called idempotent: running them twice leaves the same result as running them once.

MWhat does GO do in a SQL script?concept

GO is not a T-SQL command; SSMS and sqlcmd use it to split a script into batches and send each batch separately. Some statements, such as CREATE VIEW or CREATE PROCEDURE, must be the first statement in a batch. Variables declared before a GO do not exist after it.

RDBMS basics

FWhat is a relational database (RDBMS)?concept

A relational database stores data in tables made of rows and columns, and links tables to each other with keys. An RDBMS (Relational Database Management System), such as SQL Server, is the software that stores the data, runs queries, and enforces rules so many users can work safely at the same time.

FWhat are a table, a row, and a column?concept

A table stores one kind of thing, such as students. A row is one item of that thing, such as one student. A column is one detail that every row has, such as DateOfBirth.

FWhat is the difference between DDL and DML?concept

DDL (Data Definition Language) defines the structure: CREATE, ALTER, and DROP for tables and other objects. DML (Data Manipulation Language) changes the data inside them: INSERT, UPDATE, and DELETE. Creating the Students table is DDL; adding a student is DML.

MWhat are the system databases in SQL Server, and what does each one do?concept

master stores server-wide information such as databases and logins. model is the template copied for every new database. msdb stores SQL Server Agent jobs and backup history. tempdb holds temporary objects and work tables, and is recreated at every restart. Application tables never belong in any of them.

MWhat is the difference between SQL and T-SQL?concept

SQL is the standard language for relational databases. T-SQL (Transact-SQL) is Microsoft's extension of SQL for SQL Server. It adds variables, control flow such as IF and WHILE, and error handling with TRY...CATCH.

MWhat is a schema such as dbo, and why write dbo.Students instead of Students?concept

A schema is a named group of objects inside a database, used for organization and permissions; dbo is the default. Writing dbo.Students names the object exactly, so SQL Server does not have to resolve it per user. That is clearer, avoids picking the wrong object, and lets cached query plans be reused.

SA school keeps everything in spreadsheets and asks why it should move to a database. What do you tell them?scenario

A database lets many staff work at once without overwriting each other, enforces rules such as unique admission numbers and valid marks, and links data without copying it. It answers questions like "all of Kabir's absences this term" instantly, and adds security, backups, and an audit trail of who changed what.

How to answer:

Lead with the pain they already feel: lost changes, inconsistent copies, slow searches. Map each pain to a database feature with an SMS example. Be honest about the cost: setup, training, and someone to own backups, and propose moving one module first.

SWhat is tempdb used for, and why does it matter for performance?concept

tempdb holds temporary tables and table variables, and work areas for sorting, hashing, and row versioning. Every database on the server shares it. A busy or badly sized tempdb slows down every application on that server, so it is usually given several data files on fast storage.

How to answer:

Explain what goes into tempdb (explicit temp objects and internal work), then why sharing makes it a bottleneck. Give an SMS case: a large report that sorts 600,000 attendance rows spills to tempdb. Close with the trade-off: more files and fast disks help, but fixing the query so it sorts less helps more.

AWould you use a relational database or a NoSQL database for a School Management System? Why?design

A relational database. School data has a stable structure and strict rules: every mark belongs to a real enrollment, and fees must add up exactly across invoices and payments. Constraints and transactions enforce exactly that. NoSQL fits flexible documents or huge write-heavy workloads, which is not the core of a school system.

How to answer:

Start from the data's shape and rules, not from fashion. Name the relational strengths the SMS needs: constraints, joins, and transactions for fees. Then show balance: a NoSQL store could still fit a side feature, such as an activity feed or a search index, next to the relational core.

Data modeling

FWhat is an ER diagram, and what are entities and attributes?concept

An ER (Entity-Relationship) diagram is a picture of what a database stores and how the parts connect. An entity is a thing to remember, such as a student, and becomes a table. An attribute is a detail of an entity, such as a date of birth, and becomes a column.

FWhat are one-to-one, one-to-many, and many-to-many relationships?concept

One-to-one: one row on each side at most, such as a teacher and their login. One-to-many: one row links to many, such as a class and its sections. Many-to-many: many on both sides, such as students and guardians, which needs a junction table.

FGive an example of a one-to-many relationship and say where the foreign key goes.concept

A class has many sections, and each section belongs to one class. The foreign key always goes on the "many" side, so Sections has a ClassId column that points to Classes.

MHow do you implement a many-to-many relationship in tables?concept

Add a junction table with a foreign key to each side, and make the pair of keys its primary key. For students and guardians, StudentGuardians has StudentId and GuardianId; each row is one link.

MHow do you read crow's foot notation?concept

The symbols at each end of a line show how many rows can be on that side: || is exactly one, o| is zero or one, |{ is one or more, and o{ is zero or more. The three-pronged "crow's foot" means many. Classes ||--|{ Sections reads "one class has one or more sections".

MWhat is a junction table, and can it have columns of its own?concept

A junction table connects two tables in a many-to-many relationship. Yes, it can hold facts about the link itself. StudentGuardians stores Relationship (Father, Mother, Guardian) and IsPrimaryContact, because those describe the pair, not either side alone.

SWhy does the SMS have an Enrollments table instead of a SectionId column on Students?scenario

A student changes section every year. A SectionId on Students would overwrite last year's section and break the history of attendance, marks, and fees. Enrollments keeps one row per student per academic year, and everything year-specific links to it.

How to answer:

Explain that the section is a fact about a student in a given year, not about the student forever. Walk through Aarav in 9-A last year and 10-A this year. Mention the trade-off: queries need one more join, which is cheap compared to losing history.

SHow do you model a relationship that changes over time, such as which teacher teaches a subject?design

Make the relationship its own table and add the period it is valid for. In the SMS, SubjectAllocations links teacher, subject, section, and academic year, with a unique rule on (year, section, subject). Next year gets new rows, and old years stay correct for reports.

How to answer:

State the pattern (a time-scoped association table). Use the SMS allocation example and show how a past report card still shows the right teacher. Discuss the alternative of start and end dates, which handles mid-year changes but makes queries more complex.

AHow would you design attendance so it can later become per period without breaking existing data?design

Keep attendance in its own table linked to the enrollment, and plan an optional period column now. Daily records leave it empty; period records fill it, with a unique rule on enrollment, date, and period. Reports read both, so old data stays valid and new data adds detail.

How to answer:

Show that you design for likely change without building it all now. Describe the migration path (add a nullable column, add a new unique index, backfill nothing). Weigh it against a separate PeriodAttendance table, which is cleaner but means every report must read two tables.

Normalization

FWhat is normalization, and why do we do it?concept

Normalization is a set of rules for splitting tables so that every fact is stored once. It prevents update, insert, and delete anomalies, where copies of the same fact disagree or are lost. The usual target for business systems is third normal form.

FWhat is first normal form (1NF)?concept

A table is in 1NF when every cell holds a single value, there are no repeating columns such as Guardian1 and Guardian2, and every row can be identified by a key. A cell containing "Rajesh Sharma, Neha Sharma" breaks 1NF.

FWhat are update, insert, and delete anomalies?concept

An update anomaly: a fact stored twice is changed in one place only, so copies disagree. An insert anomaly: you cannot record one fact without another, such as a class teacher without a student. A delete anomaly: deleting one row removes an unrelated fact, such as a guardian's phone.

MExplain second normal form with an example.concept

A table is in 2NF when it is in 1NF and every non-key column depends on the whole key. In a table keyed by (AdmissionNumber, GuardianName), StudentName depends only on the admission number: a partial dependency. Moving student details to Students and guardian details to Guardians fixes it.

MExplain third normal form with an example.concept

A table is in 3NF when it is in 2NF and no non-key column depends on another non-key column. ClassTeacher on Students depends on the section, which depends on the student: a transitive dependency. Moving the class teacher to ClassTeachers (per section and year) fixes it.

MWhat is the difference between a partial dependency and a transitive dependency?concept

A partial dependency is a column that depends on only part of a composite key; 2NF removes it. A transitive dependency is a column that depends on the key only through another non-key column; 3NF removes it. Short test: a column must depend on "the key, the whole key, and nothing but the key".

SWhen would you denormalize, and how do you keep the copied data correct?concept

Denormalize when a measured performance or history need justifies a copy, such as an invoice total stored on FeeInvoices. Keep it correct with one owner: write it in the same transaction as the source rows, block other updates, or rebuild it on a schedule. Without an owner, copies drift.

How to answer:

Make clear denormalization is a deliberate trade-off, then give the SMS invoice total example with both reasons (speed, and a total that must not change after issue). Name the cost: more code paths to keep in sync, and the risk of drift if anyone forgets.

SThe fee report joins six tables and is slow. A developer wants to copy the student name onto FeePayments. What do you say?scenario

First measure: most slow joins are missing indexes or return too many rows, and copying the name fixes neither. If the report is still slow after indexing, consider a reporting view or summary table rebuilt on a schedule. Copying names onto payments creates a second place to update whenever a name is corrected.

How to answer:

Show you diagnose before redesigning: check the execution plan and indexes. Explain why this particular copy is risky (names get corrected and the copy goes stale). Offer the better options in order of cost: indexes, a narrower query, then a reporting table with a clear refresh owner.

Data types

FWhat is the difference between VARCHAR and NVARCHAR?concept

VARCHAR stores text in a limited code page, usually one byte per character, so letters outside it become ?. NVARCHAR stores Unicode, so any language works, at about two bytes per character. Use NVARCHAR for names, and write Unicode literals as N'...'.

FWhy should money use DECIMAL and not FLOAT?concept

FLOAT stores an approximation in binary, so values like 0.1 cannot be stored exactly and totals drift by tiny amounts. DECIMAL stores exact decimal digits. In SQL Server, 0.1 + 0.2 - 0.3 as FLOAT is about 5.55E-17, while as DECIMAL it is exactly 0.00.

FWhat is the difference between DATE and DATETIME2?concept

DATE stores only the day, which suits a date of birth or an attendance date. DATETIME2 stores the day and the time, with precision you choose; DATETIME2(0) keeps whole seconds. DATETIME2 replaces the older DATETIME, with a wider range and better precision.

MHow do you choose between TINYINT, SMALLINT, INT, and BIGINT?concept

Pick the smallest type that safely holds the largest value the column will ever need. TINYINT covers 0 to 255, SMALLINT about ±32,000, INT about ±2.1 billion, and BIGINT far more. For tables that grow with time, estimate rows per year times years of growth; attendance across many schools needs BIGINT.

MWhen would you use CHAR instead of VARCHAR?concept

Use CHAR(n) only when every value has the same short length, because it always uses n bytes and pads with spaces. Gender CHAR(1) is a good fit. For values of varying length, VARCHAR saves space; CHAR(50) stores a five-letter name in 50 bytes.

MWhat do precision and scale mean in DECIMAL(10, 2)?concept

Precision (10) is the total number of digits, and scale (2) is how many of them come after the decimal point. DECIMAL(10, 2) holds values up to 99,999,999.99, which is enough for any school fee.

SThe total of fees collected is off by 0.01 from the bank statement. How do you investigate?scenario

Check the data types first: a FLOAT or REAL amount column, or a FLOAT used in calculations, causes exactly this kind of drift. Then check rounding in code and reports, for example rounding each line versus rounding the total. Fix the type to DECIMAL and recalculate from the original payments.

How to answer:

Give a method: compare totals at each layer (database, API, report) to find where the difference appears. Explain the FLOAT cause with a concrete number. Close with the fix and its cost: changing a column type on a large table needs a migration, so it is cheaper to choose DECIMAL from the start.

SWhy store timestamps in UTC instead of local time?concept

UTC never changes with time zones or daylight saving, so every server, user, and report agrees on the same moment. Local times break when users or servers are in different zones, and some local times repeat or are skipped. Store UTC with SYSUTCDATETIME() and convert only for display.

How to answer:

Explain the problem with a concrete case: a payment at 11:30 PM local time lands on a different day in another time zone. Give the rule (store UTC, convert at the edges). Note the trade-off: every display needs a conversion, and dates without a time, like a date of birth, should stay plain DATE.

AWould you use INT IDENTITY or GUID (UNIQUEIDENTIFIER) primary keys?design

INT IDENTITY is 4 bytes and always increasing, so new rows go to the end of the index and joins stay fast. A GUID is 16 bytes and random, which fragments indexes, but it can be created anywhere without a central counter. Use INT or BIGINT for a single database, and GUIDs when many systems create rows independently.

How to answer:

Compare size, insert order, and index fragmentation, then the cases where GUIDs win: offline clients, merging databases, or not exposing a guessable Id in public URLs. Give the middle road: an INT key inside the database plus a GUID "public id" column for outside use.

Tables

FWhat does CREATE TABLE do, and what do you define for each column?concept

CREATE TABLE creates a new, empty table. For each column you define a name, a data type, and whether it allows NULL. You usually also define the primary key, and often other constraints, in the same statement.

FWhat is an IDENTITY column?concept

An IDENTITY(seed, increment) column is filled automatically by SQL Server. IDENTITY(1, 1) starts at 1 and adds 1 for each new row, so you never supply the value yourself. It is the usual way to create surrogate primary keys like Id.

FWhat is a primary key? Can it contain NULL or duplicate values?concept

A primary key is the column, or set of columns, that uniquely identifies each row. It can never contain NULL and never contain duplicates; SQL Server enforces both. A table has at most one primary key.

MWhy name constraints yourself instead of letting SQL Server name them?concept

SQL Server generates names like PK__Subjects__3214EC07A1B2C3D4, which differ on every server. Named constraints such as PK_Subjects appear clearly in error messages and can be referenced reliably in change scripts, for example to drop or alter them.

MDoes an IDENTITY column guarantee numbers without gaps?concept

No. A failed or rolled-back insert still uses up its number, and a server restart can skip a block of cached values. Gaps are normal: an identity value identifies a row, it does not count rows. If the business needs gapless numbers, such as invoice numbers, generate them separately inside a transaction.

MWhat is the difference between a master (lookup) table and a transaction table?concept

A master table holds lists that other data refers to and rarely changes, such as classes and subjects. A transaction table records events that happen all the time, such as attendance or payments. Transaction rows point to master rows, not the other way round.

SA deployment script fails in production with "There is already an object named 'Students'". How should deployment scripts be written?scenario

They should be idempotent: safe to run more than once. Each change checks first, for example IF OBJECT_ID(N'dbo.Students', N'U') IS NULL before CREATE TABLE, or COL_LENGTH before adding a column. Then a re-run after a partial failure, or a hotfix that already applied a change, does not break the release.

How to answer:

Name the principle (idempotent scripts), show the check pattern for tables, columns, and constraints, and explain the real cause: environments drift. Mention the trade-off: checks add lines to every script, while migration tools track applied scripts in a table instead.

SWhy does the SMS use an Id column as primary key instead of AdmissionNumber?design

Id is a surrogate key: small, never changes, and has no business meaning. AdmissionNumber is a natural key from the real world, and real-world values can change or be entered wrongly; changing a primary key means updating every foreign key that uses it. So the natural key is protected with a UNIQUE constraint instead.

How to answer:

Define surrogate and natural keys, then use the SMS case: a typo in an admission number must be fixable without touching attendance, marks, and fees. Note when natural keys are fine, such as small code tables that never change, and that you still enforce the natural key's uniqueness.

AHow do you manage database schema changes across development, test, and production over years?design

Every change is a versioned script stored in source control and reviewed like code. The same scripts run in the same order in every environment, usually through a migration tool that records which scripts were applied. Nobody changes production by hand.

How to answer:

Describe the pipeline: numbered, idempotent scripts, code review, automated deployment, and a record of applied changes. Compare approaches: migration tools that run scripts in order versus state-based tools that compare a model with the database. Mention the hard parts: data migrations on large tables, and rolling back.

Constraints

FWhat kinds of constraints does SQL Server support?concept

NOT NULL (a value is required), PRIMARY KEY (unique and not NULL), UNIQUE (no duplicates), CHECK (the value must pass a test), DEFAULT (a value when none is given), and FOREIGN KEY (the value must exist in another table). Together they keep data valid no matter which program writes it.

FWhat is the difference between a PRIMARY KEY and a UNIQUE constraint?concept

Both prevent duplicates. A table has only one primary key, and it never allows NULL. A table can have many unique constraints, and each allows one NULL. The primary key is the row's identity; unique constraints protect other business values such as a subject code.

FWhat does a foreign key do?concept

A foreign key makes a column's values refer to an existing primary key in another table. SQL Server then refuses a value that does not exist there, such as a section for class 99, and refuses to delete a row that is still referenced. This is called referential integrity.

MHow do you allow only one row to have IsCurrent = 1?coding

Use a filtered unique index: CREATE UNIQUE INDEX ... ON dbo.AcademicYears (IsCurrent) WHERE IsCurrent = 1. Uniqueness then applies only to rows that match the filter, so many past years can have 0 but only one year can have 1. A plain UNIQUE (IsCurrent) would wrongly allow only one past year.

MWhat happens if you delete a class that still has sections?concept

The delete fails with error 547: "The DELETE statement conflicted with the REFERENCE constraint FK_Sections_Classes". By default a foreign key blocks deleting a referenced row. You can choose ON DELETE CASCADE or SET NULL instead, but for school records blocking is safer.

MShould a rule like 'an academic year ends after it starts' be a CHECK constraint or application code?concept

Both, for different reasons. The application checks it to give the user a friendly message. The CHECK constraint guarantees it for every path into the database, including imports and manual fixes. A simple, permanent rule about one row belongs in a CHECK.

SYou need to add a foreign key to a table that already contains invalid rows. What do you do?scenario

First find and fix or archive the invalid rows, then add the constraint normally so SQL Server checks all existing data. WITH NOCHECK can add it without checking old rows, but the constraint is then marked untrusted, the optimizer cannot rely on it, and the bad data stays.

How to answer:

Show a safe process: measure the bad rows with a query, agree with the business how to fix each one, clean in a transaction, then add the constraint. Explain why WITH NOCHECK is only a temporary step, and that untrusted constraints lose query-plan benefits.

SA script that creates a filtered index works in SSMS but fails through sqlcmd. Why?scenario

Filtered indexes require QUOTED_IDENTIFIER ON. SSMS turns it on by default, but sqlcmd does not, so the CREATE INDEX fails with error 1934. Run sqlcmd with -I, or put SET QUOTED_IDENTIFIER ON in the script. Later inserts and updates on that table need the setting too.

How to answer:

Explain the session setting and why tools differ. Add the hidden danger: stored procedures and triggers remember the setting they were created with, so creating them through sqlcmd without -I breaks them later. Close with the fix: standardize the setting in every deployment tool.

AWhich business rules belong in database constraints, and which belong in application code?design

Rules that must always be true, whatever the context, belong in constraints: uniqueness, required values, valid ranges, and relationships. Rules that depend on who is acting, when, or on several steps belong in code: permissions, workflows, and time windows. Many important rules live in both places.

How to answer:

Give the test: "must this be true for every row, forever, from every source?" Use SMS examples on both sides (a mark belongs to an enrollment vs a teacher may edit marks only before results are published). Mention the cost of each: constraints are cheap and reliable but rigid; code is flexible but can be bypassed.

People tables

FWhy does the SMS store guardians in their own table instead of parent columns on Students?concept

A guardian is a person who can have several children in the school. With their own table, each guardian is stored once, with one phone number, and the StudentGuardians junction table links them to each child. Parent columns would repeat the same data for siblings.

FWhat is a composite primary key?concept

A composite primary key is made of two or more columns whose combination identifies the row. In StudentGuardians, (StudentId, GuardianId) is the key: one guardian can be linked to many students, but the same pair cannot appear twice.

FWhat is the difference between writing constraints inline and adding them with ALTER TABLE?concept

Inline constraints are written inside CREATE TABLE, either after a column or after all columns, so the whole definition is in one place. ALTER TABLE ... ADD CONSTRAINT adds a rule to a table that already exists. The result is the same; inline is simpler for new tables, ALTER for changes.

MWhy does Students.Status use a CHECK list instead of a separate lookup table?design

The list of statuses is short, fixed, and drives code behaviour, so a CHECK constraint is the simplest way to keep values valid. A lookup table is better when users must add or rename values without a code change, or when each value needs extra data such as a display name.

MHow would you guarantee that each student has at most one primary contact guardian?coding

Add a filtered unique index on StudentGuardians (StudentId) WHERE IsPrimaryContact = 1. Each student can then have any number of guardians, but only one row per student can be marked as the primary contact.

MWhy must tables be created in a particular order?concept

A foreign key can only reference a table that already exists. So tables that others point to, such as Students and Guardians, are created first, and tables that point to them, such as StudentGuardians, afterwards. Data must be inserted in the same order.

SA student leaves the school and rejoins two years later. How does this design handle it?scenario

The student keeps the same Students row and admission number; their status changes to Withdrawn when they leave and back to Active when they return. The gap years simply have no enrollment, and the return year gets a new Enrollments row. History before and after stays connected to one person.

How to answer:

Separate the person (permanent) from the yearly placement (enrollments). Walk through the rows that change. Mention the alternative some schools want, a new admission number on return, and why it splits one student's history in two.

SThe people tables hold personal data. What would you do to protect it?design

Collect only what the school needs, restrict who can read sensitive columns, and use made-up data in development and test. SQL Server features such as permissions on columns or Dynamic Data Masking can hide values from users who do not need them, and backups must be protected like the live database.

How to answer:

Cover the principles (minimize, restrict, protect copies) before the features. Use SMS examples: a teacher needs a guardian's phone, but not every guardian's occupation. Note the trade-off: tighter access adds work for support staff, so define roles carefully.

AWould you store teachers, students, and guardians in one People table or in separate tables?design

Separate tables, as in the SMS, are simpler: each has its own columns and rules, and queries stay clear. A single People table (a supertype) avoids repeating name and contact columns and suits people with several roles, such as a teacher who is also a parent, but it adds joins and nullable role-specific columns.

How to answer:

Present both designs fairly, then decide from the requirements: how often one person has several roles, and how different the roles' data is. Mention the middle path: separate tables now, plus a shared Users table for login, which is what the SMS does.

Enrollment

FWhat is a unique constraint on multiple columns?concept

It makes the combination of the columns unique, not each column on its own. UNIQUE (StudentId, AcademicYearId) lets a student appear once per year, so the same student can still have one row for every year.

FHow does the database stop two students getting the same roll number in a section?concept

With UNIQUE (SectionId, AcademicYearId, RollNumber) on Enrollments. Roll number 3 can exist in 10-A and 10-B, and in 10-A next year, but only once in 10-A in the same year.

FWhat does an enrollment represent in the SMS?concept

One student in one section for one academic year, with a roll number. Attendance, marks, and fee invoices all link to the enrollment, so every record knows which year and section it belongs to.

MWhy do the SMS unique rules on Enrollments include AcademicYearId?concept

Because the facts they protect are true per year. A student is in one section per year, and roll numbers repeat each year. Without the year, UNIQUE (StudentId) would allow a student to be enrolled only once in their life.

MWhy is the class teacher stored in a ClassTeachers table instead of a column on Sections?design

The class teacher changes every year, while a section such as 10-A exists every year. A column on Sections would be overwritten each year and lose history. ClassTeachers keeps one row per section per year, protected by UNIQUE (AcademicYearId, SectionId).

MWhat does SubjectAllocations store, and which rule protects it?concept

It stores which teacher teaches which subject to which section in each academic year, with four foreign keys. UNIQUE (AcademicYearId, SectionId, SubjectId) ensures one teacher per subject per section per year, while one teacher can still teach many sections.

SA student moves from 10-A to 10-B in the middle of the year. How do you handle it with this design?scenario

The simple design allows one enrollment per year, so you correct the section on the existing enrollment and record the change in the audit columns. If the school needs to know which section the student was in on each date, the design must change: add a "valid from" date and one row per move, and adjust the unique rules.

How to answer:

Show that you see the hidden requirement: does history per date matter? Compare the two designs and their costs (simple updates vs more complex queries). End with the process: agree the rule with the school before coding, because both are valid.

SHow would you stop a section from going over its capacity of 40 students?design

A constraint cannot count rows, so this needs logic: a stored procedure or the API checks the current count before enrolling, inside a transaction that locks the section, so two enrollments at the same moment cannot both pass. A trigger can act as a safety net.

How to answer:

Explain why CHECK and UNIQUE cannot do it, then show the race condition: two clerks enrolling the 40th student at once. Describe the fix with a transaction and lock, and mention the trade-off between enforcing in the database (safe) and in the API (easier to show friendly messages).

AHow would you design the year-end rollover that promotes 10,000 students to the next year?design

Create the new academic year, then insert next year's enrollments in one set-based statement from this year's enrollments, moving each student up a class. Run it in a transaction, make it safe to re-run, and produce a review report first so the school can correct exceptions such as students who repeat a year or leave.

How to answer:

Cover the steps (prepare, preview, execute, verify) and the guarantees (all or nothing, re-runnable, auditable). Discuss the exceptions that need human decisions, and the trade-off between a fully automatic job and a reviewed, two-step process.

Attendance and marks

FWhy is the key of AttendanceRecords a BIGINT?concept

Attendance grows by one row per student per school day. One school of 10,000 students adds about 2 million rows a year, and many schools together pass the 2.1 billion limit of INT. BIGINT costs four more bytes per row and removes that risk.

FHow does the database prevent marking a student's attendance twice on the same day?concept

With UNIQUE (EnrollmentId, AttendanceDate) on AttendanceRecords. A second record for the same enrollment and date is refused, so a double click or a network retry cannot create a duplicate.

FWhy store NULL marks for an absent student instead of 0?concept

Zero means "attended and scored nothing"; absent means "did not write the paper". Storing 0 would lower averages and show a misleading report card. MarksObtained is NULL and IsAbsent is 1, so reports can treat absence correctly.

MExplain the CHECK constraint that combines IsAbsent and MarksObtained.coding

CHECK ((IsAbsent = 1 AND MarksObtained IS NULL) OR (IsAbsent = 0 AND MarksObtained >= 0)) allows only two valid states: absent with no marks, or present with marks of zero or more. It refuses "absent with 45 marks" and "present with no marks". A CHECK can compare columns of the same row like this.

MWhy is there an ExamSubjects table between Exams and Marks?design

An exam such as "Unit Test 1" has many papers: one per class and subject, each with its own date, maximum marks, and pass marks. ExamSubjects stores those papers, and each mark belongs to one paper. Without it, every mark would have to repeat the paper's details.

MWhy can't a CHECK constraint enforce 'marks cannot exceed the paper's maximum'?concept

A CHECK constraint can only see the row being saved. The maximum lives in ExamSubjects, another table. Cross-table rules need a trigger, a stored procedure, or application code; the SMS adds a trigger in Lesson 23 and the same check in the API.

SEvery class teacher saves attendance between 8:45 and 9:00 AM. What design concerns does that create?scenario

Thousands of inserts arrive in a few minutes, so saves must be fast and safe to retry. Save a whole section in one set-based statement inside a transaction, rely on the unique constraint to stop duplicates, use an "insert or update" approach for corrections, and keep the table's indexes minimal so inserts stay cheap.

How to answer:

Describe the load pattern first (short, intense peak). Then cover correctness (unique rule, idempotent saves), efficiency (one statement per section, not one per student), and the trade-off between extra indexes for reports and insert speed at peak time.

SA mark must be corrected after report cards were printed. How should the system handle it?scenario

Allow the correction only for authorized roles, record who changed it and when in the audit columns, and keep the old value in an audit log or history table. Reprint the affected report card and keep the reason for the change. A silent overwrite would make the printed and stored marks disagree with no explanation.

How to answer:

Combine process and design: permissions, audit trail, and a reason field. Name the SQL Server options for keeping old values (an audit table written by a trigger, or a system-versioned temporal table) and the cost of each in storage and complexity.

AHow would you store ten years of attendance for 1,000 schools?design

That is billions of rows, so plan for size from the start: BIGINT keys, partitioning by date so old periods can be managed separately, archiving closed years to cheaper storage, and summary tables for reports that need totals rather than single days. Daily screens then only touch the current year's data.

How to answer:

Estimate the volume with numbers first. Then explain each technique and what it solves: partitioning (maintenance and fast removal of old data), archiving (cost), summaries (report speed). Close with the trade-off: more moving parts to operate, justified only at that scale.

Fees and audit

FWhat are audit columns?concept

Columns that record who created a row and when (CreatedAt, CreatedBy), and who last changed it and when (UpdatedAt, UpdatedBy). CreatedAt usually has a default of SYSUTCDATETIME(). They answer "who and when" for the latest change, not the full history.

FWhat is soft delete?concept

Instead of removing a row with DELETE, you mark it as deleted with IsDeleted = 1 and a DeletedAt time. Screens and reports leave those rows out, and the row can be restored by setting the flag back.

MWhat are the downsides of soft delete?concept

Every query must filter IsDeleted = 0, and forgetting it shows deleted rows in reports. Unique constraints still see deleted rows, so a deleted record's unique value stays taken. Tables never shrink. Use it only where restore or history is required, and hide the filter in views.

SWhen are audit columns enough, and when do you need a full audit history?design

Audit columns record only the latest change, which is enough for "who touched this last". When you must know every old value, such as for marks or payments, you need a history: an audit table filled by triggers, a system-versioned temporal table, or change data capture. Each keeps old versions at the cost of storage.

How to answer:

Start from the question the business needs answered, then match a tool: audit columns, temporal tables (automatic history per table), or an audit log (custom, can include the reason). Mention storage growth and how long history must be kept.

MHow do you add a NOT NULL column to a table that already has rows?coding

Add it with a default in the same statement, for example ALTER TABLE dbo.Students ADD IsDeleted BIT NOT NULL CONSTRAINT DF_Students_IsDeleted DEFAULT (0). Existing rows get the default value. Without a default, the statement fails because existing rows would have no value.

FWhy are invoices stored as a header table and a lines table?design

The header (FeeInvoices) holds facts about the whole bill: number, date, student, total, status. Each line (FeeInvoiceItems) holds one fee type and amount. One fact per row means any number of fee types per invoice, and reports can total tuition or exam fees across all invoices.

MHow does the SMS support part payments, and how do you calculate an invoice's balance?concept

An invoice can have many rows in FeePayments. The balance is the invoice total, minus its discount, minus the sum of its payments. The invoice status (Unpaid, PartiallyPaid, Paid) is updated in the same transaction that records a payment.

SA parent double-clicks 'Pay' and two identical payments are recorded. How do you prevent that?scenario

Make the payment request idempotent: the client sends a unique payment reference, and a unique constraint on it refuses the second insert. Record the payment and update the invoice status in one transaction, and have the screen disable the button after the first click. The database rule is what makes it reliable.

How to answer:

Explain the cause (retries and double clicks happen), then layer the defences: UI, API idempotency key, unique constraint, and a transaction. Name the trade-off: you need a reference that the client generates once per payment attempt.

Inserting data

FWhat is the syntax of INSERT, and why should you always list the columns?coding

INSERT INTO dbo.Table (Col1, Col2) VALUES (v1, v2), (v3, v4); adds one or more rows. Listing the columns keeps the insert working when columns are added later, and stops values going into the wrong columns if the column order changes.

FWhat happens to a column you leave out of an INSERT?concept

SQL Server uses the column's DEFAULT if it has one, the next value if it is an IDENTITY column, or NULL if the column allows it. If none of these apply, the insert fails with "Cannot insert the value NULL".

FWhat does SET IDENTITY_INSERT do?concept

It lets you insert your own values into an IDENTITY column for one table at a time. It is used for seed data that needs fixed Ids, or when copying data between databases. You must list the Id column, and you should turn it off right after the insert.

MWhy is a set-based insert faster than inserting rows one at a time in a loop?concept

A set-based statement inserts all rows in one operation, so SQL Server plans it once, writes the log efficiently, and avoids a round trip per row. A loop runs a separate statement, and often a separate commit, for every row. The SMS generator inserts 600,000 attendance rows in seconds this way.

MWhat is GENERATE_SERIES, and how did people generate numbers before SQL Server 2022?concept

GENERATE_SERIES(start, stop) returns one row per number in a range, which you can turn into generated rows. Before SQL Server 2022, developers used a permanent numbers table, a recursive CTE, or cross joins of system views to produce the same list of numbers.

MWhy does the bulk data script use one transaction with SET XACT_ABORT ON?concept

It makes the load all or nothing. With XACT_ABORT ON, any error rolls back the whole transaction, so you never end up with students but no enrollments. Combined with the "already exists" check at the top, the script can simply be run again after a failure.

SWhy test with 10,000 students when the sample school has only 12?scenario

With 12 rows every query is instant, so slow designs stay hidden until production. A realistic volume shows missing indexes, queries that return too many rows, and slow reports during development, when they are cheap to fix.

How to answer:

Give a concrete SMS example: a class report that scans every attendance row is invisible at 36 rows and obvious at 600,000. Describe how you size test data from the real school's numbers, and note that volume tests run on dedicated test databases, not on developers' shared servers.

SWhat is the difference between seed data and test data, and where does each run?design

Seed data is part of the product, such as roles, classes, and subjects, and runs in every environment, including production. Test data, such as generated students, runs only in development and test. Mixing them puts fake students into a real school or leaves production without required lookup rows.

How to answer:

Define both, give SMS examples of each, and describe how deployment keeps them apart: separate scripts or folders, and pipeline steps that run test data only in non-production environments. Mention keeping seed data re-runnable so redeploys are safe.

AHow do you create realistic test data at scale without using production data?design

Generate it from rules: numbers become names, dates, and statuses through repeatable formulas, with realistic distributions such as about 88 percent attendance. It is safe, repeatable, and sized to match real volumes. If production data must be used, it is masked or anonymized first, never copied as is.

How to answer:

Explain why production copies are risky (personal data, access control, compliance). Describe a generator's qualities: deterministic, realistic distributions, correct relationships, and fast set-based loading. Discuss the trade-off: generated data can miss rare real-world cases, so add known edge cases deliberately.

Querying basics

FIn what order does SQL Server process the clauses of a SELECT query?concept

Logically: FROM (and joins), WHERE, GROUP BY, HAVING, SELECT, ORDER BY, then TOP. That is why a column alias defined in SELECT cannot be used in WHERE, but can be used in ORDER BY.

FWhy does WHERE Occupation = NULL return no rows?concept

NULL means unknown, and comparing anything with unknown gives unknown, which is never true. So = NULL matches nothing, even rows that are NULL. Use IS NULL or IS NOT NULL instead.

FWhat do the wildcards % and _ mean in LIKE?coding

% matches any text of any length, including none, and _ matches exactly one character. LastName LIKE N'Sh%' matches Sharma and Sheikh; LIKE '_A' matches any two-character value ending in A.

MWhy should TOP always be used with ORDER BY?concept

Without ORDER BY, SQL Server returns whichever rows it reaches first, and that can change between runs, after an index change, or under load. TOP (3) ... ORDER BY DateOfBirth DESC always returns the three youngest students.

MWhy is SELECT * discouraged in application code?concept

It returns columns the code does not need, which wastes network and memory and can stop SQL Server from using a narrower index. It also changes silently when someone adds a column, which can break code that reads columns by position. List the columns you need.

MHow do you safely run an UPDATE or DELETE on important data?coding

Run a SELECT with the exact WHERE first and check the rows. Then start a transaction, run the change with the same WHERE, check @@ROWCOUNT and the data, and only then COMMIT; otherwise ROLLBACK.

SSomeone ran an UPDATE without a WHERE clause on production. What do you do?scenario

Stop further changes to that table, find out exactly what changed and when, and restore the correct values: from a backup restored to a separate database, from audit data, or from a point-in-time restore. Communicate early with the business. Afterwards, change the process so it cannot happen again.

How to answer:

Give a calm sequence: contain, assess, recover, communicate, prevent. Explain the recovery options and their trade-offs (restoring the whole database loses later work, so restore a copy and repair only the affected rows). Close with prevention: reviewed scripts, transactions, and limited write access to production.

SWhy can a search with LIKE N'%sharma%' be slow on a large table?concept

A pattern that starts with % cannot use an index seek, because the matching text could be anywhere in the value; SQL Server has to scan every row. A pattern like N'Sharma%' can seek. For true "contains" search on large tables, use full-text search or a search index.

How to answer:

Explain index seeks vs scans in one sentence, then show the two patterns. Discuss the options for a student search screen: starts-with search, full-text search, or a separate search service, and the cost of each.

AHow would you design the process for data fixes on a production database?design

Data fixes are written as scripts, reviewed by a second person, tested on a copy of production, and run by the release process with a transaction and row-count checks. The script and its result are stored, so every change is traceable. Nobody types changes directly into production.

How to answer:

Describe the workflow (request, script, review, test, approved run, record) and the controls (permissions, transactions, expected row counts, backups). Mention the trade-off: urgent fixes take minutes longer, which is cheap compared with one bad manual update.

Joins

FWhat is the difference between INNER JOIN and LEFT JOIN?concept

INNER JOIN returns only rows that match on both sides. LEFT JOIN returns every row from the left table, and fills the right table's columns with NULL when there is no match. Every teacher with their class (LEFT) shows teachers who are not class teachers; INNER would hide them.

FWhat is a join condition, and what usually goes in it?concept

The join condition, written after ON, says which rows of the two tables belong together. It is usually a foreign key equal to the primary key it references, such as ON e.StudentId = s.Id.

FWrite a query that lists the students of Class 10-A for the current year.coding

Join Students to Enrollments, then to Sections and AcademicYears, and filter on the class, the section name, and IsCurrent = 1, ordered by roll number. Four tables, each joined on its foreign key.

MWhy does adding a join sometimes multiply the number of rows?concept

If each row on the left matches several rows on the right, the left row appears once for each match. Joining 12 students to their guardians gives 24 rows, because each has two. Totals calculated after such a join are multiplied too.

MWhat is a self join? Give an example.coding

A self join joins a table to itself using two aliases. To find students who share a guardian, join StudentGuardians to itself on the same GuardianId, with a condition like sg2.StudentId > sg1.StudentId so a student does not match themselves.

MWhy does a condition on the right table belong in the ON clause of a LEFT JOIN, not in WHERE?concept

WHERE runs after the join. A condition there on the right table removes the rows where that table is NULL, which turns the LEFT JOIN into an INNER JOIN. In the ON clause, it only limits which right rows can match, and unmatched left rows are kept.

SA fee report total is exactly double what it should be. How do you find the cause?scenario

Doubled totals almost always come from a one-to-many join added after the data was already at the right level. Remove joins one at a time and watch the row count, or count rows per key to find the join that matches twice. Then aggregate before joining, or join only what the report needs.

How to answer:

Show a systematic method (compare row counts with a known number, isolate the join), then the fix (pre-aggregate in a CTE). Use the SMS example of joining payments to guardians. Mention adding a test that checks the total against a simpler query.

SWhen would you use FULL JOIN or CROSS JOIN in a real system?concept

FULL JOIN compares two lists where either side can have rows the other lacks, such as reconciling an imported fee file with the payments table. CROSS JOIN builds every combination, such as creating exam papers for every class and subject. Both are rare in daily screens.

How to answer:

Give one concrete SMS use for each, and say how you keep CROSS JOIN results under control (filter both inputs first, check the expected row count). Mention that the bulk generator in Lesson 15 uses CROSS JOIN deliberately.

AA report needs eight joins and runs slowly every morning. Would you keep the joins or build a reporting table?design

First check whether the joins are the real problem: missing indexes on the join columns are the usual cause. If the report is still too slow, or many reports repeat the same joins, a reporting table or indexed view refreshed on a schedule can serve them, accepting slightly delayed data.

How to answer:

Compare the options on freshness, cost, and complexity: tuned joins (always fresh), indexed views (fresh, slower writes), and scheduled reporting tables (fast reads, delayed data). Make the decision from measured timings and how fresh the report must be.

Aggregation

FWhat is the difference between WHERE and HAVING?concept

WHERE filters rows before they are grouped, and cannot use aggregates. HAVING filters groups after GROUP BY, so it can use aggregates, such as HAVING COUNT(*) < 5 to find small sections.

FWhat are the main aggregate functions?concept

COUNT counts rows or values, SUM adds them, AVG averages them, and MIN and MAX return the smallest and largest. With GROUP BY, each returns one value per group, such as students per section or fees per class.

FWhy does a query fail with 'column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause'?concept

Every column in SELECT must either be in GROUP BY or be inside an aggregate. Otherwise one group could have several values for that column, and SQL Server cannot choose one. Add the column to GROUP BY or aggregate it.

MWhat is the difference between COUNT(*), COUNT(column), and COUNT(DISTINCT column)?concept

COUNT(*) counts every row. COUNT(column) counts rows where that column is not NULL, so absent students without marks are skipped. COUNT(DISTINCT column) counts different values. Four 10-A Science papers give 4, 3, and 1 respectively.

MHow do you count only some rows inside a GROUP BY query?coding

Put a CASE inside SUM: SUM(CASE WHEN Status IN ('Present', 'Late') THEN 1 ELSE 0 END) adds 1 for each matching row and 0 for others. Divided by COUNT(*) and multiplied by 100.0, it gives an attendance percentage per student.

MWhy does 100 * 2 / 3 give 66 instead of 66.67 in SQL Server?concept

When both sides of a division are whole numbers, SQL Server returns a whole number and drops the fraction. Make one side decimal, for example 100.0 * 2 / 3, or CAST a value to DECIMAL, to keep the fraction.

SThe class average looks too high because absent students are left out. How do you handle it?scenario

AVG skips NULLs, so absent students do not count. That is usually right, but the school must decide the rule. If absent should count as zero, use AVG(ISNULL(MarksObtained, 0)); if not, show the number of papers averaged next to the average so readers know.

How to answer:

Explain how aggregates treat NULL, then turn it into a business decision with the school. Show both SQL forms. Recommend documenting the definition with the report so every report uses the same rule.

STwo reports show different attendance percentages for the same class. How do you resolve it?scenario

Compare the definitions first: which statuses count as present, which dates are included, and whether deleted or transferred students are counted. Then recompute the number by hand from raw rows. Agree one definition with the school and make both reports use it.

How to answer:

Show that you treat it as a definitions problem before a SQL problem. Walk through the checks, reconcile with raw counts, and close with prevention: one shared, documented definition, ideally in one view used by every report.

AThe principal's dashboard aggregates millions of rows on every page load. How would you redesign it?design

Pre-compute the numbers: a summary table updated as data changes or on a short schedule, or an indexed view that SQL Server keeps up to date. The dashboard then reads a few rows instead of millions, at the cost of extra work on writes or slightly delayed numbers.

How to answer:

Quantify the load first (rows scanned, page loads per minute). Compare indexed views, summary tables, and caching on freshness, write cost, and complexity. Choose based on how fresh the principal really needs the numbers to be.

Subqueries and CTEs

FWhat is a subquery?concept

A subquery is a query inside another query, in brackets. It can return one value (used with = or >), a list (used with IN), or be used with EXISTS to test whether any row matches.

FWhat is a CTE?concept

A CTE (Common Table Expression) is a named query written with WITH name AS ( ... ) before a statement. That statement can use the name like a table. It makes long queries readable as steps, and it exists only for that one statement.

FFind the students who scored above their section's average.coding

Compare each mark with a subquery that returns the average for the same paper and section: WHERE m.MarksObtained > (SELECT AVG(MarksObtained) FROM dbo.Marks WHERE ...). In 10-A Unit Test 1 Mathematics, the average is 84.75, so Meera, Aarav, and Diya qualify.

MWhy can NOT IN return no rows at all, and what should you use instead?concept

If the subquery's list contains a NULL, x NOT IN (...) is unknown for every row, because "not equal to NULL" is never true. So the query returns nothing. Use NOT EXISTS, which is not affected by NULLs, or filter NULLs out inside the subquery.

MWhat is the difference between IN and EXISTS?concept

IN checks whether a value is in a list returned by the subquery. EXISTS checks whether the subquery returns any row at all, and can stop at the first match. For positive checks they often perform the same; for negative checks, NOT EXISTS is safer than NOT IN because of NULLs.

MWhat is a correlated subquery?concept

A correlated subquery uses a column from the outer query, so it is evaluated for each outer row. Example: each student's last attendance date with (SELECT MAX(a.AttendanceDate) FROM dbo.AttendanceRecords AS a WHERE a.EnrollmentId = e.Id).

SWrite a query for invoices that still have money due, with the balance.coding

In a CTE, sum the payments per invoice. Then left join the invoices to it, compute total minus discount minus ISNULL(paid, 0), and keep rows where that is above zero. Summing first avoids multiplied totals, and the left join keeps invoices with no payments.

How to answer:

Write it in two steps aloud, explaining why each part exists (CTE to aggregate, LEFT JOIN for unpaid invoices, ISNULL for NULL sums). Mention edge cases: deleted payments, discounts, and cancelled invoices, and how you would test the result against one known invoice.

SA nightly job using NOT IN suddenly sends no reminders at all. What happened?scenario

Most likely a NULL appeared in the column the NOT IN subquery returns, so the condition became unknown for every row and nothing qualified. Rewrite it with NOT EXISTS, fix or explain the NULL data, and add an alert when a reminder job processes zero rows.

How to answer:

Diagnose from the symptom (zero rows, not an error), explain the three-valued logic briefly, then fix and prevent: NOT EXISTS, a data check, and monitoring that treats "zero processed" as suspicious.

AWhen would you choose a CTE, a temporary table, or a view for a multi-step report?design

A CTE for readable steps inside one statement. A temporary table when an intermediate result is reused several times, is large, or benefits from its own index. A view when many queries and reports need the same logic. Each adds reuse or speed at the cost of more objects to manage.

How to answer:

Compare scope (one statement, one session, permanent), reuse, and performance. Use SMS examples for each: a report card CTE, a temp table for a year-end calculation, a view for "current enrollments". Mention measuring before switching for speed.

Window functions

FWhat is the difference between ROW_NUMBER, RANK, and DENSE_RANK?concept

All three number rows in order. ROW_NUMBER always gives different numbers, even for ties. RANK gives ties the same number and then skips (1, 2, 3, 3, 5). DENSE_RANK gives ties the same number without gaps (1, 2, 3, 3, 4).

FHow is a window function different from GROUP BY?concept

GROUP BY collapses each group into one row. A window function calculates across a group of rows but keeps every row, so you can show each student with their rank or the section average next to their mark.

FWhat does PARTITION BY do in an OVER clause?concept

It splits the rows into groups, and the window function restarts for each group. RANK() OVER (PARTITION BY SectionId ORDER BY Total DESC) ranks students within their own section, starting at 1 in every section.

MHow do you remove duplicate rows from a table using ROW_NUMBER?coding

Number the rows within each group of duplicates with ROW_NUMBER() OVER (PARTITION BY the duplicate columns ORDER BY a tie-breaker) in a CTE. Rows numbered 1 are kept; delete or ignore the rest.

MHow do you calculate a running total in SQL Server?coding

Use SUM(Amount) OVER (ORDER BY PaidOn, ReceiptNumber ROWS UNBOUNDED PRECEDING). Each row gets the total of all rows up to it. A unique ORDER BY and the explicit ROWS frame make the result predictable and fast.

MWhat do LAG and LEAD do?concept

LAG(column) returns the value from the previous row in the window, and LEAD(column) from the next row. They compare a row with its neighbours, such as this exam's marks against the previous exam's. The first row's LAG is NULL.

SWrite a query for the top 3 students in every section.coding

In a CTE, compute each student's total, then add ROW_NUMBER() OVER (PARTITION BY Section ORDER BY Total DESC, AdmissionNumber). In the outer query, keep rows numbered 1 to 3. Use RANK instead if tied students must both appear.

How to answer:

Write the two-step pattern and explain why the filter must be outside (window functions are not allowed in WHERE). Ask about the tie rule before choosing the function, and mention the tie-breaker that keeps results stable.

SA page loads 50,000 rows into C# only to rank them and show the top 3 per group. How would you improve it?scenario

Move the ranking into SQL with a window function and return only the rows the page shows. The database does it in one pass with the data already there, and the network, memory, and page time drop sharply.

How to answer:

Measure first (rows transferred, page time), then show the window-function rewrite and the expected gain. Discuss the trade-off: logic in SQL is less visible to C# developers, so keep it in a named view or procedure with tests.

AShould rankings and running totals be calculated in the database or in application code?design

For large data sets, in the database: it avoids moving rows and uses set-based processing. For small results that the screen already holds, or rules that change often and need unit tests in C#, application code can be simpler. Keep one place responsible for each calculation.

How to answer:

Weigh data volume, network cost, testability, and who maintains the logic. Give SMS examples on both sides (prize lists over 10,000 students in SQL; re-sorting 40 rows on a screen in code). Stress consistency: one calculation, one place.

Views and functions

FWhat is a view?concept

A view is a saved SELECT with a name. It stores no data; every time you query it, SQL Server runs its query against the real tables. Views hide joins and filters, such as vw_CurrentEnrollments hiding four joins and the soft-delete filter.

FWhat is the difference between a scalar function and a table-valued function?concept

A scalar function returns one value and is used in SELECT or WHERE, such as dbo.fn_GetGrade(92). A table-valued function returns a table and is used in FROM, such as dbo.fn_GetSectionResults(1, 19). An inline table-valued function is like a view that takes parameters.

FWhy use a view to hide soft-deleted rows?concept

So the IsDeleted = 0 filter is written once. Every report and API that reads the view automatically leaves deleted students out, and nobody can forget the filter. In the SMS, soft-deleting Meera drops the 10-A count from 4 to 3 through the view.

MWhat is the difference between a view and an inline table-valued function?concept

Both are saved queries used in FROM. A view takes no parameters, while an inline table-valued function does, such as an exam and section. SQL Server expands both into the calling query, so both perform like the query written out in full.

MWhy can a scalar function make a query slow?concept

It runs once for every row it is applied to, and when used on a column in WHERE, it hides that column from indexes. SQL Server 2019 and later can inline simple scalar functions, but functions that read tables or use loops often cannot be inlined.

MCan you insert or update through a view?concept

Yes, if the change affects one base table and the view has no DISTINCT, GROUP BY, or aggregates. Views with joins usually cannot accept changes to more than one table. In the SMS, views are for reading; changes go through tables or procedures.

SA report using a scalar function over 2 million rows takes 40 minutes. How do you fix it?scenario

Look at what the function does. If it reads tables, rewrite that logic as a join or an inline table-valued function so SQL Server processes all rows as one set. Compare the plans and timings before and after; this kind of rewrite often turns minutes into seconds.

How to answer:

Explain the row-by-row cost and why the optimizer cannot see inside a non-inlined function. Describe the rewrite and how you would prove it with logical reads and duration. Mention checking whether SQL Server's scalar UDF inlining applies first.

SHow can views be used as a security boundary?design

Grant reporting users SELECT on views only, never on the tables. The view exposes only the columns and rows they may see, and because the view and tables have the same owner, SQL Server does not check table permissions (ownership chaining). The tables stay private.

How to answer:

Combine the design (views as the public shape of the data) with the permission model (GRANT on views, nothing on tables). Use the SMS reports role. Note the limit: a view is not row-level security per user; for that, use filters or Row-Level Security policies.

AWhen would you use an indexed view, and what does it cost?design

When a frequently run aggregate over large tables is too slow and must be up to date, such as daily attendance totals. The indexed view stores its result and SQL Server maintains it on every change to the base tables, so reads are fast but writes become slower, and strict rules apply.

How to answer:

Present it as one option among summary tables, caching, and better indexes. Weigh freshness against write cost, and mention the restrictions (schema binding, no outer joins). Decide from measured numbers on the real workload.

Stored procedures

FWhat is a stored procedure?concept

A stored procedure is a named block of T-SQL saved in the database, with parameters. It can read and change data and use transactions. The SMS uses usp_RecordFeePayment to check, save, number, and update a payment in one call.

FWhat is the difference between a stored procedure and a function?concept

A procedure can change data and use transactions, and is called with EXEC. A function cannot change data, and is used inside a query, returning one value or a table. Use procedures for business actions and functions for calculations and reusable reads.

FWhat is an OUTPUT parameter?concept

A parameter that sends a value back to the caller. usp_RecordFeePayment returns the new receipt number through @ReceiptNumber OUTPUT, and the caller passes a variable with the OUTPUT keyword to receive it.

MWhy use SET NOCOUNT ON in a stored procedure?concept

It stops SQL Server from sending a "rows affected" message after every statement. The application does not need them, they add network traffic, and some client libraries can confuse them with result sets.

MHow do stored procedures protect against SQL injection, and when can they still be vulnerable?concept

Parameters are treated as values, never as code, so input like '; DELETE ... is just text. A procedure is still vulnerable if it builds dynamic SQL by joining strings with input. Dynamic SQL must pass values through sp_executesql parameters.

MWhy use a SEQUENCE instead of MAX(...) + 1 to number receipts?concept

Two sessions running MAX + 1 at the same time can read the same maximum and produce the same number. A sequence hands out each number exactly once, without locking the table. Numbers used in rolled-back transactions are not returned, so gaps can appear.

STwo payments for the same invoice arrive at the same moment. How does usp_RecordFeePayment stay correct?scenario

It reads the invoice WITH (UPDLOCK) inside its transaction. The second payment waits until the first commits, then sees the updated balance, so both cannot pass the balance check. The receipt numbers come from a sequence, so they never collide.

How to answer:

Describe the race condition first (both read the same balance), then the fix (lock the row you will change, early), and the guarantee it gives. Mention the cost: payments for the same invoice are serialized, which is acceptable because they are rare.

SHow do you change a stored procedure that the API depends on without breaking it?design

Treat parameters and result columns as a contract. Use CREATE OR ALTER so permissions are kept, add new parameters at the end with defaults, and do not rename or remove result columns that callers read. Deploy the database change before the application change that uses it.

How to answer:

Explain backward compatibility, the deployment order, and how you test both old and new callers. Mention versioned procedure names as a last resort for breaking changes.

AShould business logic live in stored procedures or in application code?design

Data-heavy, transactional steps that must be atomic, such as recording a payment, fit procedures well. Workflows, validation messages, integrations, and logic that needs unit tests fit application code better. Most systems use both, with a clear rule for which goes where.

How to answer:

Avoid absolutes. Weigh testability, deployment, team skills, performance, and reuse across channels. Give SMS examples on both sides and describe the agreed boundary your team would write down.

Triggers

FWhat is a trigger?concept

A trigger is code attached to a table that SQL Server runs automatically when rows are inserted, updated, or deleted. It runs inside the same transaction, so it can refuse a change with an error or record it in another table.

FWhat are the inserted and deleted tables in a trigger?concept

They are temporary tables with the same columns as the real table. inserted holds new rows (after an insert or update), and deleted holds old rows (after an update or delete). For an update, joining them shows each row before and after.

FWhy does the SMS use a trigger for 'marks not above the maximum' instead of a CHECK constraint?concept

The maximum is in ExamSubjects, another table, and a CHECK constraint can only see the row being saved. The trigger joins inserted to ExamSubjects and throws error 50001 if any mark is too high.

MHow many times does a trigger fire for an UPDATE that changes 500 rows?concept

Once. Triggers fire per statement, with all 500 rows in inserted and deleted. Code that assumes a single row, such as assigning a column to a variable, silently handles only one of them; trigger code must be set-based.

MWhat happens when a trigger throws an error?concept

The statement that fired it fails, and its transaction is rolled back, including any rows the trigger itself wrote. In the SMS, updating two marks where one is 105 fails as a whole: both marks keep their old values.

MHow does the audit trigger know which user made a change?concept

The API stores the logged-in user's Id in SESSION_CONTEXT for the connection, with sp_set_session_context. The trigger reads it with SESSION_CONTEXT(N'UserId'), so it knows the user without the API passing it to every statement.

SSaving marks became slow after someone added a trigger. What do you check?scenario

Read the trigger: loops, cursors, queries without indexes, or calls to other databases or services run inside every save. Check the plan of the trigger's statements and the wait types during saves. Rewrite it set-based and move any external work out of the transaction.

How to answer:

Show that triggers are part of the write path. Describe how you would measure (plans, duration with and without the trigger) and the usual culprits. End with a rule: triggers only check and record.

SHow would you choose between a constraint, a trigger, and a stored procedure for a business rule?design

Use a constraint when the rule concerns one row and is always true. Use a procedure for a multi-step business action. Use a trigger only when the rule needs other tables and must hold for every way data is written, such as imports and manual fixes.

How to answer:

Give the decision order (constraint, then procedure, then trigger) and an SMS example for each. Mention the costs of triggers: hidden behaviour, write overhead, and testing effort.

AHow would you design auditing for a system that must keep every change for 7 years?design

Record old and new values with who and when for the tables that matter, using triggers, temporal tables, or change data capture. Store audit data so it cannot be edited by the application, partition or archive it by date, and plan its size, retention, and access.

How to answer:

Compare the options: triggers (flexible, custom), system-versioned temporal tables (automatic history per table), and change data capture (log-based, for downstream use). Cover storage growth, query needs, security, and how long data must be kept.

Transactions

FWhat is a transaction?concept

A group of changes that succeed together or fail together. BEGIN TRANSACTION starts it, COMMIT makes every change permanent, and ROLLBACK undoes them all. Recording a payment and updating the invoice status is one transaction.

FWhat does ACID stand for?concept

Atomicity (all or nothing), Consistency (rules hold before and after), Isolation (others do not see half-done work), and Durability (committed changes survive a crash). Together they describe what a database transaction guarantees.

FWhat is autocommit mode?concept

SQL Server's default: without BEGIN TRANSACTION, each statement is its own transaction and is committed as soon as it succeeds. Two related statements run this way are not protected; if the second fails, the first stays saved.

MInside a transaction, the second of two statements fails. Is the first one undone?concept

Not by default. SQL Server undoes only the failed statement; the transaction stays open with the first change in it, and a later COMMIT saves it. Use TRY...CATCH with ROLLBACK, or SET XACT_ABORT ON, so any error undoes everything.

MWhat does SET XACT_ABORT ON do, and why use it?concept

With it on, any run-time error rolls back the whole transaction and stops the batch. It guarantees that a failure never leaves a half-done transaction, even when a CATCH block is missing or a client times out. Procedures that change data should use it.

MWrite the standard TRY...CATCH pattern for a transaction.coding

BEGIN TRY BEGIN TRANSACTION; ...changes...; COMMIT TRANSACTION; END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION; THROW; END CATCH;. The check avoids an error when no transaction is open, and THROW; passes the original error to the caller.

SDoes SQL Server support nested transactions?concept

Not really. Each BEGIN TRANSACTION increases @@TRANCOUNT, and an inner COMMIT only decreases it; nothing is saved until the outermost COMMIT. A ROLLBACK anywhere undoes everything and sets the count to 0. Savepoints are the only way to undo part of a transaction.

How to answer:

Explain @@TRANCOUNT with the 2, 1, 0 example, then the consequence: a procedure that rolls back destroys its caller's transaction. Show how callers should check @@TRANCOUNT after an error, and mention savepoints for partial undo.

SUsers say saving 'hangs' every afternoon. You suspect an open transaction. How do you find it?scenario

Run DBCC OPENTRAN in the database to see the oldest open transaction and its session, and query sys.dm_exec_requests for blocked sessions and who blocks them. Often it is an SSMS window with an uncommitted change, or an application path that never commits. Close or kill it, then fix the cause.

How to answer:

Give the diagnosis steps with the exact tools, then the decision (contact the owner before killing a session), and the prevention: short transactions, XACT_ABORT, and alerts on long-running transactions.

AA business action spans the database and an external payment service. How do you keep them consistent?design

A database transaction cannot include an external service. Record the intent first in the database, call the service with an idempotency key, then record the result; a background job retries or reconciles anything left pending. The design accepts brief inconsistency and always ends in a known state.

How to answer:

Explain why distributed transactions are avoided, then describe the pattern (outbox or pending-state plus reconciliation). Use the SMS online payment as the example, and cover retries, idempotency, and monitoring.

Locking and isolation

FWhat is the difference between a shared lock and an exclusive lock?concept

A shared lock is taken for reading; many sessions can hold it at once. An exclusive lock is taken for changing data; only one session can hold it, and it blocks other writers and, by default, readers. Exclusive locks last until the transaction ends.

FWhat is SQL Server's default isolation level?concept

READ COMMITTED. Readers see only committed data, and wait for writers that hold locks on the rows they need. It prevents dirty reads but still allows non-repeatable reads and phantoms.

FWhat is a deadlock?concept

Two sessions each hold a lock the other needs, so neither can continue. SQL Server detects it within seconds, chooses one session as the victim, rolls it back, and returns error 1205, letting the other finish.

MWhat is a dirty read, and which setting allows it?concept

A dirty read sees a change that another transaction has not committed and may roll back. READ UNCOMMITTED and the NOLOCK hint allow it. In the SMS demo, a NOLOCK read returned a phone number that was rolled back a moment later.

MHow do you find which session is blocking another?coding

Query sys.dm_exec_requests for rows where blocking_session_id <> 0, joined to sys.dm_exec_sql_text for the waiting query. It shows who waits, who blocks, the wait type such as LCK_M_S, and for how long.

MWhat is Read Committed Snapshot Isolation (RCSI)?concept

A database setting that makes normal READ COMMITTED reads use the last committed version of each row instead of waiting for writers' locks. Readers stop blocking on writers, and still never see uncommitted data. The cost is row versions kept in tempdb.

SUsers get deadlock errors when saving attendance and fees. How do you reduce them?scenario

Capture the deadlock details (from the system_health session) to see which statements and resources are involved. Then make every code path touch tables and rows in the same order, keep transactions short, add indexes so fewer rows are locked, and retry error 1205 a few times.

How to answer:

Start from evidence (the deadlock graph), then apply the prevention techniques in order of impact. Explain why retrying is still needed, and why NOLOCK is not a fix.

SA developer added WITH (NOLOCK) to every report query to stop blocking. What is your response?scenario

NOLOCK can return uncommitted rows, skip rows, or read rows twice when pages move, so reports can show wrong numbers. Find the real cause of the blocking, usually long transactions or missing indexes, and consider RCSI so reports read committed versions without waiting.

How to answer:

Acknowledge the pain, explain the correctness risks with a concrete example, and offer better options. Mention where NOLOCK is acceptable: rough monitoring queries where accuracy does not matter.

AHow would you choose isolation settings for an SMS serving 1,000 schools?design

Turn on RCSI so reads do not block on writes, keep READ COMMITTED as the default, and use stronger locking only where needed, such as UPDLOCK on an invoice during payment. Test under realistic concurrency, and monitor blocking and deadlocks in production.

How to answer:

Weigh correctness, concurrency, and tempdb cost. Explain why SERIALIZABLE everywhere does not scale, and why targeted locking for money operations does. Mention load testing at the 8:45 AM peak and monitoring.

Indexes

FWhat is an index?concept

A sorted structure that lets SQL Server find rows without reading the whole table, like the index at the back of a book. In the SMS, an index on AttendanceDate cut one day's attendance query from 3,351 page reads to 38.

FWhat is the difference between a clustered and a nonclustered index?concept

The clustered index is the table itself, stored in key order; there is only one. A nonclustered index is a separate sorted copy of some columns with a pointer to the row; a table can have many. Primary keys are clustered by default.

FWhat is the difference between an index seek and an index scan?concept

A seek jumps straight to the matching values in a sorted index and reads few pages. A scan reads the whole index or table. Scans are fine for small tables or when most rows are needed, but a scan on a big table for a few rows usually means a missing or unusable index.

MWhat is a covering index, and what does INCLUDE do?concept

A covering index contains every column a query needs, so no key lookups to the table are required. INCLUDE adds columns to the index's leaf level without sorting by them, such as INCLUDE (Status) on the attendance date index.

MWhy does the order of columns in a multi-column index matter?concept

SQL Server can seek only on the leading column or columns. An index on (ExamSubjectId, EnrollmentId) helps a search by paper, but not a search by enrollment alone, which is why the SMS needed a separate index starting with EnrollmentId.

MWhat is the cost of adding indexes?concept

Every insert, update, and delete on the indexed columns must also update each index, so writes get slower, and each index takes storage and memory. Add indexes for frequent, measured queries, and drop indexes that are never used.

SThe daily attendance report is slow. Walk through how you would decide which index to add.scenario

Measure the query with SET STATISTICS IO and the actual plan, and find the scan on the big table. Index the filtered column first, here AttendanceDate, and include the columns the query reads, here Status. Measure again: in the SMS, reads dropped from 3,351 to 38.

How to answer:

Follow measure, analyze, change, measure. Explain the column choice (filter first, include the rest) and confirm the plan changed to a seek. Mention checking the write cost on a busy table.

SA table has 23 indexes and inserts are slow. What do you do?scenario

Check sys.dm_db_index_usage_stats over a representative period to find indexes with many updates and no reads, and look for indexes that duplicate or overlap others. Drop or merge them after review, keeping the ones that serve important queries.

How to answer:

Show a data-driven clean-up: usage statistics, overlap analysis, and agreement with the team. Mention that usage stats reset on restart, so measure over a long enough period, and keep indexes that support constraints.

AHow do you plan an indexing strategy for a new system?design

Start with primary keys, unique constraints, and indexes on foreign keys used in joins. Then add indexes for the most frequent and most important queries, tested with realistic data volumes. Review usage and missing-index data after launch, and maintain indexes and statistics on a schedule.

How to answer:

Describe the lifecycle: design-time basics, query-driven additions, load testing, and production review. Balance read speed against write cost per table, such as the busy attendance table versus rarely written masters.

Execution plans

FWhat is an execution plan?concept

The step-by-step recipe SQL Server chooses to run a query: which indexes to read, in what order, and how to join the results. You read it in SSMS to see why a query is slow.

FWhat is the difference between an estimated and an actual execution plan?concept

The estimated plan is built without running the query and shows guessed row counts. The actual plan is captured while the query runs and adds real row counts. Use the actual plan when you can, because big gaps between estimated and actual rows point to problems.

FWhat does SET STATISTICS IO ON show, and why is it useful?concept

It reports the logical reads (8 KB pages read) for each table a query touches. Logical reads do not change with caching, so they are a fairer before-and-after measure than duration.

MWhat does SARGable mean? Give an example of a non-SARGable condition.concept

A SARGable condition lets SQL Server seek in an index. YEAR(AttendanceDate) = 2026 is not SARGable because the function hides the column; in the SMS it read 1,567 pages, while AttendanceDate = '2026-07-01' read 38. Compare the bare column, using a date range if needed.

MWhat is an implicit conversion, and how does it hurt performance?concept

When a value's type differs from the column's, SQL Server converts one of them. If it must convert the column, as with a VARCHAR column compared to an NVARCHAR value, it cannot seek. In the SMS, N'ADM-2017-0001' caused a scan of 39 reads; 'ADM-2017-0001' was a 4-read seek.

MWhat is a key lookup, and why might SQL Server ignore your index?concept

A key lookup fetches columns missing from a nonclustered index, one row at a time. For many rows, SQL Server decides a full scan is cheaper: 668 matching Sharmas led to a scan of 126 reads. A covering index with INCLUDE turned it into a 6-read seek.

SA query ran in 1 second yesterday and takes 40 seconds today. Nothing was deployed. What do you check?scenario

Check for blocking first, then compare today's plan with the old one, using Query Store if it is on. Common causes are parameter sniffing (a plan built for unusual values), outdated statistics after a big data load, and data growth past a tipping point.

How to answer:

Give a calm, ordered checklist: blocking, plan change, statistics, data volume. Explain how you would prove the cause, then the fix, such as updating statistics, forcing a good plan, or adjusting an index. Mention measuring after the fix.

SWhat is parameter sniffing, and how do you deal with it?concept

SQL Server builds a procedure's plan for the first parameter values it sees and reuses it. That plan can be poor for very different values, such as a tiny section versus a huge one. Fixes include better indexes, OPTION (RECOMPILE) for a specific query, or forcing a good plan with Query Store.

How to answer:

Explain that sniffing is normally helpful, then show when it hurts with the SMS class list example. Compare fixes by cost: RECOMPILE costs CPU per call, while a better index helps every value.

AHow would you set up ongoing query performance monitoring for a production database?design

Turn on Query Store to keep plan and runtime history, and track the top queries by total CPU and reads. Alert on regressions, blocking, and deadlocks, and review the top queries regularly, tuning with the measure, change, measure method.

How to answer:

Describe the tools (Query Store, DMVs, alerts), the routine (weekly top-N review), and the ownership (who acts on alerts). Link it to business outcomes, such as the attendance peak at the start of the school day.

Security and backup

FWhat is the difference between a login and a user in SQL Server?concept

A login is server-level and controls who can connect. A user is database-level, mapped to a login, and holds permissions inside one database. For example, SchoolApiLogin connects, and SchoolApiUser works in SchoolDb.

FWhat do GRANT, DENY, and REVOKE do?concept

GRANT allows an action, DENY forbids it, and REVOKE removes an earlier grant or deny. DENY always wins over GRANT, which is how a role can delete in general but never delete from Students.

FWhat are the full, differential, and transaction log backup types?concept

A full backup copies the whole database. A differential copies changes since the last full backup. A log backup copies changes since the last log backup and allows restoring to a point in time.

MWhat is the difference between the SIMPLE and FULL recovery models?concept

SIMPLE allows no log backups, so you can restore only to the last full or differential backup. FULL needs regular log backups, or the log keeps growing, and it allows restoring to any point in time. Use SIMPLE for development and FULL for production.

MWhy should an application not connect as sa or db_owner?concept

One bug or SQL injection would then have full control, including dropping the database. Least privilege gives the application its own login and a role with only the permissions it needs, such as running procedures and changing specific tables.

MWhat are RPO and RTO?concept

RPO (Recovery Point Objective) is how much data the business can afford to lose, such as 15 minutes. RTO (Recovery Time Objective) is how long the system may be down, such as 2 hours. Together they decide the backup types and schedule.

SThe school can lose at most 15 minutes of data. Design the backup schedule and explain a restore to 10:40 AM Wednesday.scenario

Use the FULL recovery model, a full backup on Sunday night, differentials on the other nights, and log backups every 15 minutes. To restore: Sunday's full backup, Tuesday night's differential, then every log backup up to 10:40 with STOPAT.

How to answer:

Start from RPO and RTO, then derive the schedule. Walk through the restore sequence step by step, and add retention, off-site copies, and regular restore tests.

SHow do you know your backups actually work?concept

RESTORE VERIFYONLY checks that a backup file is readable, but only a real restore proves it. Restore regularly to a test server, run DBCC CHECKDB, check key row counts, and time it against the RTO.

How to answer:

Distinguish verifying a file from proving a restore. Describe an automated, scheduled restore test with results someone reviews, and mention that the course's restored copy was checked by counting students.

AHow would you protect a school database against ransomware?design

Follow 3-2-1: three copies, on two kinds of storage, one off site, plus one immutable copy that cannot be changed or deleted for a set time. Limit who can reach backup storage, use separate credentials for it, and test restores from the immutable copy.

How to answer:

Cover prevention (least privilege, patching), protection of backups (immutability, separate accounts), and recovery (tested restore plan meeting the RTO). Keep it business-focused: the school must be running again on the next school day.

Interview practice

FWrite a query to find the second-highest mark in a paper.coding

Use DENSE_RANK() OVER (ORDER BY MarksObtained DESC) and keep rank 2, or use a subquery: MAX(MarksObtained) WHERE MarksObtained < (SELECT MAX(...)). For 10-A's Mathematics marks of 95, 92, 85, and 67, both return 92.00, and DENSE_RANK handles ties and any N.

FHow do you find duplicate values in a column?coding

Group by the column and keep groups with more than one row: SELECT LastName, COUNT(*) FROM dbo.Students GROUP BY LastName HAVING COUNT(*) > 1;. To delete duplicates while keeping one, use ROW_NUMBER() partitioned by the column.

FWhat is the difference between UNION and UNION ALL?concept

UNION ALL keeps every row; UNION removes duplicates, which needs a sort or hash. In the SMS, 8 teacher and 22 guardian last names give 30 rows with UNION ALL but 19 with UNION. Prefer UNION ALL when duplicates are impossible or wanted.

MHow do you find rows in one table with no match in another?coding

Use NOT EXISTS with a correlated subquery, or a LEFT JOIN and WHERE right.Id IS NULL. Avoid NOT IN when the subquery's column can be NULL, because one NULL makes it return no rows.

MHow do you turn rows into columns, such as one column per attendance status?coding

Use conditional aggregation: SUM(CASE WHEN Status = 'Present' THEN 1 ELSE 0 END) AS Present, one expression per status, grouped by student. SQL Server's PIVOT keyword does the same, but SUM(CASE ...) is easier to read and works in every database.

MWhy is DATEDIFF(YEAR, DateOfBirth, @Date) wrong for age, and how do you fix it?coding

DATEDIFF counts year boundaries crossed, not birthdays. Someone born 23 August 2011 gets 15 on 1 July 2026, but is really 14. Subtract 1 when the birthday has not yet happened in that year.

STell me about a database you designed.scenario

In about two minutes, cover what it is, the key design choices, the rules enforced in the database, the performance work with numbers, and safety. For the SMS: 22 tables, enrollments per year, a trigger and transactional procedures, indexes cutting 3,351 reads to 38, and least-privilege roles with tested backups.

How to answer:

Use the five-part structure and give at least one measured result. Be ready for follow-ups on any part, and mention a trade-off you made and why.

SThe fee report is suddenly slow. Walk me through your answer.scenario

Restate the symptom and ask what changed, then measure: actual plan, logical reads, and blocking. List the likely causes in order, such as a plan change, outdated statistics, or a missing index after data growth. Make the smallest fix, measure again, and add monitoring.

How to answer:

Use the five-part scenario structure: symptom, measure, cause, fix, prevent. Keep each part short and concrete, naming the exact tools you would use.

AAs a lead, how would you assess a candidate's SQL skills?design

Mix a short live task on a realistic schema, a design discussion, and a scenario question. Judge how they clarify requirements, handle NULLs and ties, test edge cases, and explain trade-offs, not just whether the query runs.

How to answer:

Describe a structured, fair process: the same tasks and scoring rubric for every candidate, with expectations matched to the level. Mention watching for thinking aloud and self-correction.

Temp tables and cursors

FWhat is a temp table in SQL Server?concept

A table whose name starts with #, stored in tempdb and visible only to your session. It lives until the session ends or you drop it. You use it to save an intermediate step of a report and reuse it in later queries.

FWhat is the difference between #Name and ##Name?concept

#Name is a local temp table, visible only to the session that created it. ##Name is a global temp table, visible to every session. Reports should use local tables, so two users never share or overwrite each other's data.

FWhat is a cursor, and what are its steps?concept

A cursor reads a query's rows one at a time. The steps are DECLARE, OPEN, FETCH NEXT, a WHILE @@FETCH_STATUS = 0 loop, and finally CLOSE and DEALLOCATE.

MCompare a temp table, a table variable, and a CTE.concept

A CTE is not stored and belongs to one statement. A temp table lives in tempdb until the session ends, has statistics, and can have any index. A table variable lives for one batch, has no column statistics, and is not undone by ROLLBACK. Use temp tables for big or reused steps.

MWhy is a cursor usually slower than a set-based query?concept

A cursor runs one small query per row, each with its own overhead. A set-based query reads the data once in one plan. In the SMS, a cursor over 10,012 students took about 2.9 seconds, and one GROUP BY gave identical results in about 0.2 seconds.

MWhat happens to a table variable's rows when a transaction rolls back?concept

They stay. Table variables are not part of the transaction, so ROLLBACK does not undo them. This is useful in a CATCH block: save error details in a table variable, roll back, and then write them to a log table.

SA nightly job loops over 10,000 students with a cursor and takes 40 minutes. How do you fix it?scenario

Find what each loop iteration does, and express the whole job as a few set-based statements, using temp tables for intermediate steps. Prove the new version gives the same rows with EXCEPT, then measure. Keep a loop only for work that truly must happen one row at a time.

How to answer:

Show the method: understand, rewrite in sets, prove equality, measure. Mention SET NOCOUNT ON, testing on a copy of production-sized data, and running old and new versions side by side before switching.

SWhen is a cursor the right choice?concept

When each row must go through logic that handles one row at a time, such as calling a procedure like usp_RecordFeePayment for every payment in an uploaded file. Admin scripts that loop over databases or tables are another fair use. Use LOCAL FAST_FORWARD.

How to answer:

Avoid "never use cursors". Give the rule (if it can be one query, write one query), then real exceptions, and mention the alternative of a set-based procedure that accepts many rows.

AHow would you guide a team that writes most reports with loops and cursors?design

Set a review rule: set-based first, cursors only with a written reason. Provide patterns (temp-table steps, window functions, conditional aggregation), pair on rewriting the slowest jobs, and track their run times so the gains are visible.

How to answer:

Focus on changing habits, not one query: standards, examples, mentoring, and measurement. Mention tempdb sizing and monitoring as temp tables become more common.

MERGE and upserts

FWhat is an upsert?concept

Updating a row if it already exists and inserting it if it does not, in one operation. Loading a revised fee list, where some fees change and some are new, is an upsert.

FWhat are the three branches of a MERGE statement?concept

WHEN MATCHED (in both, usually update), WHEN NOT MATCHED BY TARGET (only in the source, usually insert), and WHEN NOT MATCHED BY SOURCE (only in the target, usually delete). Each is optional, and the statement must end with a semicolon.

FWhat is a staging table?concept

A table that holds incoming data, such as an uploaded file, before it touches the real tables. You can check and clean the data there, then apply it with a merge.

MHow do you see what a MERGE changed?coding

Add an OUTPUT clause. $action returns INSERT, UPDATE, or DELETE for each row, deleted holds the old values, and inserted the new ones. You can also send the output into a log table with OUTPUT ... INTO.

MWhat causes error 8672 in a MERGE, and how do you prevent it?concept

One target row matched more than one source row, so SQL Server would update or delete it twice. Prevent it with a primary key on the staging table, or remove duplicates before the merge.

MWhy add WITH (HOLDLOCK) to a MERGE?concept

Without it, two sessions running the same merge can both decide a row is missing and both insert it, causing a duplicate key error. HOLDLOCK keeps the range locked for the whole statement, so the second session waits.

SA teacher uploaded one section's student list and the import deleted every other section's students. What went wrong, and how do you prevent it?scenario

The merge had a WHEN NOT MATCHED BY SOURCE THEN DELETE branch on the whole table, so every row missing from the file counted as deleted. Limit the target to the rows the file covers, preview deletes before running, and require confirmation. Foreign keys and backups are the last line of defense.

How to answer:

Explain the mechanism, then the immediate recovery (restore or rebuild from backup), then prevention at several layers: scoped targets, previews, confirmation, foreign keys, and tests with a partial file.

SMERGE or UPDATE plus INSERT: which do you choose for an upsert?concept

Both work when written carefully. MERGE is shorter and can also delete, but has more traps: duplicates, scoping, and concurrency. UPDATE plus INSERT in a transaction with UPDLOCK, HOLDLOCK is longer but easier to review. Follow the team standard.

How to answer:

Compare on correctness, readability, and concurrency, and show you know the traps of each. Mention making the upsert idempotent, so a repeated import changes nothing.

ADesign a safe fee-list import for 1,000 schools.design

Upload into a staging table with keys and validation, show a preview of inserts, updates, and deletes, and require a person to confirm. Apply in a short transaction with locking hints, log every change with OUTPUT, and keep the import idempotent so retries are harmless.

How to answer:

Cover the full flow: upload, validate, preview, approve, apply, audit. Address scale (one school's import must never touch another school's rows) and recovery (undo from the change log).

JSON

FWhat is JSON, and how does SQL Server store it?concept

JSON is a text format of objects (name and value pairs), arrays, and values, used by web and mobile apps. SQL Server 2022 stores it as text in NVARCHAR(MAX); SQL Server 2025 adds a native json type.

FWhat do FOR JSON PATH and OPENJSON do?concept

FOR JSON PATH turns query results into JSON text. OPENJSON does the opposite: it turns JSON text into rows, which you can select or insert into a table.

FHow do you check whether a string is valid JSON?concept

ISJSON(@text) returns 1 for valid JSON and 0 otherwise. A trailing comma, for example, makes it return 0.

MHow do you return nested JSON, such as a student with a guardians array?coding

Use FOR JSON PATH. A dot in a column alias, like [currentClass.section], creates a nested object. A correlated subquery that ends with FOR JSON PATH creates an array. Add WITHOUT_ARRAY_WRAPPER to return a single object.

MWhat is the difference between JSON_VALUE and JSON_QUERY?concept

JSON_VALUE returns a single value, such as a number or text. JSON_QUERY returns an object or array. JSON_VALUE on an object returns NULL, which is a common surprise.

MHow do you insert rows from a JSON array?coding

Use INSERT ... SELECT ... FROM OPENJSON(@json) WITH (Column TYPE '$.path', ...). The WITH clause names each column, its type, and its path; missing properties become NULL. Paths are case-sensitive.

SThe attendance app sends one request per student and some fail on weak networks. How would you redesign it?scenario

Send the whole section as one JSON array and save it with one INSERT ... OPENJSON (or a bulk insert from C#) inside a transaction. The section is then saved completely or not at all, and the app can retry safely because the unique key prevents duplicates.

How to answer:

Explain the failure mode (partial saves), the new design (one atomic call), and the safety net (validation, constraints, unique keys for idempotent retries). Mention a clear error message for the teacher.

SWhen should data be stored as JSON instead of normal columns?concept

Use JSON for data with a varying shape that you store and return whole, such as audit details or extra settings. Use normal columns for anything you filter, join, sort, or must check with constraints.

How to answer:

Give both sides with examples, then the cost of getting it wrong: slow, unchecked filters on JSON, or many sparse columns. Mention computed columns with indexes for the occasional JSON filter.

AShould JSON for an API be built in SQL Server or in the application?design

Usually in the application: the API controls its own response format, and C# serializes objects automatically. FOR JSON is a good option for large nested reports read straight from the database, and OPENJSON for saving many rows sent in one call.

How to answer:

Weigh separation of concerns, performance, testability, and team skills. Show you would pick per case and keep one consistent default.

Temporal tables

FWhat is a temporal (system-versioned) table?concept

A table for which SQL Server automatically keeps every old version of every row in a history table. Two period columns, ValidFrom and ValidTo, record when each version was valid.

FHow do you see a table as it was at a past moment?coding

Query it with FOR SYSTEM_TIME AS OF @moment. SQL Server combines current and history rows to rebuild the table at that moment. FOR SYSTEM_TIME ALL returns every version.

FIn which time zone are a temporal table's period columns stored?concept

UTC. SQL Server fills them itself, so a local time must be converted to UTC before using it in AS OF.

MHow do you turn an existing table into a temporal table?coding

Add two DATETIME2 columns GENERATED ALWAYS AS ROW START and ROW END with defaults and a PERIOD FOR SYSTEM_TIME, then SET (SYSTEM_VERSIONING = ON (HISTORY_TABLE = ...)). HIDDEN keeps the new columns out of SELECT *.

MCan you edit or delete rows in a temporal history table?concept

Not while versioning is on: updates fail with error 13561 and deletes are blocked too. Only someone with ALTER TABLE permission can turn versioning off, which makes the history trustworthy.

MDoes a temporal table record who changed a row?concept

No, only when. Keep an UpdatedBy column in the row; because it is versioned with the rest of the row, the history then shows who made each change.

SA parent disputes last term's fee. How would temporal tables help, and how would you answer them?scenario

Query the fee table FOR SYSTEM_TIME AS OF the payment time, converted to UTC, and show the amount that was valid then, plus who changed it and when from the versions list. The history cannot be edited, so the answer is reliable.

How to answer:

Walk through the query, the UTC conversion, and how you present the evidence. Mention that without versioning you would depend on invoices and emails.

SCompare audit triggers, temporal tables, and change data capture.concept

Audit triggers keep exactly what you choose and need code. Temporal tables keep every version automatically and answer "as of" questions. Change data capture reads changes from the log for other systems and needs SQL Server Agent.

How to answer:

Compare setup, storage, query style, and requirements, then pick per need: temporal for prices and settings, triggers for custom audit rules, CDC for data feeds.

AWhich tables in a multi-school SaaS would you make temporal, and how would you manage history growth?design

Version tables whose past values matter and change rarely: fees, prices, rates, and settings. Avoid busy tables like attendance. Set a retention period that matches the legal rule, watch history size, and include history tables in backup and archiving plans.

How to answer:

Tie each choice to a business question ("what was it on that date?"), then cover cost, retention, compliance, and operations.