UPI Study › Courses › Database Programming › Free lessons › Lesson 5.6 Free with a free account
Built-In SQL Functions: How and When to Use Them
Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.6 · lesson 31 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: Replacing Nulls with the NVL Function →← Ordering Results: Sorting Techniques in SQLNext lesson: Replacing Nulls with the NVL Function →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Using numeric, date, and text functions and checking how dialects differ.
- Apply CEILING, FLOOR, ROUND, and ABS according to a stated business rule
- Calculate date offsets and gaps, recognizing how DATEDIFF differs between MySQL and SQL Server
- Use UPPER, LOWER, and length functions to build labels without changing stored data
- Explain why wrapping an indexed column in a function can slow a WHERE filter
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,050 words). Read along, or search it.
Opening Question
Labels, Billed Weights, and Return Dates
Maya Rao at Lantern Books needs shipping labels, billed weights, and return dates. Leo could write separate application routines, but the database already provides useful tools. Which transformations belong in a query, and which details could change when the same-looking function runs on another database? A built-in function takes arguments and returns a value. Numeric, text, and date functions can shape a result, without rewriting the original facts.
Definition
Function Names, Arguments, and Nesting
Read round as the function name, followed by its arguments in parentheses. The weight is the first argument, and the requested decimal places are the second. An argument can be a literal, a column, or another expression. Use its return value in select, conditions, or sorting. Documentation square brackets mark optional syntax; you do not type those brackets. A vertical bar in a manual normally separates alternatives. Nesting puts one call inside another. The inner result supplies an input to the outer transformation; scalar functions produce a value per row. Aggregate functions instead summarize collections. Null-handling, aggregates, and trimming have their own detailed lessons; here we focus on numeric, date, and basic text transformations.
Numeric Functions
Billing Weights With CEILING and FLOOR
These illustrative parcels are billed per started kilogram. Ceiling moves upward to an integer, while floor moves downward; round gives a display value at chosen precision. The policy determines the function. Rounding to a nearby integer would undercharge some partial kilograms, even though the result looks tidy. Our SQLite build enables mathematical functions, including ceiling and floor. Their availability depends on build options, so test the actual runtime. Run the weight query. Rounding a displayed value is distinct from choosing the unit count used for billing. The parcels bill as three and eight kilograms. Seven point five is not already whole; ceiling increases it, while an exactly whole input would remain unchanged.
Negative Numbers
CEILING, FLOOR, and ABS on Negatives
Absolute value gives distance from zero, removing the sign. Ceiling and floor instead follow direction on the number line, even for negative inputs. Negative two is larger than negative three. Ceiling of negative two point five therefore moves to negative two; floor moves to negative three. Run the signed examples. Halfway rounding goes away from zero for these SQLite inputs, and for exact numeric arguments in MySQL and SQL Server. The results distinguish size, upward rounding, downward rounding, and nearest rounding. MySQL approximate-number rounding can differ, so avoid universal halfway claims across every numeric type.
Dialect Comparison
ROUND With Negative Precision
MySQL and SQL Server use negative rounding precision for tens or hundreds. SQLite treats negative precision like zero, so our local run cannot establish their behavior. SQL Server requires the digits argument to round, and can retain the input type's scale. Cast to an appropriate decimal type when the output type must change. Round at the business policy's final calculation point. Exact money needs an exact representation; SQLite's decimal declaration alone does not provide fixed-scale decimal arithmetic.
Date Arithmetic
Adding Days and Measuring Gaps
Date arithmetic can add a period or measure a gap. This fixed starting date matches our first order; the delivery date is illustrative. SQLite's date modifier adds seven days, and string format extracts a year. Subtracting Julian day values measures elapsed days for these date-only inputs. Run the deterministic examples. Fixed dates keep the teaching result reproducible, unlike a current-time expression whose output changes as the clock advances. The return date is September eighth, and the elapsed gap is three days. Keep source dates and derive durations, avoiding redundant stored facts.
Dialect Comparison
DATEDIFF Differs Between MySQL and SQL Server
These non-run call fragments compare the dialects. MySQL uses now or current date for the clock, and date add or date subtract for offsets. SQL Server uses get date and date add, with a named unit and signed amount. Both provide year, month, and day extraction, but formatting names differ. Notice the gap arguments. MySQL date diff places the later date first; SQL Server names the unit, then takes the start and end dates. SQL Server date diff counts unit boundaries. Crossing New Year's midnight crosses a year boundary, even though a complete year has not elapsed. MySQL timestamp diff counts complete units instead. Check the function's meaning along with its name; neither result should be mistaken for the other's measurement.
Text Functions
Case Conversion and Length Counting
For text functions, return to our canonical customer names. We will transform their presentation without updating their stored spelling. Upper and lower change letter case. This SQLite build handles ordinary ASCII case conversion, so broader linguistic handling requires an appropriate implementation. Length needs special attention. MySQL length counts bytes, character length counts characters, and SQL Server len omits trailing spaces.
Worked Example
Building Name Labels With UPPER and LOWER
Lower and upper transform the names, then pipes join them with a space. The nested length call counts the result of upper. SQLite uses double pipes here. MySQL and SQL Server offer concat, but their null behavior differs; supply replacements only when their meaning is justified. Run the labels with their name lengths. These character counts match the visible letters. The labels change case in the result, while the stored customer records retain their original values. Use clear output aliases.
Performance
Functions in WHERE and Index Use
Functions in select are useful for presentation. In where, wrapping an indexed column can prevent an ordinary index seek; a half-open date range often preserves that opportunity. That is a planning guideline, not a claim that every optimizer evaluates every function on every row. Expression indexes and optimizer rewrites can change the access strategy. Check what a function returns, how it treats null, and the types or argument order in the target system. Familiar names are a starting point for verification.
Quick Check
Ceiling and Floor of Negative 4.2
A new signed measurement is negative four point two. The query asks for its ceiling and floor, in that order. Which pair will it return? Pause, and decide.
Answer
Minus Four and Minus Five
The answer is minus four, minus five. Ceiling chooses the larger bounding integer, and floor chooses the smaller one. Reversing those values swaps their directions. Returning minus four twice confuses floor with truncation toward zero, which is a different operation. The real run confirms the direction rule for a value we have not used before. Negative inputs make the distinction especially clear.
Key Takeaways
A Function's Spelling Is Not Its Contract
Maya's report can now derive weights, dates, and labels from recorded facts. Each function serves a specific reporting or calculation rule. Read arguments and return types, nest transformations carefully, and check null behavior. Prefer source facts over redundant stored derivations. Choose precision and date semantics deliberately, then verify the target dialect. A function's spelling alone cannot tell you its complete contract.
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 Built-In SQL Functions: How and When to Use Them
What is the difference between CEILING, FLOOR, and ROUND in SQL?
How does DATEDIFF work in MySQL compared with SQL Server?
How do you add days to a date in SQL?
What is the difference between LENGTH and CHAR_LENGTH in MySQL?
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 →