Reputation: 1954
I retrieve quite a lot of data from SQLite database. When retrieving I map it to different views in my application. There is a text field in my table from which I don't want to get the full text, just first n chars. So if my query for example is:
Select description from articles where id='29';
Then how do I get the substring from description? thanks
Upvotes: 49
Views: 60390
Reputation: 74645
Use the substr
function.
From the list of core functions:
substr(X,Y,Z) substr(X,Y) substring(X,Y,Z) substring(X,Y)
The
substr(X,Y,Z)
function returns a substring of input stringX
that begins with theY-th
character and which isZ
characters long. IfZ
is omitted thensubstr(X,Y)
returns all characters through the end of the stringX
beginning with theY-th
. The left-most character ofX
is number 1. IfY
is negative then the first character of the substring is found by counting from the right rather than the left. IfZ
is negative then theabs(Z)
characters preceding theY-th
character are returned. IfX
is a string then characters indices refer to actual UTF-8 characters. IfX
is a BLOB then the indices refer to bytes.
substring()
is an alias forsubstr()
beginning with SQLite version 3.34.
Upvotes: 75
Reputation: 7415
You can use the builtin function in SQLite which is substr(X,Y,Z)
. The x field represents the string input to be sliced, the y field represents the starting point using an index, and the z field represents the substring length.
===============================
|Database Table : **articles**|
===============================
|id | description |
-------------------------------
|29 | Lorem ipsum domit |
===============================
Now we will try to make a select query for our description
SELECT substr(description,1,4) FROM articles where id='29';
Output would be: Lore instead of Lorem ipsum domit
Upvotes: 22
Reputation: 175596
To extend existing answers, starting from SQLite 3.34.0:
The substr() SQL function can now also be called "substring()" for compatibility with SQL Server.
substring(X,Y) "substring()" is an alias for "substr()" beginning with SQLite version 3.34.
Upvotes: 1