QA Interview Hub · Knowledge base · Quizzes · Українська

SQL

Database basics

tables, keys, types, NULL

What is a relational database and what is SQL?

A relational database stores data in related tables with a predefined schema, and SQL is a declarative query language for it. A query describes the result needed, and the optimizer decides how to find it, for example through an index. The core of SQL is the same across engines (SELECT, JOIN, GROUP BY), but dialects differ in details: row limiting, date functions, the empty string in Oracle.

SQL · Basics

A table holds three million transactions and you need the last five failed ones. How to get them without a loop?

A QA engineer checks whether failed payments reach the log. The database holds three million transactions, and only the last five with status FAILED matter. You can export everything and filter in code, or ask the database for exactly that in one query. This lesson explains what a relational database consists of, why SQL describes the result and not the steps, and where the "sameness" of SQL across engines ends.

How it works and why. A relational database stores data in tables (formally, relations). A row is one record: a user, an account, a transaction. A column is a property with a fixed type. The schema (the set of tables, types and constraints) is defined in advance, and the database itself rejects what contradicts it: text in a numeric field, a row pointing to a record that does not exist. Tables are linked by keys: accounts.user_id points to users.id, so every fact lives in one place and cannot drift from its copies.

Two tables linked by a key

users
idemail
1anna@test.com
2ivan@test.com
accounts
iduser_idbalance
101100.00
1115.50
1220.00
Figure 1. Accounts 10 and 11 belong to user 1, account 12 to user 2. The email is stored once, in users.

SQL is declarative. A query describes the result you need: from which table, under which condition, in which order. How to find it is decided by the DBMS: the optimizer builds a plan, for example uses an index instead of a full table scan. So the same query can run in milliseconds or minutes depending on indexes and statistics, while the result does not change.

Example: from a loop to a query. The imperative approach pulls all three million rows into the application:

// imperative: pull everything and filter by hand
const all = await db.query('SELECT * FROM transactions');
const failed = all
  .filter((r) => r.status === 'FAILED')
  .sort((a, b) => b.created_at - a.created_at)
  .slice(0, 5);

The bottleneck here is the network and memory: filtering, sorting and trimming happen after all the data has been transferred. The declarative form hands the same work to the database, which has indexes and sits next to the data:

-- declarative: describe the result
SELECT id, amount, created_at
FROM transactions
WHERE status = 'FAILED'
ORDER BY created_at DESC
LIMIT 5;

The client receives five rows instead of three million. For QA it is also a way to check test data without pulling everything into an automated test: the query can be run in a database client (psql, DBeaver, DataGrip) in a minute.

Two ways to get five rows

Imperative

A loop in code

Export everything, filter, sort, trim. Lots of data on the network, lots of code.

Declarative

One SQL query

Describe the result. The database picks the plan and access path, the client receives only what is needed.

Figure 2. Both approaches give the same result. The difference is who does the work and how much data travels over the network.

Limits and dialects. SQL is a standard (ISO/IEC 9075), but each DBMS adds its own dialect. The core is the same: SELECT, JOIN, GROUP BY. Details differ, and interviews are likely to ask about them:

-- PostgreSQL, MySQL
SELECT id FROM transactions ORDER BY id LIMIT 5;
-- SQL Server
SELECT TOP 5 id FROM transactions ORDER BY id;
-- standard form (PostgreSQL, Oracle 12c+; SQL Server only with ORDER BY … OFFSET 0 ROWS)
SELECT id FROM transactions
ORDER BY id
FETCH FIRST 5 ROWS ONLY;

Other differences: date functions, types (JSONB exists in PostgreSQL), identifier quoting, the behaviour of the empty string (Oracle treats it as NULL). Examples in this course are given for PostgreSQL. The relational model is not the only one: document stores (MongoDB) and key-value stores fit better when the schema changes often or there are almost no relations, but for integrity guarantees and transactions relational databases remain the base for financial data. PostgreSQL can also store flexible documents in JSONB.

Common mistakes.

  • Thinking SQL runs top to bottom in the order written: the real order is different (there is a separate lesson).
  • Moving the syntax of one dialect to another without checking: LIMIT does not work in SQL Server, TOP does not work in PostgreSQL.
  • Exporting a table into code to filter it instead of querying.
  • Treating the database as "just storage": it checks types, uniqueness and relations itself.
  • Running a query on a shared environment without knowing whether it only reads.

Check yourself

Why is a query with WHERE and ORDER BY faster in the database than the same loop in a test?

Answer

In the database, filtering and sorting happen next to the data, often with an index, and the client receives only the result. In a loop all rows first travel over the network into the test and only then get discarded.

