Trimming Text with SQL TRUNCATE String, Explained

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

Trimming Text with SQL TRUNCATE String

Database Programming · Chapter 7: Text Operations and Practical Data ManipulationSection 7.1 · lesson 40 of 769 min · free with a free account

← Transaction Control Language (TCL): Managing Data SafelyNext lesson: Clearing Tables with SQL TRUNCATE Table →

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

Extract, trim, pad and replace text, and truncate numbers safely.

  • Extract parts of a string with LEFT, RIGHT, SUBSTRING and SQLite's substr
  • Remove boundary spaces with TRIM, LTRIM and RTRIM while keeping internal spaces
  • Cut text before a marker such as @ with a guarded position search
  • Distinguish numeric truncation with TRUNCATE or ROUND from string cutting and column length limits

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,075 words). Read along, or search it.

Opening Problem

A Label That Fails an Exact Match

Sofia Alvarez, a sales associate at Lantern Books, imports a product label with extra spaces. Its visible words look right, but an exact match fails. She also needs the year from a product code. Should she cut characters, remove spaces, or truncate something? Those operations solve different problems. We will repair these fictional import values, while keeping the original meaning intact.

Extraction

LEFT, RIGHT and SUBSTRING Positions Start at One

Start with extraction. This listing shows MySQL and SQL Server syntax; it is not sent to our SQLite terminal. Left takes the first three characters, giving PRD. Right takes the final four, preserving the leading zeros in that text. Substring takes a start and a length. Start at position five, then take four characters: the year, 2024. Positions begin at one. Counting the dash matters; the fifth character is the first digit of the year. MySQL permits an omitted length. SQL Server requires length through 2022; 2025 and later allow omission. Giving it explicitly works across these versions.

SQLite Version

SQLite substr With a Negative Start

SQLite spells the operation substr. A negative start counts backward from the end, so minus four selects the suffix here. Run this self-contained file in an in-memory database. The result has the prefix, year, and suffix, exactly as intended. These are expressions inside select. They compute returned values; they do not rewrite a stored product code.

Space Cleanup

TRIM, LTRIM and RTRIM Clean Boundaries

Trimming solves Sofia's space problem. These SQLite queries use quote, so the boundary spaces remain visible inside quotation marks. Run them. LTRIM removes leading spaces; RTRIM removes trailing spaces. Trim removes spaces from both ends. The results keep the space between Blue and Notebook. Removing that space would change the label, rather than clean its boundaries. These one-argument forms remove ordinary spaces, not every possible invisible character. Tabs or other whitespace need deliberate handling. MySQL has these functions too. SQL Server supports trim from 2017; older versions can nest LTRIM around RTRIM.

Padding

LPAD Adds Zeros to a Target Width

Padding adds characters to a target width. MySQL's LPAD turns the text forty-two into five characters, by adding zeros at the left. The comments show documented expected values, not terminal output. Watch the overlength example: six digits are shortened to five. SQL Server can combine a zero prefix with a cast to text, then take the rightmost five characters. That expression also needs a width check. A value longer than the chosen width loses significant digits, rather than simply staying unchanged. Treat padding as a display rule. It must not quietly damage an order identifier.

Text Replacement

REPLACE Changes Every Matching Piece

Replace changes matching text wherever it occurs. An empty replacement removes each matching piece, so this phone example loses its dash. Run the file. The second result changes both occurrences of red, leaving the other words and punctuation intact. SQLite and MySQL use case-sensitive matching for replace. SQL Server follows the input's collation, which may be case-sensitive or case-insensitive. Do not assume that a rule tested on lowercase text covers uppercase variants. Decide which variants your cleaning rule should recognize.

Finding a Marker

INSTR Locates the At Sign

A marker can determine the cut. In this illustrative contact, instr finds the at sign in Asha's email address. Run the query. The position is eleven, so taking one fewer character returns asha.verma, without the at sign. The subtraction converts a marker's position into the length before it. The start stays at one. But what if an imported contact has no at sign? A missing marker returns zero, and blindly subtracting one gives a negative length.

Missing Marker

Return Null When the Marker Is Absent

Guard the missing-marker case first. This non-run SQL Server listing returns null when the marker is absent. CHARINDEX takes the search text first, then the text being searched. MySQL's INSTR takes those arguments in the opposite order. When the marker exists, left receives a valid length. Without the guard, SQL Server rejects a negative length; MySQL's left returns empty text. Neither behavior tells your application why the address is unusable. Choose a clear policy, such as returning null and flagging the import for review.

