Course outline

MariaDB / Intermediate: concurrency and reusable SQL / Lesson 14

Generated columns for same-row calculations

Derive a synthetic line total and inspect the schema while planning version and storage behavior.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Explain PERSISTENT and VIRTUAL generated values.
  • Update inputs rather than directly assigning the derived value.
  • Test precision, version compatibility, and migration behavior.
  • Explain how generated totals follow their source values and distinguish virtual from persistent storage.
  • Validate decimal range, missing inputs and historical pricing requirements.

Define the calculation

A shipment line can derive an extended amount from quantity and unit price on the same row. A generated column centralizes that expression in the table definition so writers do not supply a separate total. The lab uses a small decimal example; real money requires a currency, rounding rules, valid ranges, overflow handling, and a policy for discounts and tax. Those business rules are not provided by multiplication alone.

Create a persistent calculation

The following illustrative SQL is for a new disposable MariaDB InnoDB lab. The PERSISTENT generated column stores the calculated result, while the application supplies the ordinary input columns. MariaDB also supports VIRTUAL generated columns, calculated dynamically when queried. Check the target server version, engine, expression restrictions, and SQL mode before using a generated column in an actual migration.

sql Create a generated line total
CREATE TABLE lab_line (
 id INT PRIMARY KEY, quantity INT NOT NULL, unit_price DECIMAL(8,2) NOT NULL,
 line_total DECIMAL(12,2) AS (quantity * unit_price) PERSISTENT
) ENGINE=InnoDB;
INSERT INTO lab_line (id, quantity, unit_price) VALUES (1, 3, 2.50);
SELECT id, quantity, unit_price, line_total FROM lab_line WHERE id = 1;

Three units at 2.50 give a line total of 7.50 under the declared fixture. The example is non-runnable in the public course and does not assert live server output.

Change an input and inspect the definition

Modify the quantity rather than manually writing the generated total, then inspect the row and table definition. A change to the source value changes the derived value according to the expression. The example operates only on the synthetic row; a real update needs a scoped predicate, transaction policy, and application authorization.

sql Update quantity and inspect
UPDATE lab_line SET quantity = 4 WHERE id = 1;
SELECT id, quantity, unit_price, line_total FROM lab_line WHERE id = 1;
SHOW CREATE TABLE lab_line;

With the fixture, quantity four and unit price 2.50 imply a total of 10.00. SHOW CREATE TABLE output depends on the server and SQL mode and is not reproduced here.

Consider storage and indexing

PERSISTENT values occupy storage, whereas VIRTUAL values are computed when queried. Generated columns can be indexed under the documented engine and version rules, but an index adds write and storage cost. Do not assume an optimizer recognizes every equivalent expression or that MariaDB and MySQL have identical behavior. Measure representative queries and writes on the exact target version.

Test the migration boundary

Before rollout, test boundary inputs, decimal precision, nullability, existing data, and both application versions on an isolated copy. Inspect the actual generated definition and compare representative totals with hand calculations. Document backup, expected locks, and a recovery path for the chosen ALTER procedure. A correct sample multiplication does not establish that every historical row or monetary rule is represented correctly.

Define the line-total contract

A line total is a derived value, so begin with the meaning and units of its inputs. In this lesson quantity is a nonnegative count, unit_price is an exact decimal price per item, and the illustrated expression is quantity * unit_price. Three items at 2.50 yield 7.50; changing the quantity to four yields 10.00. This is a pre-tax line amount under the stated rule, not a complete invoice or a statement about how every business rounds. A generated column centralizes that expression in the table definition so a writer does not have to supply a second, potentially inconsistent amount.

State the allowed range of both inputs and the currency scale before choosing types. A return, discount, fractional quantity or multi-currency transaction needs an explicit extension of the rule rather than an accidental negative or an implicit conversion. The generated value is only as trustworthy as its inputs. Constraints, validation and a documented unit convention address different failure modes from the expression itself. The examples use synthetic fixtures and reasoned results, not an executed server.

Choose precision for intermediate and stored values