Is it true that SQL is the same in every DBMS?

Answer

Only the core: SELECT, JOIN, GROUP BY, INSERT. There are differences in limiting rows (LIMIT, TOP, FETCH FIRST), date functions, types and the handling of the empty string, so an example written for one DBMS has to be checked on another.

In an interview. Junior: A relational database stores data in linked tables, and SQL is the query language for it. I describe which data I need and the database decides how to find it. The core is the same in PostgreSQL, MySQL and SQL Server. Middle/Senior: SQL is declarative: the optimizer builds an execution plan, so the same query depends on indexes and statistics. A schema with types and foreign keys protects integrity at the database level. Dialects differ in details (LIMIT, TOP, dates, the empty string in Oracle), so I check code written for one DBMS on the target one.

What are a primary key and a foreign key?

A primary key uniquely identifies a row: its values are unique and cannot be NULL. A foreign key is a column whose values must exist in the primary or unique key of another table, or be NULL if allowed. The database checks this both when a child row is inserted and when a parent row is deleted, and ON DELETE sets the deletion behaviour. Keys do not check business meaning.

SQL · Basics

A test deletes a user and the API answers 500. What exactly did the database reject?

An automated test cleans data: it deletes a user who already has an account. The API answers 500 and the log contains a line about a constraint violation. This is not a failure but the foreign key doing its job: the database refuses to leave an account without an owner. This lesson is about how primary and foreign keys guarantee integrity, what exactly they check and which test cases follow from them.

How it works and why. A primary key (PRIMARY KEY) uniquely identifies a row: values are unique and cannot be NULL. A table has only one, but it can consist of several columns (a composite key). It can be a "surrogate" key (a counter number, a UUID) that means nothing, or a "natural" one (for example an email). Natural keys are risky: an email changes and every reference would have to be fixed, so relations usually use a surrogate.

A foreign key (FOREIGN KEY) is a column whose values must exist in the primary (or unique) key of another table, or be NULL if the column allows it. The database checks this on every change: when a child row is inserted or updated (the reference must lead to an existing record) and when a parent row is deleted or changed (nothing may reference it). So an "orphan" record simply cannot appear in such a schema.

The schema from the example, PostgreSQL:

CREATE TABLE users (
  id    integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email text NOT NULL UNIQUE
);

CREATE TABLE accounts (
  id       integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id  integer NOT NULL REFERENCES users (id),
  currency char(3) NOT NULL,
  balance  numeric(14,2) NOT NULL DEFAULT 0
);

What the foreign key accepts

INSERT into accounts
user_idresult
1ok
2ok
999error rejected
users
idemail
1anna@test.com
2ivan@test.com
Figure 1. User 999 does not exist in users, so the database rejects the whole row instead of storing it with a "broken" reference.

Example: what the test sees. Creating an account for a user that does not exist:

INSERT INTO accounts (user_id, currency) VALUES (1,   'UAH');
INSERT INTO accounts (user_id, currency) VALUES (999, 'UAH');
-- ERROR: insert or update on table "accounts" violates
-- foreign key constraint "accounts_user_id_fkey"
-- DETAIL: Key (user_id)=(999) is not present in table "users".

The error texts are shortened, and their form depends on the DBMS and version (MySQL, SQL Server and Oracle word them differently, but the point is the same). The reverse side: deleting a parent row that is still referenced:

DELETE FROM users WHERE id = 1;

It helps to tell apart: a database error is correct behaviour, but how the user learns about it depends on the application. An API that returns 500 with the query text has a defect (a leak of details), while 409 with an explanatory message is proper handling. What happens to child records on delete is decided by the ON DELETE rule (rejection by default, there are CASCADE and SET NULL); there is a separate lesson on that.

Reading the error: deleting a parent

1ERROR:  update or delete on table "users" violates foreign key constraint "accounts_user_id_fkey" on table "accounts"
2DETAIL:  Key (id)=(1) is still referenced from table "accounts".
  1. What: a DELETE in the users table violated the foreign key accounts_user_id_fkey, which lives on the child table accounts. The constraint name says which rule fired.
  2. Which row: DETAIL names the key, id = 1: accounts still reference it. This explains why the delete was refused.

What to do

First remove the user's accounts and then the user, or choose an ON DELETE behaviour on purpose. Check that the API answers clearly and not with a 500 carrying the database text.

Figure 2. The real PostgreSQL message format (shortened): the numbers lead to the explanations.

