Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
SUBSTRING() function in MySQL
Next article icon

Using LENGTH() Function in SQL

Last Updated : 16 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Understanding the length of strings within a database is a fundamental aspect of effective data management and analysis. In the world of SQL, the LENGTH() function provides an essential tool for measuring the number of characters in a string, which can be invaluable for various tasks such as data validation, formatting, and manipulation.

This article delves into the power and utility of the LENGTH() function, showcasing its application and significance in real-world scenarios. By mastering this function, you can optimize your SQL queries and unlock deeper insights into your data, making it an indispensable skill for developers and analysts alike.

Understanding LENGTH() Function in SQL

SQL’s LENGTH() function is among the most versatile tools that can be applied in data validation, formatting, and handling operations. Developers and analysts can apply this method just by giving it a string value whereby it efficiently gives back the count of characters that enables them to work more efficiently and hence derive useful insights from databases.

The LENGTH() function remains an integral part of SQL query optimization and data analysis pipelines whether applicable in data cleansing activities, verification routines, or report production. This article will examine how LENGTH() works about syntax, application, and best practices to give users of SQL a deeper knowledge of this powerful instrument used for various purposes.

LENGTH() Function in SQL

SQL's LENGTH() function is about finding the character count in a string. This function comes in handy when you need to verify input lengths, format output or perform data analysis tasks. When you give a string as an argument into the LENGTH() function, SQL will return the number of characters in that particular string including spaces and special characters.

Syntax:

The syntax for the LENGTH() function in SQL is relatively straightforward:

LENGTH(string)

string: This is the input string for which you want to determine the length.

Example of LENGTH() Function in SQL

Example 1: How many letters are there in each student's name

Let's Create students table with a column called student_name.

CREATE TABLE students (
student_name VARCHAR(50)
);
INSERT INTO students (student_name) VALUES 
('John'),
('Emily'),
('Michael');

Output:

student_name

John

Emily

Michael

Query:

SELECT student_name, LENGTH(student_name) AS name_length
FROM students;

Output:

student_name

name_length

John

4

Emily

5

Michael

7

Explanation: The LENGTH() function calculates the number of characters for every student. John has 4 characters, Emily has 5, and Michael has 7 characters.

Example 2: Using with WHERE clause

Assume that we want to get all students whose names have more than 6 letters.

Let's Create students table with a column called student_name.

CREATE TABLE students (
student_name VARCHAR(50)
);
INSERT INTO students (student_name) VALUES 
('Elizabeth'),
('Christopher'),
('Alex'),
('Geek');

Output:

student_name

Elizabeth

Christopher

Alex

Geek

Query:

SELECT student_name
FROM students
WHERE LENGTH(student_name) > 6;

Output:

student_name

Elizabeth

Christopher

Explanation: All students names which have length greater than 6 characters will be filtered out by WHERE clause. Elizabeth, Christopher, and Alexander have lengths more than 6 characters.

Example 3: Combining with other functions

Imagine that we need to get the average of the length of student names.

Let's Create students table with a column called student_name.

CREATE TABLE students (
student_name VARCHAR(50)
);
CREATE TABLE students (
student_name VARCHAR(50)
);

Output:

student_name

John

Emily

Michael

Anna

David

Query:

SELECT AVG(LENGTH(student_name)) AS avg_name_lengthFROM students;

Output:

avg_name_length

5.4

Explanation: On its part, AVG() computes the average length of these lengths. The LENGTH() function calculates the total number of alphabets in each name of the students.

Conclusion

The LENGTH() function in SQL is a powerful and versatile tool for measuring the length of strings within a database, offering valuable insights for data validation, filtering, and analysis. By mastering this function, you can optimize queries and enhance data management processes, ensuring the integrity and quality of your data. Whether calculating string lengths for individual records or aggregating data for summary statistics, LENGTH() provides essential functionality that empowers SQL practitioners to work efficiently and effectively with textual data across a wide range of applications.


Next Article
SUBSTRING() function in MySQL

R

roshan_wadhai
Improve
Article Tags :
  • SQL

Similar Reads

  • Using REPLACE Function in SQL
    In Structured Query Language (SQL), the REPLACE function is used to replace a substring or a part of a string within the given String. While dealing with some data pre-processing tasks or some data cleaning tasks, the REPLACE function is found to be very useful. It can save a lot of time and it also
    4 min read
  • LEFT() Function in MySQL
    The LEFT() function in MySQL is used to extract a specified number of characters from the left side of a given string. It uses its second argument to decide, how many characters it should return. Syntax: LEFT (str, len)Parameter: This function accepts two parameters as mentioned above and described
    1 min read
  • SUBSTRING() function in MySQL
    SUBSTRING() : function in MySQL is used to derive substring from any given string .It extracts a string with a specified length, starting from a given location in an input string. The purpose of substring is to return a specific portion of the string. Syntax : SUBSTRING(string, start, length) OR SUB
    2 min read
  • SIGN() Function in MySQL
    SIGN() function in MySQL is used to return the sign of the given number. It returns 1 if the number is positive, -1 if the number is negative and 0 for zero. Syntax : SIGN(X) Parameter : SIGN() function accepts one parameter as input and will give you the results in values like Positive(+1),Negative
    1 min read
  • MONTH() function in MySQL
    MySQL MONTH() function returns the month from the given date. It returns a month value between 1 and 12 or returns 0 when the month part of the date is 0. It's a useful SQL function for date manipulation and analysis, particularly when dealing with reports or queries that require month-based groupin
    3 min read
  • LN() Function in MySQL
    LN() function : It is the function in MySQL is used to calculate the natural logarithm of a specific number with base e . The number must be greater than 0, otherwise it will return NULL. Syntax : LN(X) Parameter : LN() function accepts one parameter as mentioned above in the syntax and described be
    2 min read
  • LEAST() Function in MySQL
    The LEAST() function in MySQL is a versatile tool that returns the smallest (minimum) value from a list of expressions. It can be used with numbers, strings, or even columns of data to find the minimum value according to their data type. In this article, We will learn about LEAST() Function in MySQL
    4 min read
  • Using the REVERSE Function in SQL
    In SQL, the REVERSE function is a handy tool that does exactly what its name suggests, it reverses the order of characters within a string. This function can be particularly useful for various data manipulation tasks, allowing you to quickly transform text in a way that suits your needs. We will exa
    4 min read
  • PLSQL | SIN Function
    The PLSQL SIN function is used to return the sine of a numeric value. The SIN function accepts one parameter which is the number whose sine needs to be calculated. The SIN function returns a value of the numeric data type. This function takes as an argument any numeric data type as well as any non-n
    2 min read
  • Window Functions in PL/SQL
    In Oracle PL/SQL, analyzing and managing complex data relationships often involves performing calculations across sets of rows. This is where window functions, sometimes referred to as "Analytic functions," come into play. They enable powerful data analysis, such as sales forecasting, time-series an
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences