Extract the first word before a space using SQL - sql

Let's say I have a column in my users table called name:
name
----
Brian
Jill Johnson
Sarah
Steven Smith
I want to write a PostgreSQL query to fetch just the first name. This is what I have so far:
select substr(name, 0, position(' ' IN name) | length(name) + 1) as first_name from users;
name
----
Brian
Jill
Sarah
Steven
This appears to work but I feel like there much be an easier way.

Although I don't follow the logic, your code looks like Postgres. If so, use split_part():
select split_part(name, ' ', 1)
from users;

Related

How to use LIKE in a query to find multiple words?

I have a cust table
id name class mark
1 John Deo Matt Four 75
2 Max Ruin Three 85
3 Arnold Three 55
4 Krish Star HN Four 60
5 John Mike Four 60
6 Alex John Four 55
I would like to search for a customer which might be given as John Matt without the deo string. How to use a LIKE condition for this?
SELECT * FROM cust WHERE name LIKE '%John Matt%'
The result should fetch the row 1.
what if the search string is Matt Deo or john
The above can't be implemented when trying to find an exact name. How can I make the LIKE query to fetch the customer even if 2 strings are given?
If the pattern to be matched is
string1<space>anything<space>string2
you can write:
like string1||' % '||string2
Why not this
select * from cust where name Like 'John%Matt' ;
SELECT *
FROM custtable
WHERE upper(NAME) LIKE '%' || upper(:first_word) || '%'
AND upper(NAME) LIKE '%' || upper(:second_word) || '%'
Must you use LIKE? Oracle has plenty of more powerful search options.
http://docs.oracle.com/cd/B19306_01/server.102/b14220/content.htm#sthref2643
I'd look at those.
I believe you need REGEXP_LIKE( ):
SQL> with tbl(name) as (
select 'John Deo Matt' from dual
)
select name
from tbl
where regexp_like(name, 'matt|deo', 'i');
NAME
-------------
John Deo Matt
SQL>
Here the regex string specifies name contains 'matt' OR 'deo' and the 'i' means its case-insensitive. The order of the names does not matter.

How do you split data from one column into two?

I just recently started learning about SQL in MS Access and SQL Server so I have very limited knowledge, but what I'm looking for is help with a query in MS Access.
I know how to merge 2 columns into 1 and have the final result separated by a comma or whatever symbol I'd like. But, how do I do the opposite?
In my case, I have a column (LastFirstName) in my table (MEMBERS) where the data would look something like this: "Smith, Middle John" etc.
What I'm having trouble with is figuring out how to permanently separate the data into 2 separate columns within the same table (LastName and FirstName) and not just using a query to display them like that.
Any help would be greatly appreciated, thanks!
Starting with
memberID LastFirstName LastName FirstName
-------- ------------- -------- ---------
1 Doe, John
the query
UPDATE Members SET
LastName = Trim(Left(LastFirstName, InStr(LastFirstName, ",") - 1)),
FirstName = Trim(Mid(LastFirstName, InStr(LastFirstName, ",") + 1))
will result in
memberID LastFirstName LastName FirstName
-------- ------------- -------- ---------
1 Doe, John Doe John

SQL: How to find exact matches of words within a text

Please bear with me, I'm new to Access and SQL.
What I'm trying to do is to write a SQL query to filter through two tables - one contains words that are split into two columns and the other contains text. Essentially, what I want is a new table that gives me all of the exact matches of the two columns of words with the column of text.
Here's an analogous database to simulate what I want as a result:
Table A:
FirstName: LastName:
John Doe
Jane Doe
Josh Smith
James Jones
David Johnson
Table B:
FullName:
Jake Davidson
Mike Peters
Jason James
John Michael Smith
Query Result:
FirstName: LastName: FullName:
John Doe John Michael Smith
Josh Smith John Michael Smith
James Jones Jason James
(notice that the David - Davidson match didn't come up. i.e. I'd like exact matches only)
So help me fill in the blanks:
SELECT TableA.FirstName,TableA.LastName, TableB.FullName
FROM TableA,TableB
WHERE TableB.FullName LIKE (has an exact match with TableA.FirstName--not sure what to put )
UNION
SELECT TableA.FirstName,TableA.LastName, TableB.FullName
FROM TableA,TableB
WHERE TableB.FullName LIKE (has an exact match with TableA.LastName--not sure what to put)
;
This will be dependant on what you want it to do with FullNames with more than two names, like "John Jacob Smith", but, assuming you want it to ignore the middle word[s],
then try
Select firstname, lastname, fullname
from tableA a
Join tableb f
On f.firstname = Mid(a.fullname, 1, InStr(a.fullname, " ")-1)
Join tableb l
On l.lastname = Mid(a.fullname, InStrRev(a.FullNamee, " ")+1)
Here is an approach that compares each FullName to both Firstname and LastName:
select a.Firstname, a.LastName, b.FullName
from tableA as a inner join
tableB as b
on instr(' '&b.FullName&' ', ' '&a.FirstName&' ') > 0 and
instr(' '&b.FullName&' ', ' '&a.Lastname&' ') > 0
It assume that the delimiter for names is a space (as in your example). The comparison attaches a space onto the beginning and end of FullName and then looks for a space-padded first name and last name.