What to test here.

  • Creating a child record with a non-existent reference: it must be rejected, not silently stored.
  • Deleting a parent that has children: rejection, cascade or nulling, depending on requirements.
  • A duplicate primary key or unique field (the same email twice).
  • NULL in the foreign key column: whether an "optional" relation is allowed by business logic.

Limits and special cases. Not every schema has foreign keys: they are sometimes deliberately turned off (legacy databases, distributed services whose tables live in different databases). Then orphan records really appear, and they are found with a separate integrity query. In PostgreSQL a foreign key does not create an index on the referencing column automatically, so deleting parents and JOINs may be slow without one. A foreign key protects only the existence of the reference, not its business meaning: a UAH account can reference any existing user.

Common mistakes.

  • Taking an email or phone as a primary key: the value changes and relations break.
  • Assuming a foreign key is always there: the schema may lack it, and the data may already hold orphan rows.
  • Checking only the UI: the form does not let you pick someone else's user, while the API or SQL does.
  • Cleaning test data in the wrong order: child rows must be deleted first, then parents.
  • Accepting a 500 from the API as the norm for a key violation: the client should get a clear error.

Check yourself

The orders table has a user_id column with a foreign key to users. Can an order be inserted with user_id = NULL?

Answer

Yes, if the column is not declared NOT NULL: NULL means "no reference" and the foreign key does not check it. Whether that is acceptable for an order is decided by business logic, so it is a separate test case.

Why does the users table use a surrogate primary key while the email is just a unique field?

Answer

An email can change, and the primary key is used in references from other tables. A surrogate key is stable, and the uniqueness of the email is guaranteed by a separate UNIQUE constraint.

In an interview. Junior: A primary key uniquely identifies a row: it is unique and never NULL. A foreign key points to the primary key of another table and does not allow a reference to a record that does not exist. As QA I check that the system handles such an error properly. Middle/Senior: The database checks a foreign key both when a child row changes and when a parent is deleted, and ON DELETE sets the behaviour. I test an insert with a missing reference, deleting a parent with children, duplicates and NULL, and I look for orphan records where keys are not declared.

Which data types should QA know?

QA should know column types because a type decides which values the database accepts and gives a ready list of boundary values. The main ones are integers (INTEGER ends at 2,147,483,647), NUMERIC for money, REAL and DOUBLE PRECISION with rounding error, strings, BOOLEAN, date and time (TIMESTAMP or TIMESTAMPTZ), UUID and JSONB. A mismatch of types between UI, API and database is itself a source of bugs.

SQL · Basics

The "Amount" field accepts 0.1 + 0.2, but the database holds 0.30000000000000004. Which type was chosen?

A bug in a report: the sum of two payments of 0.10 and 0.20 does not equal 0.30. The tester looks at the schema and sees that the column has a floating-point type. A column type decides which values the database accepts, how much space they take, how they compare and where the boundary it will not cross lies. So the type is a source of boundary values for tests. Below: which types are worth knowing, what breaks with them and how to check it.

How it works and why. Every column has a type, and the database checks it on write and uses it in comparison, sorting and calculations. That is why values that look identical behave differently: the string '10' sorts before '9', the number 10 after 9. The type's limits are a ready list of boundary values: the largest number, the longest string, the number of decimal places.

TypeUsed forWhat to watch
INTEGER, BIGINTIntegers, IDsINTEGER ranges from −2,147,483,648 to 2,147,483,647; BIGINT is much larger
NUMERIC(p,s)Exact decimals, moneyp is total digits, s after the point; NUMERIC(14,2) allows up to 12 digits before the point
REAL, DOUBLE PRECISIONApproximate decimalsThey carry an error, not for money
VARCHAR(n), TEXTStringsWhat happens to a string longer than n
BOOLEANYes / noCan also be NULL
DATE, TIMESTAMP, TIMESTAMPTZDates and timeWith or without a time zone
UUID, JSONBUnique IDs, flexible dataFormat; nested fields are not checked by the schema

Example: money in the "wrong" type. The amount column is declared as DOUBLE PRECISION. Binary floating point cannot store 0.1 exactly, so sums accumulate an error:

SELECT 0.1::double precision + 0.2::double precision AS f,
       0.1::numeric + 0.2::numeric AS n;
-- f = 0.30000000000000004   n = 0.3
SELECT 0.1::double precision + 0.2::double precision
     = 0.3::double precision;   -- false

Money: two types

Risk

DOUBLE PRECISION

An approximate value. 0.1 + 0.2 is not 0.3, and reconciling a balance with the history drifts by cents.

Correct

NUMERIC(14,2)

Exact decimal arithmetic. The schema sets how many decimal places are kept, extra ones are rounded.

