SQL FIND_IN_SET function
Returns the 1-based position of a value inside a comma-separated string, or 0 when the value is not in the list.
- Catégorie
- Strings
- Returns
integer- In this category
- 90 of 172
Syntaxe
FIND_IN_SET(value, comma_separated_list)
Prise en charge des moteurs
| Moteur | Support | Notes |
|---|---|---|
| SQL Server | Not built in | No FIND_IN_SET; split with STRING_SPLIT and compare rows. |
| PostgreSQL | Not built in | No FIND_IN_SET; array_position(string_to_array(list, ','), value). |
| MySQL | Oui | Supported under this name. |
| SQLite | Not built in | No FIND_IN_SET; INSTR(',' || list || ',', ',' || value || ','). |
| Oracle | Not built in | No FIND_IN_SET; the same INSTR trick with delimiters added. |
Exemples
MySQL
SELECT FIND_IN_SET('red', 'blue,red,green') AS pos; -- 2
MySQL
SELECT * FROM roles
WHERE FIND_IN_SET('admin', permissions) > 0;
Bon à savoir
- The list is one string with no quoting or trimming: 'red' is not found in 'blue, red' because that element is ' red'.
- A search value that contains a comma never matches: FIND_IN_SET('a,b', 'a,b') is 0. Returns NULL when either argument is NULL.
- Filtering with WHERE FIND_IN_SET(5, tag_ids) cannot use an index on tag_ids, so it scans the table. A child table and a join scale; comma lists do not.
Questions about FIND_IN_SET
What is the difference between FIND_IN_SET and LIKE?
FIND_IN_SET matches a whole element of a comma list, so it finds 'red' but not inside 'bordered'. LIKE '%red%' would match 'bordered' too.
Should I store comma-separated lists to use with FIND_IN_SET?
Usually not. It defeats indexes and foreign keys. Use a child table and a join; keep FIND_IN_SET for legacy data and SET columns.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: MySQL.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.