DECIMAL is useful for the illustrated exact monetary inputs because decimal amounts such as 2.50 can be represented without binary floating-point approximation. The generated column has its own declared precision and scale; the multiplication must fit its range after any conversion or rounding required by the schema and server mode. For a DECIMAL(10,2) result there are eight integer digits and two fractional digits. Derive the maximum expected quantity times price and leave appropriate headroom rather than selecting a type solely from typical small orders.

Test zero, the highest accepted value, and a product just beyond the intended range on the exact server configuration. SQL mode and MariaDB version can affect whether an invalid or out-of-range write is rejected, warned about or converted; do not promise a particular outcome without testing the deployment. State where rounding occurs and use the approved decimal policy. Rounding each line and rounding an invoice aggregate can give different answers, so reconcile against the accounting contract rather than assuming equivalence.

Distinguish virtual and persistent columns

MariaDB supports VIRTUAL generated columns computed when read and PERSISTENT, also called STORED, generated columns whose values are stored. Both express a dependency on the underlying input columns; changing a valid quantity or price changes the derived result under the declared expression. Storage, read cost, write cost, supported indexing and migration behavior depend on the table engine, expression and MariaDB release. Select the form based on the workload and operational requirements rather than assuming either is always faster.

A generated column is not an independent field that application code should maintain with its own value. Insert or update the source fields and let the server derive the result according to the supported syntax. Inspect the exact schema and test any import, index or schema change on a disposable instance before relying on a specific behavior. Indexes add maintenance cost, and a generated-column index does not make an unsuitable predicate or inconsistent business rule correct.

Account for missing inputs and validation

SQL arithmetic with NULL generally produces NULL, so a missing unit price yields an unknown line total rather than zero. Decide whether the application allows a draft line without a price; if it does, expose the missing state clearly. If the business requires a price at insertion, use appropriate NOT NULL and domain checks alongside application validation. Substituting zero with COALESCE changes the meaning from unknown to free and should be an explicit policy, not an invisible convenience.

Similarly, zero quantity and zero price are known values that produce zero under multiplication; they are not interchangeable with missing values. Negative values may represent a correction in one system and invalid input in another. Define that distinction before imposing a CHECK or accepting a return. Verify whether the intended constraint is enforced by the exact MariaDB release and storage engine, and test failure cases in an isolated lab rather than relying on DDL text alone.

Preserve pricing history and verify

A stored generated value is derived from the currently stored source fields; it does not automatically preserve an earlier price, tax rule or rounding decision. For historical invoices, store the agreed unit price on the line and keep the appropriate rule and effective-time evidence. Referencing a current product price at report time would change historical totals when the catalog changes. If the business requires tax, define its rate, scope and rounding explicitly rather than assuming multiplication includes it.

Reconcile sample line totals against independent calculations and invoice sums, including missing values, returns and boundary amounts. Check the actual schema, SQL mode and engine on the intended version before promoting a change. Plan a migration and rollback or recovery strategy for an existing table; adding a generated field or index can require expensive work and locking. All blocks in the lesson are illustrative and non-runnable because no isolated MariaDB server has been qualified.

20 worked examples

1. Virtual line amount

Problem: What amount follows from three items at 2.50?

  1. The inserted quantity and exact decimal price are three and 2.50.
  2. The virtual expression multiplies those values when selected.
sql Illustrative MariaDB SQL
CREATE TABLE lab_line (qty INT, price DECIMAL(8,2), total DECIMAL(10,2) AS (qty * price) VIRTUAL);
INSERT INTO lab_line (qty, price) VALUES (3, 2.50);
SELECT total FROM lab_line;
Expected output
7.50

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The value follows the declared line formula without an independently supplied total.

2. Change quantity

Problem: What happens when the quantity changes from three to four?

  1. The source quantity becomes four while price stays 2.50.
  2. The generated expression uses the updated source values.
sql Illustrative MariaDB SQL
-- Fixture: qty=3, price=2.50; total is generated as qty * price.
UPDATE lab_line SET qty=4;
SELECT total FROM lab_line;
Expected output
10.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The total follows the new inputs instead of requiring a separate application update.

3. Change price

Problem: What amount results when the unit price changes?

  1. The stored quantity remains three and the price becomes 3.25.
  2. Multiplying the two current inputs yields 9.75.
sql Illustrative MariaDB SQL
-- Fixture: qty=3, price=2.50; generated total=qty * price.
UPDATE lab_line SET price=3.25;
SELECT total FROM lab_line;
Expected output
9.75

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A generated amount reflects the current line inputs, so historical pricing must be preserved deliberately.

4. Persistent amount

Problem: How does a stored generated amount represent the same calculation?

  1. The declared expression is the same multiplication as in the virtual case.
  2. PERSISTENT stores the generated value in the table.
sql Illustrative MariaDB SQL
CREATE TABLE lab_stored_line (qty INT, price DECIMAL(8,2), total DECIMAL(10,2) AS (qty * price) PERSISTENT);
INSERT INTO lab_stored_line (qty, price) VALUES (3, 2.50);
SELECT total FROM lab_stored_line;
Expected output
7.50

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: Storage mode changes where the value is kept, not this stated arithmetic result.

5. Zero quantity

Problem: What does a known zero quantity produce?

  1. Zero is a known count rather than a missing input.
  2. Multiplication by zero yields a zero amount.
sql Illustrative MariaDB SQL
SELECT 0 * CAST(2.50 AS DECIMAL(8,2)) AS total;
Expected output
0.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A zero result follows the arithmetic even if a separate domain policy disallows zero quantity.

6. Free item

Problem: What amount results from two items priced at zero?

  1. Both the quantity and the zero price are known.
  2. The multiplication therefore produces zero.
sql Illustrative MariaDB SQL
SELECT 2 * CAST(0.00 AS DECIMAL(8,2)) AS total;
Expected output
0.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A free item differs from a line whose price has not yet been supplied.

7. Missing price

Problem: What total follows from an unknown unit price?

  1. The quantity is known but the price is NULL.
  2. Arithmetic with the unknown price produces NULL.
sql Illustrative MariaDB SQL
SELECT 3 * CAST(NULL AS DECIMAL(8,2)) AS total;
Expected output
NULL

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A missing price cannot be treated as a zero-price item without an explicit substitution rule.

8. Missing quantity

Problem: What total follows from an unknown quantity?

  1. The price is known but the quantity is missing.
  2. The product cannot be determined from these inputs.
sql Illustrative MariaDB SQL
SELECT NULL * CAST(2.50 AS DECIMAL(8,2)) AS total;
Expected output
NULL

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: NULL propagates through the arithmetic rather than fabricating a quantity.

9. Substitution changes meaning

Problem: What does replacing a missing price with zero do?

  1. COALESCE substitutes zero for the missing price.
  2. Three times that substituted zero produces zero.
sql Illustrative MariaDB SQL
SELECT 3 * COALESCE(CAST(NULL AS DECIMAL(8,2)), 0) AS total;
Expected output
0.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The computation now treats an unknown price as free, so the policy must explicitly permit it.

10. Two lines

Problem: What invoice subtotal follows from two synthetic line amounts?

  1. The two line amounts are 7.50 and 4.00.
  2. Their sum is 11.50 before any tax or discount.
sql Illustrative MariaDB SQL
SELECT SUM(amount) AS subtotal FROM (SELECT CAST(7.50 AS DECIMAL(10,2)) AS amount UNION ALL SELECT 4.00) AS lines;
Expected output
11.50

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: Aggregation of line amounts is a separate step from generating each line amount.

11. SUM and missing lines

Problem: Why can a subtotal hide an unpriced line?

  1. SUM and COUNT(amount) ignore the NULL amount.
  2. COUNT(*) still includes both input rows.
sql Illustrative MariaDB SQL
SELECT SUM(amount) AS subtotal, COUNT(*) AS lines, COUNT(amount) AS priced FROM (SELECT CAST(7.50 AS DECIMAL(10,2)) AS amount UNION ALL SELECT NULL) AS x;
Expected output
7.50 | 2 | 1

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: Comparing line count with priced count reveals that the subtotal omits one unknown amount.

12. Tax is separate

