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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Floating-Point Data Types: REAL, FLOAT, and DOUBLE →← 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 →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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)?
Are DECIMAL and NUMERIC the same in MySQL and SQL Server?
How do you choose precision and scale for a DECIMAL column?
Why can rounding each line item give a different total than rounding the whole order?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
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
3 credits · NCCRSEnroll →