Figure 1. For amounts and balances use NUMERIC or integers in the smallest unit (cents). A float for money is a schema defect.

The schema-level fix is NUMERIC(14,2). But it has limits too. Here is what happens to input values:

NUMERIC(14,2) on input

sent
value
99.50
1.239
999999999999.99
1000000000000 rejected
stored
value
99.50
1.24
999999999999.99
Figure 2. Extra decimal places are rounded, while a number that does not fit into 12 digits before the point is rejected with a "numeric field overflow" error.

Other typical boundaries for tests:

SELECT 2147483647 + 1;
-- ERROR: integer out of range

INSERT INTO users (email) VALUES (repeat('a', 300));
-- for varchar(255): ERROR: value too long
-- for type character varying(255)

Strings: in PostgreSQL inserting a value longer than varchar(n) is an error. In MySQL it depends on the mode: in strict mode (the default since 5.7) it is also an error, while in non-strict mode the value is silently truncated. That is a separate test case, because truncation is invisible in both the UI and the logs. Dates: TIMESTAMP stores time as is, without a zone, while TIMESTAMPTZ in PostgreSQL stores the moment in UTC and shows it in the session time zone, so different clients see a different "wall clock" for the same record.

Limits and special cases. A database type is not always an API type: JSON has no separate type for dates or for exact numbers, so a NUMERIC sent as a JSON number becomes a floating-point number in JavaScript and may lose precision. So a mismatch of types between UI, API and database is itself a source of bugs: the UI allows 300 characters and the column holds 255. For statuses people often use text with a constraint or an enum, and then values outside the list must be rejected.

Common mistakes.

  • Storing money in REAL or DOUBLE PRECISION: an error accumulates.
  • Not checking the upper bound of INTEGER for counters and IDs that grow for years.
  • Forgetting that the length in the UI and in the database can differ.
  • Comparing TIMESTAMP and TIMESTAMPTZ as if they were the same: the difference shows in another time zone.
  • Assuming JSONB validates structure: the schema does not know which fields are inside.

Check yourself

The amount column has type NUMERIC(14,2). What happens to the input values 12.345 and 1000000000000?

Answer

12.345 is rounded to two places: 12.35 in PostgreSQL, because numeric rounds ties away from zero, while 1000000000000 does not fit into 12 digits before the point, so the database returns an overflow error. Both values are worth checking through the API and the UI.

Why is BIGINT often chosen for IDs although INTEGER looks sufficient?

Answer

INTEGER ends at 2,147,483,647. In a table with many inserts over years of work this limit can be reached, and then inserts fail with an error. BIGINT removes the problem for decades.

In an interview. Junior: Most often it is integers for IDs, NUMERIC for money, strings, booleans and dates. The column type is a source of boundary values for me: string length, decimal places, number range. Middle/Senior: Money is kept in NUMERIC or in cents, because float carries an error. I check INTEGER bounds, the behaviour with a longer string (an error or silent truncation depending on the DBMS) and the difference between TIMESTAMP and TIMESTAMPTZ. A mismatch of types between UI, API and database is a source of defects on its own.

What is NULL and how does it differ from 0 and an empty string?

NULL means the value is unknown or missing, and it is neither zero nor an empty string. A comparison with NULL yields UNKNOWN (three-valued logic), and WHERE, JOIN ON and HAVING keep only TRUE, so such rows silently drop out. Arithmetic with NULL gives NULL, aggregates skip it, and NULL is tested with IS NULL. COALESCE substitutes a value.

SQL · Basics

The filter "balance is not 0" returns one account out of three. Where did the third go?

Three accounts: the first has 100, the second 0, the third has a balance that has not been calculated. The query WHERE balance <> 0 returns only the first, although "not zero" is obviously true for the third as well. The tester sees a mismatch between the query and the report on the page. The cause is the special behaviour of NULL, and it is behind many "vanished" rows and wrong sums.

How it works and why. NULL means "the value is unknown or absent". It is neither zero nor an empty string:

Three different "nothings"

0 : a known numberthe balance equals zero'' : a known empty stringa name was set, and it is emptyNULL : unknownphone not given, balance not calculated
Figure 1. All three look "empty", but only NULL means there is no value at all.

Because of that, comparisons with NULL follow three-valued logic: the result can be TRUE, FALSE or UNKNOWN. balance <> 0 for NULL is UNKNOWN, not TRUE. WHERE filters, JOIN ... ON conditions and HAVING keep only rows where the condition is TRUE, so UNKNOWN is dropped silently, just like FALSE. Even NULL = NULL gives UNKNOWN, and arithmetic with NULL returns NULL: 100 + NULL is NULL.

