SQL Like query last match - sql

I've a database that has a name field. (i.e Firstname M. Lastname or just Firstname Lastname).
Trying to filter by lastname.
How can I do a query to find the last space?
Something like
select * from person where name like "% a%" (but the space is the last space)
Thanks,
Tee

If using some version of Microsoft SQL Server, you could reverse() the string, and then use charindex() to find the first space.

If this is mySQL, you can consider using the SUBSTRING_INDEX() function (with count = -1).

SELECT CASE WHEN [Name] LIKE '% [^ ]%'
THEN SUBSTRING([Name],
LEN([Name]) - CHARINDEX(' ', REVERSE([Name])) + 1,
8000)
ELSE [Name]
END AS [LastName]
FROM [Customers]

Related

Adding comma after first word in column

I have a table called people and a column called NAME which has last first middle (if exists) . so SMITH JOHN J I'd like to add a comma after first word so it updates to SMITH, JOHN J
I tried running this but it blew up:
update people
set name = (CHARINDEX(' ', 0), 0, ',')
I know I'm close but it's eluding me :(
You can use STUFF() along with CHARINDEX() and LEFT() for this:
update people
set name = STUFF(name,1,CHARINDEX(' ',name )-1,LEFT(name ,CHARINDEX(' ',name )-1)+', ')
WHERE CHARINDEX(' ',name) > 0
Might add a WHERE to ensure there is a space in the name so it doesn't error, or a CASE expression.
Could also use REPLACE() with CHARINDEX() and LEFT():
REPLACE(name,LEFT(name,CHARINDEX(' ',name)-1),LEFT(name,CHARINDEX(' ',name)-1)+',')

extracting last name from a name string in ORACLE DB

I am writing a small query to extract all last names from a bunch of Author name database. Names on file will contain first and middle name, or just first name.
Ex: John Smith
John T. Smith
So I cannot search purely by just after the first space... But I know for sure that the lastname should be from the END to the first space from the right side of the string. I don't really care about first name.
This is what I currently have...
select [name], LEFT([name], CHARINDEX(' ', [name] + ' ')-1) as firstName,
SUBSTRING([name], charindex(' ', [name]+' ') + 1, LEN([name])) as lastName
from Author
;
I am quite new to sql, any help is highly appreciated!
Thanks in advance!
EDIT: for those who ever come across this need for help, this line helps:
select substr(t.string,instr(t.string,' ',-1)+1) last_word
For Oracle DB try this :
WITH t AS
(SELECT name AS l FROM <your query>
)
SELECT SUBSTR(l,instr(l,' ',-1)+1,LENGTH(l)) FROM t;
SUBSTRING_INDEX() should work in this case.
select name, SUBSTRING_INDEX(name,' ',-1) as lastName from Author;

how to split a column into multiple value using sql

If I have thousands of rows with data and I would like to find out if the column called "Last
Name " contains both First Name and Last Name (could be middle initial too). What SQL command
do I use ? (SQL Server 2008). Once I find it, how do I split the Last Name field and place
first name or middle initial in their own columns ?
For example:
First Name MI Last Name
John B. Smith
Karen A. Jones
Jane Lawrence
Joan K. Bates
Could it be done in Excel as well ?
You could look for spaces in the last name:
select *
from t
where lastname like '% %';
You could look for rows where the first name is missing:
select *
from t
where firstname is null or firstname = '';
EDIT:
If we assume that the names are "simple" as given in the sample data, you can do:
update t
set firstname = left(lastname, charindex(' ', lastname) - 1),
lastname = right(lastname, charindex(' ', reverse(lastname))),
mi = (case when lastname like '% % %'
then rtrim(ltrim(substring(lastname, charindex(' ', lastname + 1), 2)))
end)
where lastname like '% %' and firstname is null;
This makes lots of assumptions about the formats . . . that there are no complete middle names, that there are no honorics, that there are no suffixes, that there are no multiple spaces together. But if your data is simple, it should work.
Here is an example of the logic in SQL Fiddle.
I would do it in two passes:
-- Set first name
UPDATE names
SET FirstName = SUBSTR(LastName,1,CHARINDEX(' ',LastName) - 1),
LastName = SUBSTR(LastName,CHARINDEX(' ',LastName) + 1, LEN(LastName))
WHERE FirstNAme IS NULL
AND CHARINDEX(' ',LastName) > 0
-- Set middle name
UPDATE names
SET MI = SUBSTR(LastName,1,CHARINDEX(' ',LastName) - 1),
LastName = SUBSTR(LastName,CHARINDEX(' ',LastName) + 1, LEN(LastName))
WHERE MI IS NULL
AND CHARINDEX(' ',LastName) > 0
You may have a few false positives but that should get the vast majority of cases.
I would STRONGLY recommend creating a transaction, doing the updates, doing a SELECT to see the results and rolling back the transaction since the update is not reversible.

Update one column from substring of another column

I have an existing column that I would like to take a subset of and insert into a second (new) column in the same table.
e.g. MyTable.[FullName] (existing column) contains a string like "P-13-146 PS - Goodyear - Tire repair"
I created a new column, MyTable.[ShortName] that I want to insert a substring of the value from the first column into ("P-13-146 PS"). The problem is that the length of the substring is different for each full name. The only real consistency is that I want up to the second whitespace character.
I am trying to resolve the following:
UPDATE [MyTable] SET [ShortName] = ???
Try this:
declare #exp varchar(200)
set #exp='P-13-146 PS - Goodyear - Tire repair'
select RTRIM(SUBSTRING(#exp,1,CHARINDEX(' ',#exp,charindex(' ',#exp)+1)))
Just combine the string manipulation functions until you get what you want:
SELECT
CASE WHEN CHARINDEX(' ',FullName, CHARINDEX(' ', FullName)+1) = 0 THEN FullName
ELSE SUBSTRING(FullName, 1, CHARINDEX(' ',FullName, CHARINDEX(' ', FullName)+1)-1)
END ShortName
FROM MyTable
The first part of the CASE statement is for names that have fewer than two spaces.

CONCAT'ing NULL fields

I have a table with three fields, FirstName, LastName and Email.
Here's some dummy data:
FirstName | LastName | Email
Adam West adam#west.com
Joe Schmoe NULL
Now, if I do:
SELECT CONCAT(FirstName, LastName, Email) as Vitals FROM MEMBERS
Vitals for Joe is null, as there is a single null field. How do you overcome this behaviour? Also, is this the default behaviour in MS SQL Server?
Try
ISNULL(FirstName, '<BlankValue>') -- In SQL Server
IFNULL(Firstname, '<BlankValue>') -- In MySQL
So,
CONCAT(ISNULL(FirstName,''),ISNULL(LastName,''),ISNULL(Email,'')) -- In SQL Server
CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,'')) -- In MySQL
would return the same thing without the null issue (and a blank string where nulls should be).
Look at CONCAT_WS
For example:
CONCAT_WS('',NULL,"TEST STRING","TEST STRING 2")
Yields
TEST STRINGTEST STRING 2
This is easier than constructing IFNULL around everything. You can use an empty string as the separator.
In mysql isnull wont work some time. try IFNULL(),
CONCAT(IFNULL(FirstName,''),IFNULL(LastName,''),IFNULL(Email,''))
SELECT ISNULL(FirstName,'')+ISNULL(LastName,'')+ISNULL(Email,'') as Vitals FROM MEMBERS
is recommended, but if you are really hooked on CONCAT, wrap it in {fn } and you can use the ODBC function like:
SELECT {fn CONCAT(ISNULL(FirstName,''), ISNULL(LastName,''), ISNULL(Email,''))} as Vitals FROM MEMBERS
If you need first<space>last but just last when first is null you can do this:
ISNULL(FirstName+' ','') + ISNULL(LastName,'')
I added the space on firstname which might be null -- that would mean the space would only survive if FirstName had a value.
To put them all together with a space between each:
RTRIM(ISNULL(Firstname+' ','') + ISNULL(LastName+' ','') + ISNULL(Email,''))
You can always use the CONCAT_NULL_YIELDS_NULL setting..
just run SET CONCAT_NULL_YIELDS_NULL OFF and then all null concatenations will result in text and not null..
If you get (like I do in MySQL):
#1582 - Incorrect parameter count in the call to native function 'ISNULL'
You can replace ISNULL function by COALESCE:
CONCAT(COALESCE(FirstName,''),COALESCE(LastName,''),COALESCE(Email,''))
Stefan's answer is correct.
To probe a little bit deeper you need to know that NULL is not the same as Nothing. Null represents the absence of a value, or in other words, not defined. Nothing represents an empty string which IS in fact a value.
Undefined + anything = undefined
Good database tidbit to hold onto!
Starting from MS SQL Server 2012 it was introduced CONCAT function
and according to MSDN
Null values are implicitly converted to an empty string. If all the
arguments are null, an empty string of type varchar(1) is returned.
so it's enough to use CONCAT without IsNull
CONCAT(FirstName, LastName, Email)
SQL Server does not have a CONCAT function.
(Update: Starting from MS SQL Server 2012 it was introduced CONCAT function)
In the default SQL Server behavior, NULLs propagate through an expression.
In SQL Server, one would write:
SELECT FirstName + LastName + Email as Vitals FROM MEMBERS
If you need to handle NULLs:
SELECT ISNULL(FirstName, '') + ISNULL(LastName, '') + ISNULL(Email, '') as Vitals FROM MEMBERS
In the case of MS Access
Option 1) SELECT (FirstName + " " + LastName + " " + Email) as Vitals FROM MEMBERS
You will get blank result in the case of any field with null.
Option 2) SELECT (FirstName & " " & LastName & " " & Email) as Vitals FROM MEMBERS
You will get Space in place of field with null.
After observing the answers for this question, you may combine all of them into one simple solution
CONCAT_WS(',',
IF(NULLIF(FirstName, '') IS NULL, NULL, FirstName),
IF(NULLIF(LastName, '') IS NULL, NULL, usr_lastname),
IF(NULLIF(Email, '') IS NULL, NULL, Email))
So, in short we use CONCAT_WS to concatenate our fields and separate them with ,; and notice that NULL fields nor EMPTY wont concatenated
NULLIF will check if the field is NULL or EMPTY, a field that contains only spaces or is empty as well, ex: '', ' ') and the output will be either NULL or NOT NULL
IF Will out put the field if it's not NULL or EMPTY