Oracle 10G regexp for Name

I am trying to write a regexp_replace to create a "Friendly" name for some employees. They are currently stored as FIRST <POSSIBLE MIDDLE INITIAL> LAST <POSSIBLE SUFFIX> <MULTIPLE WHITESPACE> SITE_ID
For example,
JOHN SMITH ABC
JOHN Q SMITH ABC
JOHN Q SMITH III ABC
I am trying to write a regex so that I will end up with:
Smith, John
Smith, John Q
Smith III, John Q
The ABC "Site ID" doesn't need to be included in my output.
This is what I tried with little success:
regexp_replace(
employee_name,
'^(\S+)\s(\S+)\s(\S+)',
'\3, \1 \2'
)
Also, I am using Oracle 10G. Any help would be greatly appreciated!
If your names don't show the problems ruakh points out, i.e., there aren't single-letter names or surnames, and no Hispanic names, you can try this regexp:
^(\S+)\s(\S\s)?(\S+)(\s\S+)?\s\s+\S+$
The replacement should be:
\3\4, \1\2

T-SQL Query Problem

I have a column in Database called Full Name and I want split that name as FirstName and LastName:
Here is an Example:
FullName
Sam Peter
I want this to be
FirstName LastName
--------------------
Sam Peter
But the Problem is Some of the columns in Database have Full Names Like this
FullName
--------
Sam George Jack Peter
Sam Adam Peter
I want this to be
FirstName LastName
--------- --------
Sam George Jack Peter
Sam Adam Peter
How do I write T-SQL Query for this.
Thanks in Advance for all the help
There's a very thorough name parsing routine described in this answer. It handles your situation, along with much trickier cases like "Mr. Martin J Van Buren III".
String manipulation in SQL Server is notoriously weak.
Your best bet is to do it in your application layer.
For your example with more than 2 names, how do you know which fields those additional names go into? Are you guaranteed they will always have only one last name?
Found this on net (did not test it)
REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
You can test it with
SELECT REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
FROM Table
if it works you can then
UPDATE Table
SET LastName = REVERSE(SUBSTRING(REVERSE([FullName]),1,FINDSTRING(REVERSE([FullName])," ",1)))
I leave the exercise for the first name to you.
Are you just splitting at the last space? If so this should work:
select 'Sam George Jack Peter' as FullName
into #names
union select 'Sam Adam Peter'
select LEFT(FullName,LEN(FullName)-CHARINDEX(' ',REVERSE(FullName))) as FirstName
,RIGHT(FullName,CHARINDEX(' ',REVERSE(FullName))-1) as LastName
from #names
EDIT:
To handle names with no spaces and put the FullName as LastName
select 'Sam George Jack Peter' as FullName
into #names
union select 'Sam Adam Peter'
union select 'Peter'
select CASE
WHEN CHARINDEX(' ',FullName) = 0 THEN ''
ELSE LEFT(FullName,LEN(FullName)-CHARINDEX(' ',REVERSE(FullName)))
END as FirstName
,CASE
WHEN CHARINDEX(' ',FullName) = 0 THEN FullName
ELSE LTRIM(RIGHT(FullName,CHARINDEX(' ',REVERSE(FullName))))
END as LastName
from #names