MySQL
SQL functions
FIND_IN_SET
IN operator
database queries

FIND_IN_SET vs IN

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In SQL, different functions and clauses are available to perform various operations based on your needs. Two such functionalities are `FIND_IN_SET()` and the `IN()` clause. While both can be used to identify the presence of a value within a set, they differ significantly in syntax, use cases, performance, and limitations.

FIND_IN_SET()

The `FIND_IN_SET()` function is predominantly used in MySQL to search for a string within a comma-separated string list. This function returns the position of the first occurrence of the searched string in the list of strings if it exists; otherwise, it returns zero.

Syntax

  • `string_to_find`: The string value we are looking for.
  • `string_list`: A list of strings separated by commas.

1 | John | Math,Science,Art 2 | Alice | History,Math 3 | Bob | Art,History,Math

  • Only works with comma-separated string lists.
  • `FIND_IN_SET()` returns the position (1-based index) or zero if not found.
  • Slower on large datasets due to its sequential scanning nature.

1 | John | Math 2 | John | Science 3 | John | Art 4 | Alice | History 5 | Alice | Math 6 | Bob | Art 7 | Bob | History 8 | Bob | Math

  • Can operate with column data directly without requiring string lists.
  • Much faster due to its nature of leveraging indexes and set-based operation.
  • Works across all SQL-compliant databases, not just MySQL.
  • `FIND_IN_SET()`: Linear search through a string list; not optimized for large datasets. Since MySQL treats the string list as a single string, the function cannot utilize any indexing, making it slower as dataset sizes grow.
  • `IN()`: More performant for large datasets; it leverages database indexing mechanisms which optimize searching operations, especially when compared to sequential scans.
  • `FIND_IN_SET()`: Practical when dealing with denormalized tables where lists, like tags or roles, are stored as strings. Mainly useful when regular database normalization isn't employed.
  • `IN()`: Preferred when database normalization is respected. Operates seamlessly when referencing columns that have been set up according to normal forms.

Course illustration
Course illustration

All Rights Reserved.