Precision Number Types: DECIMAL and NUMERIC, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 4.1 Free with a free account

Precision Number Types: DECIMAL and NUMERIC

Database Programming · Chapter 4: SQL Data Types in DepthSection 4.1 · lesson 20 of 769 min · free with a free account

← Whole Number Data Types: INT and SMALLINTNext lesson: Floating-Point Data Types: REAL, FLOAT, and DOUBLE →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

How precision and scale make DECIMAL and NUMERIC store exact values.

  • Calculate the whole-number and fractional capacity of a DECIMAL column from its precision and scale
  • Compare DECIMAL defaults, limits, and storage sizes in MySQL and SQL Server
  • Explain how multiplication, rounding, and overflow affect exact decimal results
  • Choose and document a rounding policy for invoice totals

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,105 words). Read along, or search it.

Opening Question

SQLite Accepts DECIMAL Without Fixed Precision

Maya Rao, the owner of Lantern Books, expects a price column to keep exactly two decimal places. This disposable SQLite example declares decimal five, two. Does that declaration actually enforce her expectation? Run the file through the SQLite shell, with headers and aligned columns enabled. The result keeps more than two decimal places, and the stored value has the real storage class. SQLite accepts the declaration, but does not implement fixed precision decimal storage through that name. That distinction matters throughout this lesson: we will separate decimal design from what this local engine enforces.

Definition

Precision, Scale, and Digit Slots

An exact number type represents its supported values without a binary approximation. Integers are exact, but have no fractional places. In MySQL and SQL Server, decimal and numeric provide exact decimal values. Those two names are interchangeable here. Precision means the total number of decimal digits. Scale means the number of those digits after the point. Subtract scale from precision, to find the room before the point. The sign and decimal point consume no digit slots. For decimal seven, two, five digits remain before the point. The greatest positive value is ninety-nine thousand, nine hundred ninety-nine point nine nine. Our design reserves cents for prices, four decimal places for rates, and three for kilograms measured to the gram. These are non-run dialect definitions. Choosing scale records required detail; choosing precision provides enough range for growth.

Defaults and Limits

Defaults Are Risky for Money Columns

Defaults are dangerous when the column represents money. Omitting the scale gives zero fractional places in both systems. MySQL defaults a bare decimal declaration to precision ten. SQL Server defaults it to precision eighteen. MySQL supports at most sixty-five digits, with scale at most thirty. SQL Server supports thirty-eight digits, with scale no larger than precision. Write both arguments, even when the defaults happen to fit. That makes the intended range and detail reviewable. A scale equal to precision leaves no whole-number capacity. Decimal three, three can hold fractions below one, but cannot hold one. A zero scale is useful for exact whole amounts within its range. Codes with meaningful leading zeros belong in text instead.

Worked Example

Storing Prices as Integer Cents

Back to Maya's price. Database Basics costs twenty-five dollars in our shared shop data; this copy represents it as twenty-five hundred cents. For this SQLite demonstration, bounded integer cents keep additions and whole-number multiplications exact. The check disallows negative prices. Run the query for three copies. The stored unit is cents, so the result must be interpreted in that unit. The subtotal is seventy-five hundred cents, or seventy-five dollars. No floating-point price enters this calculation. Integer cents are one SQLite strategy, not a replacement for every decimal calculation. Rates and fractional cents still need deliberate treatment. Also check the integer range before multiplying. Exact representation never promises unlimited capacity, even with a sensible unit.

Arithmetic Rules

Result Scale in Tax Calculations

Exact decimals prevent binary approximation, but calculations can still produce more fractional places than a destination column allows. For addition and subtraction, the larger operand scale normally determines the fractional detail, subject to engine precision limits. Multiplication adds operand scales before those limits apply. A cents subtotal times a four-place rate produces six fractional places. Our illustrative tax is eight point two five percent. Seventy-five dollars times that rate gives six point one eight seven five dollars. Round the tax deliberately to cents, giving six dollars and nineteen cents. Keep the rounding policy visible in the query. Division has additional engine rules. MySQL normally adds four places to the first operand's scale; SQL Server uses its own formula. In SQL Server, round changes the value without necessarily changing its type scale. Cast to the target decimal type when that scale matters.

Rounding and Overflow

Half Away From Zero and Rounding Policy