Problem: Does multiplication by quantity include a ten percent tax?

  1. The expression multiplies only quantity and unit price.
  2. No tax rate or tax rule appears in the expression.
sql Illustrative MariaDB SQL
SELECT 3 * CAST(2.50 AS DECIMAL(8,2)) AS line_before_tax;
Expected output
7.50

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The generated total is pre-tax under the stated contract, regardless of later tax calculation.

13. Discount is separate

Problem: Does a 2.00 discount automatically affect the generated formula?

  1. The generated formula uses quantity and price only.
  2. The separate discount is absent from the multiplication.
sql Illustrative MariaDB SQL
-- qty=3, price=2.50, separate discount=2.00.
SELECT 3 * CAST(2.50 AS DECIMAL(8,2)) AS gross;
Expected output
7.50

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A discount requires its own explicit calculation and rounding contract.

14. Maximum declared result

Problem: What is the largest positive value representable by DECIMAL(10,2)?

  1. Precision ten includes two fractional digits.
  2. Eight digits remain for the integer part.
sql Illustrative MariaDB SQL
-- DECIMAL(10,2) has 8 integer digits and 2 fractional digits.
SELECT CAST(99999999.99 AS DECIMAL(10,2)) AS max_positive;
Expected output
99999999.99

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The declared result type bounds the product even when each input individually fits.

15. Product exceeds type

Problem: What should be investigated for a product of 100000000.00?

  1. The mathematical product has nine integer digits.
  2. DECIMAL(10,2) provides only eight integer digits.
sql Illustrative MariaDB SQL
-- qty=1000000, unit price=100.00; generated result type DECIMAL(10,2).
SELECT 1000000 * CAST(100.00 AS DECIMAL(8,2)) AS product;
Expected output
100000000.00 exceeds DECIMAL(10,2) maximum 99999999.99.

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: Range and actual SQL mode must be tested before relying on the attempted stored result.

16. Per-line rounding

Problem: How can rounding each line differ from rounding the aggregate?

  1. Each exact positive 0.005 rounds to 0.01 at two places.
  2. Their unrounded sum is 0.010, which rounds to 0.01.
sql Illustrative MariaDB SQL
SELECT ROUND(0.005,2) + ROUND(0.005,2) AS line_rounded, ROUND(0.005 + 0.005,2) AS sum_rounded;
Expected output
0.02 | 0.01

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: The location of rounding is a business rule and can change invoice totals.

17. Historical price

Problem: What happens if the stored line price is overwritten?

  1. The expression uses the current stored price of 4.00.
  2. Three times four produces 12.00 rather than the original 7.50.
sql Illustrative MariaDB SQL
-- Historical line: qty=3, stored price=2.50; generated total=7.50.
-- A later update sets the line price to 4.00.
SELECT 3 * CAST(4.00 AS DECIMAL(8,2)) AS revised_total;
Expected output
12.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A generated column does not by itself preserve an earlier pricing decision.

18. Negative quantity policy

Problem: What is the mathematical result for a negative quantity?

  1. Negative two multiplied by positive three is negative six.
  2. The expression itself does not decide whether the line is an authorized return.
sql Illustrative MariaDB SQL
SELECT -2 * CAST(3.00 AS DECIMAL(8,2)) AS amount;
Expected output
-6.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A separate business and validation policy must define whether negative quantities are accepted.

19. Derived versus supplied

Problem: Why omit the generated field from an ordinary insert?

  1. The insert supplies both input fields required by the formula.
  2. The server derives total from two times four.
sql Illustrative MariaDB SQL
CREATE TABLE lab_line2 (qty INT, price DECIMAL(8,2), total DECIMAL(10,2) AS (qty * price) VIRTUAL);
INSERT INTO lab_line2 (qty, price) VALUES (2, 4.00);
SELECT total FROM lab_line2;
Expected output
8.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: Naming source columns avoids maintaining an independent, potentially inconsistent total.

20. Explicit line identity

Problem: How can an update target one synthetic line?

  1. The predicate changes only line 1 in the stated fixture.
  2. Line 1 becomes four times 2.50 while line 2 remains two times 2.50.
