Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split FirstName and LastName in sqlite

Tags:

sqlite

I have a table in sqlite db called [tblbook] with a column [authors]. What I am trying to do in the sql is to split the author values to firstname and the lastname and sort it on lastname. I did find this great code:

 SELECT substr(BookAuthor, 1, NULLIF(CHARINDEX(' ', BookAuthor) - 1, -1)) AS [FirstName],
   substr(BookAuthor, CHARINDEX(' ', BookAuthor) + 1, LEN(BookAuthor)) AS [LastName]
 FROM tblBook where _id=3

It works perfectly on MSSQL but sqlite doesn't have the charindex function hence it fails.

Could anyone please be kind and advise me what should be the best approach to achieve this.

like image 604
snowflakes74 Avatar asked Jun 22 '12 12:06

snowflakes74


People also ask

How do I select two columns in SQLite?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can I use varchar in SQLite?

You can declare a VARCHAR(10) and SQLite will be happy to store a 500-million character string there. And it will keep all 500-million characters intact. Your content is never truncated. SQLite understands the column type of "VARCHAR(N)" to be the same as "TEXT", regardless of the value of N.

What is difference between text and varchar in SQLite?

Some Differences Between VARCHAR and TEXT The VAR in VARCHAR means that you can set the max size to anything between 1 and 65,535. TEXT fields have a fixed max size of 65,535 characters. A VARCHAR can be part of an index whereas a TEXT field requires you to specify a prefix length, which can be part of an index.

Does SQLite support multiple connections?

The current version of SQLite handles multiple connections through its thread-mode options: single-thread, multi-thread, and serialized. Single-thread is the original SQLite processing mode, handling one transaction at a time, either a read or a write from one and only one connection.


1 Answers

Another way (a little shorter) to write this would be

SELECT 
  substr(BookAuthor, 1, instr(BookAuthor, ' ') - 1) AS first_name,
  substr(BookAuthor,    instr(BookAuthor, ' ') + 1) AS last_name
FROM tblBook where id=3
ORDER BY last_name

This would apply for version 3.7.15 and beyond.

like image 195
demongolem Avatar answered Oct 04 '22 22:10

demongolem