Example: from a lost row to the right filter. The data is:

A filter that drops NULL

accounts
idbalance
1100
20
3NULL
WHERE balance <> 0
idbalance
1100
20 filtered out
3NULL lost
Figure 2. Zero fails the condition "not zero" and NULL gives UNKNOWN: only account 1 remains in the result.

The fix depends on the requirement. If you need "everything except a known zero", write the condition explicitly:

-- idea: all accounts with a non-zero balance
SELECT id FROM accounts WHERE balance <> 0;
-- returns only id = 1

SELECT id FROM accounts
WHERE balance IS DISTINCT FROM 0;
-- returns id = 1 and id = 3

IS NULL and IS NOT NULL check exactly the absence of a value, while IS DISTINCT FROM compares in a way that treats NULL as an ordinary value. More on searching for empty values is in the lesson about IS NULL.

Aggregates and NULL. The functions COUNT(col), SUM, AVG skip NULL, while COUNT(*) counts all rows. So the average is computed only over known values (here 50, not 33), and the sum of an empty group is NULL, not 0. To replace NULL with a value use COALESCE:

SELECT COUNT(*), COUNT(balance),   -- 3, 2
       SUM(balance), AVG(balance)   -- 100, 50
FROM accounts;

SELECT SUM(balance) FROM accounts WHERE id = 3;   -- NULL
SELECT COALESCE(SUM(balance), 0) FROM accounts
WHERE id = 3;                                     -- 0

Other places where NULL surprises: NOT IN with a list that contains NULL returns no rows (a separate lesson); a CHECK (balance >= 0) constraint lets NULL through, because UNKNOWN is not treated as a violation, so mandatory fields need NOT NULL as well; in a UNIQUE column several NULLs are allowed in PostgreSQL (since version 15 there is UNIQUE NULLS NOT DISTINCT); GROUP BY and DISTINCT gather all NULLs into one group. Sorting: in PostgreSQL NULL goes last in ascending order, in some DBMS first.

Limits and dialects. Oracle treats the empty string '' as NULL ('' IS NULL is TRUE), PostgreSQL does not. A JSON API response also has three states: the field is absent, the field is null and an empty string, and they correspond to different situations in the database. For QA that means separate cases: the field was not sent, null was sent, an empty string was sent.

Common mistakes.

  • Writing = NULL or <> NULL: the result is always UNKNOWN, no rows come back.
  • Filtering with <> or NOT and not noticing that NULL rows dropped out.
  • Treating average and sum as computed "over all rows": NULL is skipped.
  • Relying on CHECK instead of NOT NULL for mandatory fields.
  • Mixing up NULL, 0 and an empty string in test expectations.

Check yourself

Will WHERE phone = NULL return the rows where the phone is not set (NULL)?

Answer

No. A comparison with NULL gives UNKNOWN, so no row passes. The correct form is WHERE phone IS NULL.

In a group all balance values are NULL. What do SUM(balance), COUNT(balance) and COUNT(*) return?

Answer

SUM returns NULL (not 0), COUNT(balance) gives 0 because NULLs are skipped, and COUNT(*) counts all rows of the group. To get 0 in a report use COALESCE(SUM(balance), 0).

In an interview. Junior: NULL means the value is unknown or absent, it is neither zero nor an empty string. Any comparison with NULL gives "unknown", so rows with NULL drop out of filters and arithmetic with NULL gives NULL. It has to be checked with IS NULL. Middle/Senior: The logic is three-valued: WHERE keeps only TRUE. So <> loses NULL rows, CHECK lets them through, aggregates ignore them, and NOT IN with a NULL in the list returns nothing. Mandatory fields need NOT NULL, and in tests I separately check a missing field, null and an empty string.

Which groups are SQL commands divided into?

SQL commands are divided into groups by what they act on: data, structure, permissions or transactions. DQL (SELECT) only reads, DML (INSERT, UPDATE, DELETE) changes rows, DDL (CREATE, ALTER, DROP) changes structure, DCL permissions, TCL transactions. The group hints at risk: DML can be rolled back before COMMIT, while DDL can be rolled back in PostgreSQL but not in MySQL or Oracle.

SQL · Basics

A colleague asks you to "just run a script" on the environment. Does it read data, change data or change structure?

The environment script contains SELECT, UPDATE, ALTER and GRANT. Some lines are safe, others change data, still others can lock a table or hand out permissions. SQL commands are split into groups not for the sake of terms: the group tells what exactly changes, whether it can be rolled back and how careful you must be. This lesson goes through the groups and how to work with them in a test database.

