Day 12: String Functions
Introduction:
String functions in SQL are used to manipulate string data. They are essential for transforming and analyzing text.
Key Concepts:
LENGTH(): Returns the length of a string.
LOWER() and UPPER(): Converts a string to lower-case or upper-case.
CONCAT(): Concatenates two or more strings.
SUBSTRING(): Extracts a substring from a string.
TRIM(): Removes leading and trailing spaces from a string.
REPLACE(): Replaces occurrences of a substring within a string.
SQL Commands and Examples:
LENGTH() Function:
Get the length of a string.
-- Get the length of the CourseName string
SELECT CourseName, LENGTH(CourseName) AS NameLength FROM Courses;
LOWER() and UPPER() Functions:
Convert a string to lower-case or upper-case.
-- Convert the FirstName to lower-case and upper-case
SELECT FirstName, LOWER(FirstName) AS LowerCaseName, UPPER(FirstName) AS UpperCaseName FROM Students;
CONCAT() Function:
Concatenate two or more strings.
-- Concatenate FirstName and LastName to create FullName
SELECT FirstName, LastName, CONCAT(FirstName, ' ', LastName) AS FullName FROM Students;
SUBSTRING() Function:
Extract a substring from a string.
-- Extract the first 3 characters from the CourseName
SELECT CourseName, SUBSTRING(CourseName, 1, 3) AS ShortName FROM Courses;
TRIM() Function:
Remove leading and trailing spaces from a string.
-- Remove leading and trailing spaces from the CourseName
SELECT CourseName, TRIM(CourseName) AS TrimmedName FROM Courses;
REPLACE() Function:
Replace occurrences of a substring within a string.
-- Replace 'SQL' with 'Structured Query Language' in the CourseName
SELECT CourseName, REPLACE(CourseName, 'SQL', 'Structured Query Language') AS NewName FROM Courses;
Practice Exercise:
Use the Courses and Students tables.
Write a query to get the length of each
FirstName.Write a query to convert the
LastNameto upper-case.Write a query to concatenate
FirstNameandLastNamewith a space in between.Write a query to extract the first 5 characters from the
CourseName.Write a query to trim leading and trailing spaces from the
FirstName.Write a query to replace 'Course' with 'Subject' in the
CourseName.
-- Get the length of each FirstName
SELECT FirstName, LENGTH(FirstName) AS NameLength FROM Students;
-- Convert LastName to upper-case
SELECT LastName, UPPER(LastName) AS UpperCaseLastName FROM Students;
-- Concatenate FirstName and LastName
SELECT FirstName, LastName, CONCAT(FirstName, ' ', LastName) AS FullName FROM Students;
-- Extract the first 5 characters from CourseName
SELECT CourseName, SUBSTRING(CourseName, 1, 5) AS ShortName FROM Courses;
-- Trim leading and trailing spaces from FirstName
SELECT FirstName, TRIM(FirstName) AS TrimmedName FROM Students;
-- Replace 'Course' with 'Subject' in CourseName
SELECT CourseName, REPLACE(CourseName, 'Course', 'Subject') AS NewCourseName FROM Courses;
Mastering string functions allows you to manipulate text data effectively.
0 Comments