sql Illustrative MariaDB SQL
-- Fixture: line_id 1 has qty=3; line_id 2 has qty=2; both have price=2.50.
UPDATE lab_lines SET qty=4 WHERE line_id=1;
SELECT line_id, total FROM lab_lines ORDER BY line_id;
Expected output
1 | 10.00; 2 | 5.00

Synthetic inputs and results are reasoned; this statement has not been run on a qualified MariaDB server.

Why this result follows: A specific key limits the source update and each generated total follows its own row.

Common errors and fixes

A generated total is assigned like an ordinary field.

Why it happens
The writer treats the derived column as independent input.
How to fix it
Write the supported source columns and let the expression derive the value.
Prevent it next time
Name writable fields explicitly in application statements.

A monetary total differs from the business expectation.

Why it happens
Precision or rounding rules were assumed rather than specified.
How to fix it
Define and test the required numeric contract.
Prevent it next time
Include boundary and fractional cases in acceptance tests.

A migration behaves differently on another server.

Why it happens
Engine, version, expression, or SQL mode differences were ignored.
How to fix it
Inspect the target definition and supported behavior.
Prevent it next time
Rehearse against the exact target configuration.

20 practice exercises

1. What is the fixture total before and after the update?

Show hint

Multiply each quantity by the unchanged unit price.

Show worked solution

Initially 3 Γ— 2.50 = 7.50. After the quantity becomes 4, the derived total is 4 Γ— 2.50 = 10.00.

Initially 3 times 2.50 gives 7.50. After the quantity changes to 4, the expression gives 10.00; the generated value follows the updated source field.

Check your solution

  • Initial amount is 7.50.
  • Updated amount is 10.00.

2. Does the generated total account for tax automatically?

Show hint

Identify every operation present in the expression.

Show worked solution

No. The expression only multiplies quantity and unit price. Tax and rounding require an explicit, tested business contract.

The generated expression multiplies quantity and unit price only. It does not contain a tax rate, tax scope or rounding policy; those require a separately specified and tested rule.

Check your solution

  • The multiplication does not include tax.
  • Specify and test tax and rounding separately.

3. Calculate totals for quantities 2 and 5 at unit price 1.25.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The first line is 2.50 and the second is 6.25, because each quantity is multiplied by the same exact unit price. These are line amounts before any separately defined tax or discount.

Check your solution

  • First total is 2.50
  • Second total is 6.25

4. A line changes from quantity 3 to 4 at price 2.50. Predict both generated totals.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The original total is 7.50 and the updated total is 10.00. A generated expression based on quantity and price reflects the changed source quantity; no separate total should be supplied.

Check your solution

  • Before is 7.50
  • After is 10.00

5. Price is NULL and quantity is 4. What is the line total and why?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The product is NULL because the price is unknown. Treating it as zero would be a separate policy that changes an unpriced line into a free line; display or reject missingness according to the contract.

Check your solution

  • Total is NULL
  • Do not silently equate missing and zero

6. A quantity is zero and its price is 8.00. Compare it with NULL quantity.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The known zero quantity yields 0.00, while a NULL quantity yields NULL. Decide separately whether either input is permitted; the arithmetic alone does not validate the business domain.

Check your solution

  • Zero quantity yields 0.00
  • NULL quantity yields NULL

7. Design a generated line expression for quantity and unit_price without tax.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Declare a generated decimal column based on quantity * unit_price with suitable precision and scale, and supply the input columns on insert. The expression excludes tax; validate domains and test the exact server mode.

Check your solution

  • Expression multiplies the inputs
  • Tax is outside the formula

8. A generated total is defined as quantity times price. Does it include a 10 percent tax?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

No. The expression contains no tax rate or tax rule. Define whether tax applies per line or invoice, its rate and rounding policy, then test the approved calculation separately.

Check your solution

  • Tax is not included
  • Define tax and rounding separately

9. Compare VIRTUAL and PERSISTENT for the same deterministic multiplication.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Both represent the same stated arithmetic dependency, but VIRTUAL is computed when queried and PERSISTENT stores the generated value. Evaluate storage, writes, reads and supported indexing on the actual MariaDB release and engine.