Quick Check

Predict a Nested Function Result

Try a fresh import code. This query combines functions, with the inner expression providing the input to the outer one. Which text does the query return? Read the nesting carefully. Pause, and predict. 0731. Trim cleans the boundaries, replace removes the prefix and dash, and substr takes the first four remaining characters. Run it to confirm. The leading zero remains because this is text. The other choices either keep the prefix or discard a meaningful character.

Numeric Truncation

MySQL TRUNCATE Drops Extra Decimal Digits

Numeric truncate is a different tool. MySQL's function drops digits beyond the requested decimal places; it does not trim a string. At two decimal places, 3.789 becomes 3.78. Round instead produces 3.79. For a negative number, truncation moves toward zero. -3.789 becomes -3.78. Floor behaves differently: it goes downward, giving negative four here. A negative decimal count cuts left of the point; minus two gives twelve hundred. These documented examples remain non-run listings. None of them empties a table.

Dialect Difference

SQL Server ROUND With a Third Argument

SQL Server has no numeric truncate function. Its round function truncates when the third argument is nonzero. The value is 3.78, but the original scale is retained. It can display as 3.780. SQLite round does not provide that third argument. Function names are familiar, but their supported signatures still depend on the database.

Storage Limits

Values Too Long for a Column

A storage limit is another boundary. A nonspace value that exceeds a column's capacity can make an insert fail. MySQL reports a data-too-long error under strict mode. Without strict mode, it can shorten the value and issue a warning. SQL Server reports string or binary data truncation with ANSI_WARNINGS on. Exact messages depend on version and configuration. SQLite does not enforce a declared varchar length. Successful SQLite insertion therefore cannot prove that the same import fits a server column. Measure with the right function: MySQL's CHAR_LENGTH counts characters; SQL Server's LEN excludes trailing spaces. Storage limits may also involve bytes.

Applying the Fix

Widen, Shorten Deliberately, or Reject

Sofia can now clean the imported label without deleting its internal space. But a cleaned value can still exceed the destination's capacity. If a genuine customer name needs more room, widen the column through a planned schema change. Preserve the real name. If only a short display label is needed, deliberately take a prefix. Keep the complete source value elsewhere when the application needs it. For a meaningful identifier, reject and report overlength input. Silent shortening could turn two different codes into the same one.

Key Takeaways

Cut, Clean and Validate Text Safely

Extract with a start and length, and check the database's dialect. Trim boundary spaces; replace matching text deliberately. Padding also needs an overlength policy. Guard missing markers before calculating a cut. Numeric truncation drops digits, while storage validation protects meaning.

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 Trimming Text with SQL TRUNCATE String

How do you shorten a string to a fixed number of characters in SQL?
Take a prefix with LEFT(name, 10) in MySQL or SQL Server, or with SUBSTRING(name, 1, 10); SQLite offers substr(name, 1, 10). Positions start at 1. Despite its name, MySQL's TRUNCATE function works on numbers, not text. Shorten display labels on purpose only, because cutting a meaningful identifier can turn two different codes into the same value; reject or report overlength identifiers instead.
What is the difference between TRIM, LTRIM, and RTRIM in SQL?
LTRIM removes leading spaces, RTRIM removes trailing spaces, and TRIM removes spaces from both ends. None of them touches the space between words, so TRIM(' Blue Notebook ') returns 'Blue Notebook'. The one-argument forms remove ordinary spaces, not tabs or every invisible character. SQL Server added TRIM in SQL Server 2017; older versions can nest LTRIM(RTRIM(name)) for the same result.
How do you get the text before a character like @ in SQL?
Find the character's position, then take one fewer character from the left. In SQLite, instr('asha.verma@example.com', '@') returns 11, so substr(email, 1, instr(email, '@') - 1) gives asha.verma. SQL Server's CHARINDEX('@', email) takes the search text first, while MySQL's INSTR(email, '@') takes the string first. Guard the missing case: a position of 0 minus 1 is negative, so return NULL and flag the row.
What is the difference between TRUNCATE and ROUND for numbers in SQL?
In MySQL, TRUNCATE drops digits beyond the requested decimal places, while ROUND rounds to the nearest value. So TRUNCATE(3.789, 2) returns 3.78 but ROUND(3.789, 2) returns 3.79. Truncation moves toward zero, so TRUNCATE(-3.789, 2) gives -3.78, while FLOOR(-3.789) gives -4. SQL Server has no numeric TRUNCATE function; ROUND(3.789, 2, 1) truncates instead and can display 3.780.

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 →