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
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: Clearing Tables with SQL TRUNCATE Table →← 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 →
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.
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 Trimming Text with SQL TRUNCATE String
How do you shorten a string to a fixed number of characters in SQL?
What is the difference between TRIM, LTRIM, and RTRIM in SQL?
How do you get the text before a character like @ in SQL?
What is the difference between TRUNCATE and ROUND for numbers in SQL?
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 →