What if an incoming value has too many fractional digits? The destination scale can force rounding during insertion. Half away from zero means a halfway value moves toward greater magnitude. Positive and negative values follow the same principle. For these exact decimal inputs, two point six seven five becomes two point six eight; its negative becomes negative two point six eight. Overflow is different: the rounded value needs more integer digits than the column permits. Even rounding can push a value over the boundary. MySQL strict mode rejects an out-of-range value; nonstrict settings can clamp it and issue a warning. SQL Server normally reports arithmetic overflow. SQL Server session options also affect overflow handling. Check the configured environment, and never treat a successful insert as proof that nothing changed. A separate question is where to round. Suppose three individual purchases each cost one dollar and ninety-nine cents. Apply the same illustrative tax rate, then compare rounding each line with rounding the combined basket. Run this small arithmetic illustration. SQLite uses approximate arithmetic here; the example demonstrates policy, not fixed decimal enforcement. The line method totals forty-eight cents, while the basket method produces forty-nine cents. Exact decimal arithmetic produces that same policy difference. Binary rounding error is not the explanation for this particular disagreement. Maya needs one documented rule for invoices, refunds, and reports, consistent with applicable requirements. Choosing a type cannot choose that rule.

Storage Cost

Bytes Used by Each Precision Tier

Precision also has a storage cost. SQL Server allocates five bytes for precisions through nine, then nine bytes through nineteen. The remaining tiers use thirteen and seventeen bytes. Crossing a boundary can increase storage for every value in the column. MySQL packs groups of nine decimal digits into four bytes, counting the integer and fractional portions separately. Remaining groups of one or two digits need one byte; three or four need two; five or six need three. Seven or eight remaining digits need four bytes. Decimal nineteen, four uses seven bytes before the point, plus two after it. Choose enough capacity and a justified growth margin. Oversizing is not free: four extra bytes across a hundred million values add four hundred million bytes.

Quick Check

Sizing a Column for Shipping Weights

A new shipping scale must record weights through eighty kilograms, to three decimal places. Which declaration supplies exactly enough digits for that requirement? Read the options, then pause and decide. The middle choice, decimal five, three, supplies two integer digits and three fractional digits. Run the digit count: five total digits are required. Decimal four, three cannot hold eighty; decimal six, two loses the required fractional detail. This is a capacity calculation, not a SQLite enforcement test. In MySQL or SQL Server, use that declaration in the real schema.

Key Takeaways

Exact Types Plus an Agreed Policy

Choose exact decimal types for prices and fixed-detail quantities, in engines that enforce their declared precision and scale. Budget range and fractional detail separately. Keep rates precise enough, and avoid mixing approximate values into exact money calculations. Round deliberately, check overflow behavior, and document the rounding point. Maya's reliable total needs both an appropriate representation and an agreed policy.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Precision Number Types: DECIMAL and NUMERIC

What do precision and scale mean in DECIMAL(p,s)?
Precision is the total number of decimal digits a DECIMAL column can store, and scale is how many of those digits come after the decimal point. Subtracting scale from precision gives the digits available before the point. For example, DECIMAL(7,2) allows five whole-number digits and two decimal places, so its largest positive value is 99999.99. The sign and the decimal point do not use any digit slots.
Are DECIMAL and NUMERIC the same in MySQL and SQL Server?
Yes, in MySQL and SQL Server, DECIMAL and NUMERIC are interchangeable names for exact fixed-point types that store decimal values without binary approximation. Their defaults differ by system: a bare DECIMAL means DECIMAL(10,0) in MySQL and DECIMAL(18,0) in SQL Server, so writing both arguments is safer. MySQL allows up to 65 digits with a scale of at most 30, while SQL Server allows up to 38 digits.
How do you choose precision and scale for a DECIMAL column?
Set the scale to the fractional detail the data requires, then add enough whole-number digits for the largest expected value plus a sensible growth margin. Weights up to 80 kilograms recorded to the gram need DECIMAL(5,3), giving two integer digits and three decimal places. DECIMAL(4,3) cannot hold 80, and DECIMAL(6,2) loses the third decimal place. Oversizing also costs storage, because larger precisions can use more bytes per value.
Why can rounding each line item give a different total than rounding the whole order?
Rounding each line and rounding the combined total apply the rounding step at different points, so the totals can differ even with exact decimal arithmetic. Three items at $1.99 with 8.25% tax give 16 cents of tax per line, or 48 cents in total, while taxing the $5.97 basket gives 49 cents. Binary error is not the cause. Choose one documented rule and apply it consistently to invoices, refunds, and reports.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →