Built-In SQL Functions: How and When to Use Them, Explained

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

← 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 →

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

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.

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 Built-In SQL Functions: How and When to Use Them

What is the difference between CEILING, FLOOR, and ROUND in SQL?
CEILING returns the smallest integer greater than or equal to a value, FLOOR returns the largest integer less than or equal to it, and ROUND returns the nearest value at a chosen precision. So 7.5 has a ceiling of 8 and a floor of 7. On negatives, CEILING(-4.2) is -4 and FLOOR(-4.2) is -5. CEILING suits rules such as billing every started kilogram.
How does DATEDIFF work in MySQL compared with SQL Server?
MySQL DATEDIFF(end_date, start_date) returns whole days by subtracting the second date from the first, so the later date goes first for a positive result. SQL Server DATEDIFF(unit, start, end) takes a unit and counts boundaries crossed, so DATEDIFF(year, '2025-12-31', '2026-01-01') returns 1 after a single day. MySQL's TIMESTAMPDIFF(unit, start, end) counts complete units instead. Check argument order when moving code between systems.
How do you add days to a date in SQL?
Each system has its own date-addition syntax. MySQL uses DATE_ADD('2026-09-01', INTERVAL 7 DAY), SQL Server uses DATEADD(day, 7, '2026-09-01'), and SQLite uses date('2026-09-01', '+7 days'), and all three give September 8, 2026. A negative amount moves backward, and MySQL also offers DATE_SUB. Fixed dates keep results repeatable, while NOW() or GETDATE() makes them depend on the current time.
What is the difference between LENGTH and CHAR_LENGTH in MySQL?
In MySQL, LENGTH returns a string's size in bytes, while CHAR_LENGTH returns its number of characters. The two agree for plain ASCII text but differ for multibyte characters: in UTF-8 text, LENGTH('café') returns 5 and CHAR_LENGTH('café') returns 4, because é takes two bytes. SQL Server uses LEN for a character count that ignores trailing spaces and DATALENGTH for bytes, while SQLite's length counts characters in text values.

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 →