Check your solution

  • Same formula yields same stated amount
  • Storage behavior differs

10. A client supplies quantity, price and a manually calculated total. What inconsistency can arise?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

If application arithmetic differs from stored inputs, the supplied total can disagree with the line. A generated column derives it from the source fields, but input validation and a correct expression remain essential.

Check your solution

  • Avoid maintaining a separate total
  • Validate source inputs and expression

11. DECIMAL(10,2) holds a generated amount. How many integer digits are available?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Eight integer digits remain after reserving two fractional digits within the ten-digit precision. The maximum positive value is 99999999.99; calculate the product range before accepting the schema.

Check your solution

  • Eight integer digits
  • Maximum is 99999999.99

12. Quantity 1000000 and price 100.00 produce 100000000.00. Does DECIMAL(10,2) fit?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

No. The product needs nine integer digits but DECIMAL(10,2) permits eight. Choose a suitable type or constrain inputs, and test actual error and conversion behavior under the deployed SQL mode.

Check your solution

  • Product exceeds the maximum
  • Test mode and input range

13. Compare rounding 0.005 twice per line with rounding their sum to two places.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Rounding each exact positive amount yields 0.01 plus 0.01, or 0.02. Adding first yields 0.010 and rounding gives 0.01. The invoice contract must specify the rounding stage.

Check your solution

  • Per-line rounding gives 0.02
  • Aggregate rounding gives 0.01

14. A subtotal uses SUM on line amounts 7.50 and NULL. What hidden issue exists?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

SUM returns 7.50 because it ignores NULL, although one line is unpriced. Compare COUNT(*) with COUNT(amount) and apply a completeness policy before presenting the subtotal as final.

Check your solution

  • SUM is 7.50
  • One of two amounts is missing

15. A generated value uses a line price later overwritten from 2.50 to 4.00 for quantity 3. What changes?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The current generated result changes from 7.50 to 12.00. Preserve the agreed historical unit price and rule evidence if a past invoice must remain reproducible; storage mode alone does not create history.

Check your solution

  • Current result becomes 12.00
  • Preserve original price for historical reporting

16. A negative quantity represents a return in one system but invalid input in another. What is required?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Define the business semantics and allowed domain before writing a constraint. The multiplication produces a negative amount, but that arithmetic does not establish whether the input is an authorized return.

Check your solution

  • Specify return policy
  • Validate quantity domain

17. A generated total column is indexed for reports. What tradeoff should be measured?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The index may help a suitable predicate but consumes storage and requires maintenance on writes. Verify support for the expression, engine and MariaDB version, and compare representative plans and write cost in an isolated lab.

Check your solution

  • Check index support and query plan
  • Measure write and storage cost

18. A draft line may lack price. Should COALESCE(price,0) be added automatically?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

No: substituting zero makes an unknown price appear free. If the business explicitly chooses that behavior, preserve a missingness indicator and document the report semantics; otherwise retain NULL or reject the draft.

Check your solution

  • Unknown and free remain distinct
  • Substitution requires explicit policy

19. Two lines have quantity and price (3,2.50) and (2,4.00). Calculate their subtotal.

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

The first line is 7.50 and the second is 8.00, producing a subtotal of 15.50. Check separately whether tax, discounts or rounding adjustments belong in the final invoice.

Check your solution

  • Line totals are 7.50 and 8.00
  • Subtotal is 15.50

20. An UPDATE without WHERE changes quantity on every line. What should be reviewed?

Show hint

Follow the declared inputs through the formula and state any separate policy.

Show worked solution

Every row is targeted, and each generated value follows its changed inputs. Use the intended line key and verify affected scope in a disposable test; a generated column does not prevent an overbroad source update.

Check your solution

  • All rows are targeted
  • Use and verify the intended key

Key takeaways

  • Generated values derive from an expression rather than separate writer input.
  • PERSISTENT and VIRTUAL have different storage behavior.
  • Verify version, precision, and migration effects on representative data.
  • A generated amount is derived from its inputs and does not automatically include tax.
  • NULL inputs normally produce an unknown arithmetic result.
  • Choose precision and rounding from the documented business contract and test the actual server mode.

Official references