SQLite INSTR() Function
The SQLite INSTR() function returns the location of the first occurrence of string Y in the string X. If Y is not found within the string X, this function returns 0.
If the passed argument are both BLOBs, then INSTR(X,Y) returns one more than the number bytes prior to the first occurrence of Y, or 0 if Y does not occur anywhere within X.
If both arguments are non-NULL and are not BLOBs then both are interpreted as strings. If either X or Y are NULL in INSTR(X,Y) then the result is NULL.
Syntax
INSTR(X, Y)
Parameters
X |
Required. Specify the value to search. |
Y |
Required. Specify the value to search for in X. |
Return Value
Returns the location of the first occurrence of the Y in X.
Example 1:
The example below shows the usage of INSTR() function.
SELECT INSTR('AlphaCodingSkills.com', 'A'); Result: 1 SELECT INSTR('AlphaCodingSkills.com', 'Coding'); Result: 6 SELECT INSTR('AlphaCodingSkills.com', '.com'); Result: 18 SELECT INSTR('AlphaCodingSkills.com', 'l'); Result: 2 SELECT INSTR('AlphaCodingSkills.com', 'Z'); Result: 0 SELECT INSTR('AlphaCodingSkills.com', 'ABC'); Result: 0
Example 2:
Consider a database table called Employee with the following records:
PhoneNumber | EmpID | Address |
---|---|---|
+1-8054098000 | 1 | Brooklyn, New York, USA |
+33-147996101 | 2 | Grenelle, Paris, France |
+31-201150319 | 3 | Geuzenveld, Amsterdam, Netherlands |
+86-1099732458 | 4 | Yizhuangzhen, Beijing, China |
+65-67234824 | 5 | Yishun, Singapore |
+81-357799072 | 6 | Koto City, Tokyo, Japan |
In the query below, the INSTR() function is used to extract the country code from the PhoneNumber column records.
SELECT *, SUBSTR(PhoneNumber, 1, INSTR(PhoneNumber, '-') - 1) AS CountryCode FROM Employee;
This will produce the result as shown below:
PhoneNumber | EmpID | Address | CountryCode |
---|---|---|---|
+1-8054098000 | 1 | Brooklyn, New York, USA | +1 |
+33-147996101 | 2 | Grenelle, Paris, France | +33 |
+31-201150319 | 3 | Geuzenveld, Amsterdam, Netherlands | +31 |
+86-1099732458 | 4 | Yizhuangzhen, Beijing, China | +86 |
+65-67234824 | 5 | Yishun, Singapore | +65 |
+81-357799072 | 6 | Koto City, Tokyo, Japan | +81 |
❮ SQLite Functions