SQL Query to Delete Last N Characters From Field
Last Updated :
10 Dec, 2024
SQL (Structured Query Language) is the foundational language used for managing and manipulating relational databases. In SQL, string manipulation plays an essential role, particularly when we need to clean or modify data. One common task is removing the last N characters from a column. This operation might be necessary when dealing with unwanted trailing characters such as spaces, commas, or other special characters.
In this article, we will explain how to delete the last N characters from a column using SQL queries. We will dive into practical examples using popular SQL functions like SUBSTRING()
and LEN()
.
SQL String Functions Used
SQL provides a range of string functions to manipulate textual data. For removing characters, we typically rely on SUBSTRING()
and LEN()
. To perform the required function we need the following functions:
1. SUBSTRING()
This function extracts a portion of a string starting from a specific position. By combining it with LEN()
, we can easily remove characters from the end of a string or we can say it extracts a substring from the string starting at the given position for the specified length.
Syntax
SUBSTRING(string, start_position, length)
Key Terms
- String: It is a required parameter. It provides information about the string on which function is applied.
start_position
,
: It gives the starting position of the string. It is also the required parameter.
- Length: It is an optional parameter. By default, it takes the length of the whole string.
Query:
SUBSTRING('geeksforgeeks', 1, 5);
Output
geeks
2. LEN()
This function returns the number of characters in a string, excluding trailing spaces in some SQL dialects like SQL Server. It’s essential when we need to know the string's length to determine how many characters to remove. This syntax is not the standard one. Syntax for returning the length of a string may vary for different server . It takes only one parameter that is the string whose length we need to find.
Query:
LEN('geeksforgeeks')
Output
13
Removing the Last N Characters
To remove the last N characters from a column, we can use the SUBSTRING()
function, along with the LEN()
function to specify the length of the substring. To delete the last N characters from the field we will use the following query:
Syntax
SUBSTRING(string, 1, length(string)-N)
Key Terms
column_name
: The name of the column from which you want to remove characters.
LEN(column_name) - N
: Calculates the new length by subtracting N characters from the total length of the column.
Step-by-Step Guide: Removing the Last N Characters in SQL
Let’s start by creating a sample table called geeksforgeeks in a database, which will help us demonstrate how to remove the last N characters from a field.
Step 1: Create the Table
CREATE TABLE geeksforgeeks (
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
CITY VARCHAR(20),
AGE INT,
GENDER VARCHAR(20)
);
Step 2: Insert Sample Data
INSERT INTO geeksforgeeks VALUES ('ROMY', 'Kumari', 'New Delhi', 22, 'female');
INSERT INTO geeksforgeeks VALUES ('Pushkar', 'jha', 'New Delhi', 23, 'male');
INSERT INTO geeksforgeeks VALUES ('Sujata', 'jha', 'Bihar', 30, 'female');
INSERT INTO geeksforgeeks VALUES ('Roshini', 'Kumari', 'Bihar', 16, 'female');
INSERT INTO geeksforgeeks VALUES ('Avinav', 'Pandey', 'New Delhi', 21, 'male');
Step 3: View the Data
SELECT * FROM geeksforgeeks;
Output
geeksforgeeksExample 1: Remove the Last Character from the FIRSTNAME Column
Now to delete the last N characters from the field we will use the geeksforgeeks table. To remove the last character from the FIRSTNAME column, we can use the SUBSTRING() and LEN() functions as follows. Below is the query for the SUBSTRING() function to delete the last characters from the field
Query:
SELECT SUBSTRING(FIRSTNAME, 1, LEN(FIRSTNAME) - 1) AS FIRSTNAME, LASTNAME, AGE FROM demo_table;
Output
FIRSTNAME | LASTNAME | AGE |
---|
Rom | Kumari | 22 |
Pushka | Jha | 23 |
Meenaks | Jha | 20 |
Shalini | Jha | 22 |
Nikhil | Kalra | 23 |
Akanksa | Gupta | 23 |
Explanation:
- The
LEN(FIRSTNAME) - 1
part of the query calculates the length of the FIRSTNAME column and subtracts 1 from it.
- This ensures that only the first part of the string (up to the second-to-last character) is retrieved, effectively removing the last character from each entry.
Example 2: Remove the Last N Characters from the FIRSTNAME Column
If we need to remove more than just the last character, we can modify the query to remove the last N characters from the string. For instance, if we want to remove the last 3 characters from the FIRSTNAME column, the query would be:
Query:
SELECT SUBSTRING(FIRSTNAME, 1, LEN(FIRSTNAME) - 3) AS FIRSTNAME, LASTNAME, AGE FROM demo_table;
Output
FIRSTNAME | LASTNAME | AGE |
---|
Ro | Kumari | 22 |
Pushk | Jha | 23 |
Meenak | Jha | 20 |
Shali | Jha | 22 |
Nikhi | Kalra | 23 |
Akank | Gupta | 23 |
Explanation:
- Here, the query removes the last 3 characters from the FIRSTNAME column by subtracting 3 from the total length of the string.
- The result is a substring that contains the first part of each name, excluding the last 3 characters.
Example3: Delete the Last 2 Characters from the FIRSTNAME Column
If we want to remove just the last 2 characters from the FIRSTNAME column, we can use the following SQL query. This query will remove exactly the last two characters from each value in the FIRSTNAME column. It is particularly useful when dealing with names or data entries that consistently need trimming of specific characters at the end.
Query:
SELECT SUBSTRING(FIRSTNAME, 1, LEN(FIRSTNAME) - 2) FROM geeksforgeeks;
Output
FIRSTNAME |
---|
Ro |
Pushk |
Suja |
Roshi |
Avin |
Explanation:
- The
LEN(FIRSTNAME)
function returns the length of the string in the FIRSTNAME column.
- Subtracting
2
from LEN(FIRSTNAME)
effectively removes the last two characters of each value in the FIRSTNAME column.
SUBSTRING(FIRSTNAME, 1, LEN(FIRSTNAME) - 2)
starts at the first character and retrieves a substring of the length calculated by LEN(FIRSTNAME) - 2
, thereby excluding the last two characters.
Conclusion
In this article, we explained how to remove the last N characters from a field in SQL using the SUBSTRING()
and LEN()
functions. We covered different scenarios, such as removing just the last character or multiple characters, and provided detailed examples with outputs to help us understand the process. By mastering these SQL string functions, we can easily manipulate and clean our data, ensuring consistency and accuracy in our database queries.
Similar Reads
How to delete last N rows from Numpy array?
In this article, we will discuss how to delete the last N rows from the NumPy array. Method 1: Using Slice Operator Slicing is an indexing operation that is used to iterate over an array. Â Syntax: array_name[start:stop] where start is the start is the index and stop is the last index. We can also do
4 min read
SQL Query to Delete a Data From a Table Based on Date
Many of the time we have to delete data based on the date. These dates can be some older dates. For this purpose, we can use delete query along with where clause. This approach helps us to delete some old data in our database. In this article, we are going to delete the data of employees based on th
2 min read
JavaScript - Delete First Character of a String
To delete the first character of a string in JavaScript, you can use several methods. Here are some of the most common onesUsing slice()The slice() method is frequently used to remove the first character by returning a new string from index 1 to the end.JavaScriptlet s1 = "GeeksforGeeks"; let s2 = s
1 min read
Remove Last character from String in Linux
In this article, we will discuss how to remove the last character from the string in Linux. In Linux, there are various commands and techniques present by which you can do this task in an easier way if you have some basic knowledge about the commands in Linux. Here, you will see the different comman
3 min read
How to Remove Last Character from String in Ruby?
Removing the last character from a string in Ruby is a common task in various programming scenarios. Whether you need to manipulate user input, process file paths, or clean up data, there are several approaches to achieve this. This article focuses on discussing how to remove the last character from
2 min read
Deletion of character in String
Given a string str and an integer position pos, the task is to delete the character at the specified position pos from the string str. Examples: Input: str = "GeeksforGeeks", pos = 5Output: GeeksorGeeks Input: str = "HelloWorld", pos = 0Output: elloWorld Deletion of character in String using Loop:Tr
4 min read
How to Remove the Last Character From a Table in SQL?
SQL (Structured Query Language) allows for efficient data manipulation and retrieval. A common task in SQL involves removing the last character from a specific column within a table. This can be achieved using string functions like SUBSTRING() and LEN(). In this article, we will demonstrate how to a
4 min read
How to remove First and Last character from String in Scala?
In this article, we will explore different approaches to removing the first and last character from a string in Scala. Table of Content Using substring methodUsing drop and dropRight methodsUsing substring methodIn this approach, we are using the substring method which takes two arguments the starti
1 min read
SQL Query to Display Last 5 Records from Employee Table
In SQL, retrieving the last few records from a table can be crucial for various database management tasks such as auditing, pagination, and displaying recent entries. Whether you're dealing with user activity logs, recent transactions, or just viewing the latest additions to a database, SQL provides
5 min read
SQL Query to Display Last 50% Records from Employee Table
Here, we are going to see how to display the last 50% of records from an Employee Table in MySQL and MS SQL server's databases. For the purpose of demonstration, we will be creating an Employee table in a database called "geeks". Creating a Database : Use the below SQL statement to create a database
2 min read