SQL split column data - sql

I have a column in my table called display name and the data looks like this John Smith I am looking to see if there is away to split the data like so:
display name as first name => John, display name as last name => Smith
Is this possible?

Assuming MySQL, something like this should work if you always have a single space.
SELECT Substr(name, 1, Instr(name, ' ')) as FirstName,
Substr(name, Instr(name, ' ')) as LastName
FROM DisplayName
Here is some sample Fiddle that shows you how it works (and when it doesn't).
Good luck.

There are multiple solutions available for this common issue. If you are just querying the DB, then you can use the example provided by #sgeddes.
Now if you would like to take the values you get from that query and put it, in its own column, you will want to create a new column;
alter table table_name
add column first_name varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL
after col_name;
⬆️ The after statement help you choose the location of your new column.
Then you can update said column with an update statement;
update table_name
set first_name = SUBSTRING_INDEX(SUBSTRING_INDEX(display_name, ' ', 1), ' ', -1)
This worked for me. Good luck 🍀

Related

SQL query: choosing only the first word in a column

I am using PostgreSQL and Windows.
I have column data that looks like this:
Table name: employees
I need to run an SQL query where the result will:
Display only FullName column.
Display ONLY THE FIRST WORD of each name in the column.
What would be the SQL query?
There are all sorts of string functions described here String operators/functions. One that would work is:
select split_part('Adrian Klaver', ' ', 1);
split_part
------------
Adrian
--So in your case
Select split_part("FullName", ' ', 1) from employees;

Generated columns in Postgres using a given pattern

I need to generate a SQL query which can generate a column that follows a certain pattern
The pattern is stored like this Hello [Name] [lastname]
where name and lastname are both columns on the table.
How do i add a constant string at end, start and indbetween attributes?
and how do distinguish between something being a table column and something just being a string i have added that the column should contain?
My query currently looks like this - and pattern then take
ALTER TABLE IF public.nameRegistration
DROP COLUMN IF EXISTS generated_colum
ADD COLUMN generated_colum TEXT generated ALWAYS as (|Pattern|) stored;
and pattern is just Hello Name lastname
You would just do string concatenation:
ALTER TABLE ADD COLUMN
generated_colum TEXT generated ALWAYS
as ('Hello ' || name || ' ' || lastname) stored;
As commented by a_horse_with_no_name, in case any of the two column may be null you can use concat_ws():
ALTER TABLE ADD COLUMN
generated_colum TEXT generated ALWAYS
as (concat_ws(' ', 'Hello', name, lastname)) stored;

SQL - find rows with values that has 2 spaces or more in between

I have sql table with name and surname. Surname is in own column. The problem is with users with two surnames, because sometimes they add more than one space between surnames and then I have to find and fix them manualy.
How to find these surnames with more than one space in between?
If you want to find records which have more than one space then you can use the following trick:
SELECT surname
FROM yourTable
WHERE LENGTH(REPLACE(surname, ' ', '')) < LENGTH(surname) - 1
This query will detect two or more spaces in the surname column. If you want to also do an UPDATE this is possible, but it would be fairly database-specific, and you did not specify your database as of the time I wrote this answer.
First remove those extra spaces. Then add a constraint that makes sure it doesn't happen again:
alter table tablename add constraint surname_verify check (surname not like '% %')
(Or, even better, have a trigger making sure the surnames are properly spaced, cased etc.)
How to remove extra spaces? Depends on the dbms.
You can perhaps do something like:
update tablename set surname = replace(surname, ' ', ' ')
where surname like '% %'
The where clause isn't needed, but makes the transaction much smaller.
(Iterate to get rid of triple or more spaces.) Or use regexp_replace.
Even tidier:
select string = replace(replace(replace(' select single spaces',' ','<>'),'><',''),'<>',' ')
Output:
select single spaces

Add a Column that Represents a Concatenation of Two Other Varchar Columns

I have an employees table and I want to add a third column valued as the concatenation of the first and last name called "FullName". How can I accomplish that without losing any data from either of the first two columns?
Quick preface: this answer was based on the originally incorrect tag that this question was relating to SQL Server. I'm no longer aware of its validity on Oracle SQL Developer.
ALTER TABLE Employees ADD FullName AS (FirstName + ' ' + LastName)
Although in practice I'd advise that you do that operation in your SELECT. That's somewhat personal preference, but I tend to think doing things in your end queries is a bit cleaner, more readable, and easier to maintain than storing extra, calculated columns.
Edit:
This was eventually found as the answer, and listed by the OP as a comment on this post. The following is appropriate syntax for Oracle Sql Database.
ALTER TABLE emps MODIFY (FULL_NAME VARCHAR2(50) GENERATED ALWAYS AS (first_name || ' ' || last_name) VIRTUAL);
If you need fullname column all time when you select from database then you can create computed column at the time of creation of your table employee.
for example:
CREATE TABLE Employee
(
FirstName VARCHAR(20),
LastName VARCHAR(20),
FullName AS CONCAT(FirstName,' ',LastName)
)
INSERT INTO Employee VALUES ('Rocky','Jeo')
SELECT * FROM Employee
Output:
FirstName LastName FullName
Rocky Jeo Rocky Jeo
It depends on your purpose, whether you really need to add a new column to your database, or you just need to query out the "full name" on an as-needed basis.
To view it on the fly, just run the query
SELECT firstname + ' ' + lastname AS FullName FROM employees
Beyond that, you also can create a simple Stored Procedure to store it.
(For single result use equal to in the where condition)
select *
from TABLE_name
where (Column1+Column2) in (11361+280,11365+250)
In addition to #Jacky 's answer, if you are trying to add this to a query and not the table, there is also the CONCAT() function that you can use in the select statement
SELECT CONCAT(FirstName, ' ', LastName) as FullName
FROM table_name

How do I do a case sensitive comparison in sql?

Just started a tutorial in SQL for beginners. I'm doing some exercises now and I would like to know how to change the title.
If you look at here: you'll see that I have made firstname, lastname, title, age and salary. And I wrote the letters in small letter.
How can I change it to capital letter?
http://tinypic.com/r/amtpgm/3
I tried using this:
update mytablename
set firstname = 'Firstname'
where firstname = 'firstname'
But I later realized that this one will not work.
Thanks
====
additional question:
I also notice that if I wrote with spaces, then its not recognized. It's the first part only which will be displayed. Do you know why is it doing? Thanks
create table myemployees_tr0214
(First Name varchar(20),
Last Name varchar(20),
Title char(5),
Age number(3),
Salary number(6,10));
==========
thank you for all your inputs.
I've tried this one in renaming the "Firstname" to "Fname" and it didn't work. Did I miss something?
alter table myemployees_tr0214
rename column Firstname to Fname;
This should update all the firstnames in the table to an uppercase first letter:
UPDATE mytablename SET firstname = CONCAT(UCASE(MID(firstname,1,1)),MID(firstname,2));
Hope this helps you :)
First, unless you really want to change the names of the fields, don't. It's not really all that important if all you're doing is learning SQL. Note that if you want to learn the syntax for doing so, then of course it would be a worthwhile exercise, but other than that, I'd let it be.
Your edited question mentions using spaces in names. This is not allowed. The rules for what constitutes a "SQL Identifier", be it the name of a table, column, constraint, etc. has some strict rules, and simplified they are that you should only use letters, underscores, and digits, except that you can't start with a digit.
Now, why the online website that you're using to learn SQL through doesn't complain when you add those spaces, that I don't know, and to me that makes it a little suspect. It doesn't sound as though it actually uses a known database engine, as just the presence of those spaces there + the extra words would make any normal database engine complain about bad syntax.
In order to fix it, either add underscores instead of spaces, or contract and use camelCasing, like this: FirstName, LastName
Ah, there are two ways to read this question. The first is based on reading the sample UPDATE you posted. This will fail because SQL by default doesn't do a case sensitive comparison on strings.
The second piece of code implies what you wanted was to ALTER TABLE and change the name of the column from a column name with one casing to another. In MS-SQL, you can't do that without dropping the whole table and re-creating it, in other dialects of SQL there will be version specific DDL syntax.
And finally, in MS-Access, if a column name has a space, you wrap it in double quotes, e.g. "My Column" in SQL wrap it in [My Column]
update mytablename set firstname = 'Firstname'; where firstname = 'firstname';
This will update the values of the firstname column. What you are trying to do is change the name of the firstname column. How to do this depends on the database you're using (which you haven't mentioned).
If it's MS Access or SQL server, you can open the table in the UI and use the designer to change the column name.
Otherwise you can use the SQL ALTER TABLE statement, as described here.
For MS SQL Server...
You'd use [ and ] to delimit identifiers:
create table myemployees_tr0214 (
[First Name] varchar(20), --here
[Last Name] varchar(20), --here
Title char(5),
Age number(3),
Salary number(6,10)
);
If you want to change the column name from "firstname" to "Firstname", you could use sp_rename in MS SQL Server.
If you want to change the first letter of the data in the "firstname" column, other posters have offered solutions and here's another for a single name.
update mytablename
set firstname = 'Firstname'
where firstname COLLATE Latin1_general_Bin = 'firstname' COLLATE Latin1_general_Bin
If you're using mysql see: http://dev.mysql.com/doc/refman/5.0/en/charset-binary-op.html
The BINARY operator casts the string
following it to a binary string. This
is an easy way to force a comparison
to be done byte by byte rather than
character by character. BINARY also
causes trailing spaces to be
significant
mysql> SELECT 'a' = 'A';
-> 1
mysql> SELECT BINARY 'a' = 'A';
-> 0
mysql> SELECT 'a' = 'a ';
-> 1
mysql> SELECT BINARY 'a' = 'a ';
-> 0
you'll need some kind of unique row indentifier like id so you can do
update mytablename set firstname = 'Firstname' where id = 1
now what can be used as a unique row indentifier is a huge debate of natural vs surrogate keys. use what you think is best for your example but i'm a supporter of surogate keys since every natural key has the possibility to change.
This may need to be optimize for more but it will allow you to even update mulitple first name MSSQL version
select 'mary ellen' as firstname into #test
insert into #test select 'Nathan'
select
Case when patindex('% %',firstname) >0 then
upper(left(firstname,1)) --first letter
+ rtrim(substring(firstname,2,patindex('% %',firstname)-1)) --whole firstname
+ ' ' -- space
+ Upper(substring(firstname,patindex('% %',firstname)+1,1)) --first letter last name
+ rtrim(substring(firstname,patindex('% %',firstname)+2, len(firstname)))
else
upper(left(firstname,1)) + substring(firstname,2,len(firstname))
end as firstname
from #test
update #test
set firstname = Case when patindex('% %',firstname) >0 then
upper(left(firstname,1)) --first letter
+ rtrim(substring(firstname,2,patindex('% %',firstname)-1)) --whole firstname
+ ' ' -- space
+ Upper(substring(firstname,patindex('% %',firstname)+1,1)) --first letter last name
+ rtrim(substring(firstname,patindex('% %',firstname)+2, len(firstname)))
else
upper(left(firstname,1)) + substring(firstname,2,len(firstname))
end