How it works and why. The groups correspond to what the command acts on: rows, structure, permissions or a transaction.

GroupCommandsActs on
DQL (queries)SELECTOnly reads
DML (data)INSERT, UPDATE, DELETE, MERGEChanges rows
DDL (structure)CREATE, ALTER, DROP, TRUNCATEChanges tables and schema
DCL (access)GRANT, REVOKEChanges permissions
TCL (transactions)BEGIN, COMMIT, ROLLBACKGroups changes and ends them

The split is conventional: SELECT is sometimes counted as DML, and TRUNCATE is often called DDL although it removes data. Both variants occur, so in an interview it is best to name the group and explain what it does.

What each group changes

DQL: SELECTreads, changes nothingDML: INSERT UPDATE DELETEchanges rows, rollback until COMMITDDL: CREATE ALTER DROPchanges structure, lockingDCL: GRANT REVOKEchanges who can do whatTCL: BEGIN COMMIT ROLLBACKcontrols the change boundaries
Figure 1. Changes to structure or permissions have a larger impact on everyone using the database.

Example: from "just an UPDATE" to a safe change. Preparing test data: one account balance must be zeroed. Autocommit is on by default in most clients, so each command is committed at once:

UPDATE accounts SET balance = 0;
-- UPDATE 3: without WHERE every row changed, no way back

The forgotten WHERE changed every row, and nothing can be rolled back because the command has finished. The safer order is: open a transaction, change, check the number of rows affected and the result, and only then commit:

BEGIN;
UPDATE accounts SET balance = 0 WHERE id = 10;
-- UPDATE 1: one row, as expected
SELECT id, balance FROM accounts WHERE id = 10;
ROLLBACK;   -- or COMMIT when the result is right

Changing data on a shared environment

Risk

UPDATE without BEGIN

Autocommit: the change is committed at once. If the condition is wrong, the fix means restoring from a backup.

Safer

BEGIN, UPDATE, check, COMMIT

The "UPDATE 1" counter and a query after the change show what was touched. ROLLBACK removes the mistake.

Figure 2. Before running DML on a shared environment, check the condition with SELECT and run the change inside a transaction.

Limits and dialects. Rolling back DDL depends on the DBMS. In PostgreSQL ALTER, CREATE and DROP can be rolled back inside a transaction:

BEGIN;
ALTER TABLE accounts ADD COLUMN note text;
ROLLBACK;
-- PostgreSQL: no note column, the DDL rolled back too

In MySQL and Oracle DDL ends the current transaction implicitly (implicit commit), so a rollback after it is impossible. TRUNCATE in PostgreSQL is transactional too, but it takes a strong table lock and does not fire row triggers; in MySQL it is DDL with an implicit commit. Permissions (DCL) help QA: for checks it is convenient to have a separate account with SELECT only, then an accidental change is impossible. QA rarely writes GRANT and REVOKE, but understands why "permission denied" on an environment is not a bug.

Common mistakes.

  • Running UPDATE or DELETE without WHERE and without a transaction.
  • Assuming DDL can always be rolled back: in MySQL and Oracle it cannot.
  • Mixing up DELETE and TRUNCATE: different locking, rollback, counters and triggers.
  • Working on an environment under an account with full rights although reading is enough for checks.
  • Forgetting to check the affected-row counter: "UPDATE 3" where one was expected.

Check yourself

How does DML differ from DDL and why does it matter when choosing actions on a shared environment?

Answer

DML changes rows (INSERT, UPDATE, DELETE) and can be rolled back until COMMIT. DDL changes structure (ALTER, DROP) and may lock a table, and in some DBMS it cannot be rolled back. So DDL on a shared environment is run only by agreement.

After an UPDATE the client shows "UPDATE 3" instead of the expected "UPDATE 1". What to do if the transaction is not finished yet?

Answer

Run ROLLBACK, check the WHERE condition with a SELECT and repeat the change. The affected-row counter is the first signal that the condition is wrong.

In an interview. Junior: Commands are divided into groups: SELECT for reading, INSERT, UPDATE and DELETE for changing data, CREATE, ALTER and DROP for structure, GRANT and REVOKE for permissions, BEGIN, COMMIT and ROLLBACK for transactions. I write SELECT most often and make data changes inside a transaction. Middle/Senior: The group hints at risk. DML rolls back until COMMIT, DDL can lock a table and does not roll back in MySQL and Oracle, while in PostgreSQL it does. On a shared environment I first check the condition with SELECT, look at the affected-row counter and, where possible, work under a read-only account.

