Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the character in nth position in a string

For example,

create table tblvarchar 
(
lngvarchar character varying(500)
)

And Sample Row is

insert into tblvarchar (lngvarchar) values ('110010000001111101010011110000001101011000001')
  • How to find out the character(this case (0 or 1)) in lngvarchar field using the position of character ?
  • for example, the character in 15th position of lngvarchar is 1

On PostgreSQL 9.2.4

like image 361
Vivek S. Avatar asked Jul 23 '14 10:07

Vivek S.


2 Answers

You can do this (start position 15, length 1 example):

SELECT SUBSTRING(lngvarchar,15,1) FROM tblvarchar;

SQL FIDDLE

like image 200
Ilesh Patel Avatar answered Sep 18 '22 02:09

Ilesh Patel


If your data contains only 0 and 1, you might want to use bit strings instead of character varying (bit varying in your case).

You can use the get_bit() function to get a single bit (but that function use zero based indexing); also substring() works on bit strings too (but will give you text results).

SQLFiddle

like image 26
pozs Avatar answered Sep 19 '22 02:09

pozs