Why does QA need to know SQL?

QA needs SQL to check the system state deeper than the interface: the UI may show success while the database holds a wrong amount or status. SQL helps verify the result of an action, prepare test data, locate a bug and find integrity violations. Checks on a shared environment use a read-only account, data is changed only in a transaction with a condition, and real personal data is never used.

SQL · Basics

The UI says "Transfer successful". How do you make sure the money really changed the accounts?

A test transfers 100 from account 10 to account 11. The UI shows "Transfer successful", the green tick is in place. But the message only says that the client received a response without an error. Whether the balances changed, whether a history record appeared, whether the fee went off is visible only in the data. So a QA engineer who can write SQL checks the system deeper than the interface. This lesson is about where exactly SQL is useful and where its limits are.

How it works and why. A system consists of layers: the interface shows, the API responds, the database stores. Each layer can tell something that another does not know: the UI may be optimistic and show success before the server answers, the API may return 200 on a partial failure, the database is the source of truth about the state. A bug that lives only in the data is never visible from "above".

Where to look for the truth

UI: "Transfer successful"what the user sawAPI: status and response bodywhat the server answeredDatabase: balances, history, statuseswhat was really storedSide effects: logs, queuesemails, events, audit
Figure 1. The deeper the layer, the closer to the actual state. SQL gives access to the database layer.

What SQL gives a tester.

  • Checking the result: after an action in the UI or the API the amount, status, fee and history record are right.
  • Test data: find a user in the needed state or create one without going through ten UI steps.
  • Diagnostics: is the bug in the frontend, in the API or in the data? A database query often answers in a minute.
  • Integrity: duplicates, orphan records, impossible states.
  • Automated tests: preparing and cleaning data, checks after actions.

Example: from a "green" UI to a found defect. First the test checks only the message:

// before: only what the UI showed is checked
await page.getByRole('button', { name: 'Transfer' }).click();
await expect(page.getByRole('status')).toHaveText('Transfer successful');

Such a test is green even when no money moved. We add a database check after the action:

SELECT id, balance FROM accounts WHERE id IN (10, 11);
-- illustration: 10 → 500.00 (was 500), 11 → 0.00

SELECT id, from_account, to_account, amount, status
FROM transactions
WHERE from_account = 10
ORDER BY created_at DESC
LIMIT 1;
-- illustration: one row with status PENDING

Here (the data is illustrative) the balance of account 10 did not change and the transaction stayed pending although the UI showed success. This is a defect: the customer was told about a success that did not happen. Without the query this bug would go unnoticed. The UI showed what it was told, so the cause must be sought deeper, in the API or in the data.

What to check after a transfer

Not enough

Only the UI message

It shows that the client got no error. It does not prove the balances and history are right.

Enough

UI + API response + database state

Balances of both accounts, one history record with a status, the expected fee, nothing extra.

Figure 2. The same scenario is checked on several layers, and a mismatch between layers points to the place of the defect.

Limits and alternatives. SQL does not replace UI and API tests: it checks state, not what the user sees. Database access is often restricted: on a shared environment a separate read-only account is made, there is no access to production, and real user data (personal data) is not copied into a test environment. If the database is not visible, state is checked through the API, and the application's ORM logic is tested through the application rather than around it. Database replicas can lag by fractions of a second, so a check right after an action may see the old state: in an automated test it is retried with a timeout instead of a pause. And the main rule: changes on a shared database only with a transaction and a condition, while reading is free.

Common mistakes.

  • Treating the green tick in the UI as proof that data was saved correctly.
  • Writing a data change on a shared environment without WHERE and without a transaction.
  • Checking only one layer: the bug stays where nobody looked.
  • Copying real user data into a test database.
  • Checking the database right after an action without retrying: the replica or queue has not caught up.

Check yourself

The UI shows "Saved" but the database has no record. Where to look for the cause and what kind of defect is it?

Answer

First check the API response (status and body), then the write path. If the API returned success without a write, the defect is in the backend; if there was an error and the UI ignored it, it is in the frontend. The API response separates the one from the other, and the database query confirms the record is really missing.

Why should real production user data not be copied into a test database for checks?

Answer

It is personal data: its protection is regulated by law and company policy. For checks, synthetic data or anonymised copies are created, and queries are not run on production.

In an interview. Junior: SQL lets me verify the truth outside the interface. The UI may show "success" while the database holds the wrong amount or status. I also use SQL to quickly find or prepare test data and to localise a bug: frontend, backend or data. Middle/Senior: I check several layers: the UI, the API response and the database state. A mismatch between layers shows where the defect is. I look for integrity violations (duplicates, orphan records). I work carefully: a read-only account, changes only in a transaction with a condition, no real personal data, and I retry the post-action state check with a timeout.

Relationships between tables and normalization

Tables link through keys: one-to-many is a foreign key in the child table, one-to-one an FK with UNIQUE. Many-to-many goes through a join table. Normalization stores every fact once: 1NF has no lists in a cell, 2NF no dependence on part of a key, 3NF no dependence of non-key columns on each other. This removes update, insert and delete anomalies.

SQL · Basics

A test created an order and the database holds two spellings of one customer. Why did the schema allow it?

The orders table holds the customer name and email in every row. Someone fixed the email in one order, while two others kept the old one: now the system has "two Ivans". This is not a test error but a consequence of a schema where the same fact is written several times. This lesson is about how tables are linked and how normalization prevents such drift.

How it works and why. A relational database keeps each entity in its own table and expresses relationships with keys. There are three kinds:

RelationshipExampleHow it is stored
One-to-manyuser → ordersFK in the child table
One-to-oneuser → profileFK + UNIQUE
Many-to-manystudents ↔ coursesa join table

Many-to-many cannot be written directly: it is split into two one-to-many relationships through a join table with one foreign key per side.

Many-to-many through a join table

studentsid (PK)enrollments2 foreign keyscoursesid (PK)11NN
Figure 1. A student has many rows in enrollments, so does a course; each row points to one student and one course.
CREATE TABLE enrollments (
  student_id int NOT NULL REFERENCES students (id),
  course_id  int NOT NULL REFERENCES courses (id),
  PRIMARY KEY (student_id, course_id)
);

The composite primary key also forbids enrolling a student in the same course twice.

Normalization is the set of rules for splitting data across tables so that each fact is stored once. The first three normal forms:

  • 1NF: one value per cell, no lists ("10, 11, 12") and no repeating column groups (phone1, phone2).
  • 2NF: every non-key column depends on the whole composite key, not on part of it.
  • 3NF: non-key columns depend only on the key, not on each other (city, country and country code in one row).

Example: before and after. First a denormalized table, then the split one:

-- before: the customer repeats in every order
CREATE TABLE orders (id int PRIMARY KEY, item text, customer_name text, customer_email text);

-- after: a fact about the customer in one place
CREATE TABLE customers (id int PRIMARY KEY, name text, email text UNIQUE);
CREATE TABLE orders (
  id int PRIMARY KEY,
  item text,
  customer_id int NOT NULL REFERENCES customers (id)
);

One table or two

Avoid

orders

id, item, customer_name, customer_email. The customer repeats in every order.

Better

orders + customers

orders: id, item, customer_id. customers: id, name, email. A fact about the customer lives in one place.

Figure 2. In the split schema an email is changed in one row, and orders cannot drift apart.

Now changing an email is one UPDATE in customers. Before normalization the same UPDATE had to hit every order of the customer, and one missed row produced an update anomaly. There are also insert anomalies (a customer cannot be added without an order) and delete anomalies (the customer vanishes with the last order).

Limits and alternatives. Normalization is not free: a report now needs a JOIN. For analytics and data warehouses tables are denormalized on purpose, while OLTP systems keep 3NF. Historical snapshots are an exception too: the price of an item at the moment of the order must stay in orders even if the catalog price changed. That is not duplication but a different fact.

Common mistakes.

  • Storing a comma-separated list of ids instead of a join table: the database cannot check that those ids exist, and the query 'who is enrolled in course 12' turns into string parsing.
  • Building one-to-one without UNIQUE: it is really one-to-many.
  • Forgetting the composite key in a join table, so a student enrols in a course twice.
  • Copying the same name and email into every test data row without noticing the schema allows it.

Check yourself

Why is one foreign key not enough for students ↔ courses?

Answer

One foreign key gives one-to-many: either a student has one course or a course has one student. Many-to-many needs a join table with foreign keys to both sides.

Does storing the price in an order row break normalization when the catalog has it too?

Answer

No: it is the price at the time of purchase, while the catalog holds the current one. They are different facts, and the historical value must stay in the order.

In an interview. Junior: Tables are linked by keys: one-to-many is a foreign key in the child table, many-to-many is a join table. Normalization stores each fact once so data does not drift apart. Middle/Senior: I know 1NF, 2NF and 3NF and the update, insert and delete anomalies they remove. I allow denormalization for reports deliberately, and I do not treat historical values (the price at purchase) as duplication. As QA I check relationship integrity and look for orphan or duplicated records.