How to remove all spaces between a column field?. The spaces occur in the middle of the text so trim won't work and also replace is not working.
my code is
UPDATE temp_emp t1, master_employee t2
SET t1.lm= t2.emp_id
where REPLACE(t1.lm, ' ', '') = REPLACE(CONCAT(t2.first_name,'',t2.last_name), ' ', '');
for example when i run the query ,
select REPLACE(lm, ' ', '') AS concat from temp_emp1
i get the output as follows
concat
----------------------------------------
rick joe
james cole
albert Th
i want the output to be ;like this
concat
----------------------------------------
rickjoe
jamescole
albertTh
Without knowing the table structures and data, it is difficult for me to follow what you are doing. However, to accomplish the ouput of two concatenated columns is very straightforward.
Assume you have a table master_employee with just two columns and you want to output the FIRST and LAST names concatenated with no spaces in between. You simply use the function concat()for MySQL:
SELECT CONCAT(first_name, last_name)
from master_employee;
In Oracle, the concatenation is two pipes (||):
SELECT first_name || last_name
from master_employee;
Hope this helps.
If you want to update the existing column which has multiple spaces into one then this update query will be helpful:
UPDATE your_table SET column_that_you_want_to_change=
REGEXP_REPLACE(column_that_you_want_to_change, '[[:space:]]+', ' ');
If you don't want any spaces then this should work:
UPDATE your_table SET column_that_you_want_to_change=
REGEXP_REPLACE(column_that_you_want_to_change, '[[:space:]]+', '');
Related
I have a column that contains a string of comma delimited values. I use FIND_IN_SET to query this column and it works fine until there is a space between the value and the ,. I cannot control the input. The only solution I have found that works is by running REPLACE on the column within the FIND_IN_SET function. Unfortunately this will remove all spaces and could return undesired results.
The blow example would return both row in the table as opposed to the first one only.
col1 | col2
carpet , foo, bar | myVal1
abc, 123 , car pet | myVal2
Query
SELECT FIND_IN_SET('carpet', REPLACE(col1, ' ', ''));
Is there a way of limiting this to only trim the space wither side of the ,
You could try replacing ,[ ] or [ ], with just comma:
SELECT
col1,
col2,
FIND_IN_SET('carpet', REPLACE(REPLACE(col1, ', ', ','), ' ,', ',')) AS output
FROM yourTable;
Demo
Note: This answers assumes that there would be at most one leading/trailing space around the commas, and that your actual data itself does not contain commas. If there could arbitrary amount of whitespace, this answer would fail. In that case, what you would really need is regex replacement. MySQL 8+ does support this, but a better bet would be to normalize your data and stop storing CSV data like this.
I'd like to make an SQL query where the condition is that column1 contains three or more words. Is there something to do that?
maybe try counting spaces ?
SELECT *
FROM table
WHERE (LENGTH(column1) - LENGTH(replace(column1, ' ', ''))) > 1
and assume words is number of spaces + 1
If you want a condition that a column contains three or more words and you want it to work in a bunch of databases and we assume that words are separated by single spaces, then you can use like:
where column1 like '% % %'
I think David nailed it above. However, as a more complete answer:
LENGTH(RTRIM(LTRIM(REPLACE(column1,' ', ' ')))) - LENGTH(REPLACE(RTRIM(LTRIM(REPLACE(column1, ' ', ' '))), ' ', '')) + 1 AS number_of_words
This will remove double spaces, as well as leading and trailing spaces in your string.
Of course, you may go further by adding replacements for more than 2 spaces in a row...
In Postgres you can use regexp_split_to_array() for this:
select *
from the_table
where array_length(regexp_split_to_array(the_column, '\s+'), 1) >= 3;
This will split the contents of the column the_column into array elements. One ore more whitespace are used as the delimiter. It won't respect "quoted" spaces though. The value 'one "two three" four' will be counted as four words.
The best way to do this, is to NOT do this.
Instead, you should use the application layer to count the words during INSERT and save the word count into its own column.
While I like, and upvoted, some of the answers here, all of them will be very slow and not 100% accurate.
I know people want a simple answer to SELECT the word count, but it just is NOT POSSIBLE with accuracy and speed.
If you want it to be 100% accurate, and very fast, then use this solution.
Steps to solve:
Add a column to your table and index it: ALTER TABLE tablename ADD COLUMN wordcount INT UNSIGNED NULL, ADD INDEX idxtablename_count (wordcount ASC);.
Before doing your INSERT, count the number of words using your application. For example in PHP: $count = str_word_count($somevalue);
During the INSERT, include the value of $count for the column wordcount like insert into tablename (col1, col2, col3, wordcount) values (val1, val2, val3, $count);
Then your select statement becomes super easy, clean, uber-fast, and 100% accurate.
select * from tablename where wordcount >= 3;
Also remember when you are updating any rows that you will need to recount the words for that column.
For "n" or more words
select *
from table
where (length(column)- length(replace(column, " ", "")) + 1) >= n
PS: This would not work if words have multiple spaces between them.
With ClickHouse DB You can use splitByWhitespace() function.
Refer : https://clickhouse.com/docs/en/sql-reference/functions/splitting-merging-functions#splitbywhitespaces
None of the other answers seem to take multiple spaces into account. For example, a lot of people use two spaces between sentences; these space-counters would count an extra word per sentence. "Also, scenarios such as spaces around a hyphen - like that. "
For my purposes, this was far more accurate:
SELECT
LENGTH(REGEXP_REPLACE(myText, '[ \n\t\|\-]{1,}',' ')) -
LENGTH(REGEXP_REPLACE(myText, '[ \n\t\|\-]{1,}', '')) wordCount FROM myTable;
It counts any sets of 1 or more consecutive characters from any of: [space, linefeed, tab, pipe, or hyphen] and counts it as one word.
This can work:
SUM(LENGTH(a) - LENGTH(REPLACE(a, ' ', '')) + 1)
Where a is the string column. It will count the number of spaces, which is 1 less than the number of words.
To handle multiple spaces too, use the method shown here
Declare #s varchar(100)
set #s=' See how many words this has '
set #s=ltrim(rtrim(#s))
while charindex(' ',#s)>0
Begin
set #s=replace(#s,' ',' ')
end
select len(#s)-len(replace(#s,' ',''))+1 as word_count
https://exploresql.com/2018/07/31/how-to-count-number-of-words-in-a-sentence/
my raw query look something like this-
UPDATE main,category,sub_category
SET main.biz_keyword = (category.category','sub_category.sub_cat_name','main.biz_keyword)
so the result something like main.biz_keyword='Doctor,General Physician,Physician'
I know this is wrong query but you got the Idea what I am looking for,
So my question is that I can do this by single query?
You might want to have a look at using CONCAT_WS(separator,str1,str2,...)
CONCAT_WS() stands for Concatenate With Separator and is a special
form of CONCAT(). The first argument is the separator for the rest of
the arguments. The separator is added between the strings to be
concatenated.
is this something you want to achieve?
Update TableName
set biz_keyword = category.category + ',' + sub_category.sub_cat_name + ',' + main.biz_keyword
Maybe you're looking for something like this?
UPDATE
main
SET
biz_keyword = CONCAT_WS(', ',
(SELECT category FROM category WHERE ... ),
(SELECT sub_cat_name FROM sub_category WHERE ... ),
biz_keyword)
I need to fetch data from database for backup in the form of insert statements
I need to do it on a button click in c#. So i think an sql query or stored procedure will be appropriate to do this, rather than mysqldump.
Secondly I need them for all tables. Instead of writing table and column names. They should be fetched from information_schema, because the query will not need to be changed for different scema
If there already exists a solution, please guide me.
Update : I have prepared a solution, it is posted, still looking for the better one.
To get Data of whole database - SqlFiddle Demo
To get data of only one table - - SqlFiddle Demo
I have made a complex but acceptable solution. But needs improvement.
This is a complex procedure with complex coding especially the query which fetches all rows of all columns into a single result by group_concat and formats with a complex concatenation.
Need it simplified, efficient and working in all scenarios.
Some details of my solution : Following is the important part, other is just conditions/Looping (I am not handy with documentation also it needs time and suggestions, someone might help me in its formatting and improvement, Sorry for any inconvenience, however I will be glad for any help from you and me)
Note: group_concat(yourColumn separator ' --anySeparator-- ') is merging all rows of your column as one such that Rows are separated by --anySeparator--
select group_concat(column_name separator '`,`') into #cns1 from
information_schema.columns where table_schema=dn and table_name=#tn;
1 : column_names are got as a single value separated by
`,` => #cs1 = id`,`ename`,`did
select group_concat(column_name separator '`,"\',\'",`') into #cns2
from information_schema.columns where table_schema=dn and table_name=#tn;
2 : column_names are got as a single value separated by
`','` => #cn2 = id`','`ename`','`did
set #cns1=concat("`",#cns1,"`"); set #cns2=concat("`",#cns2,"`");
3: Missing letter (`) is put at beginning and end of Column names
set #res=concat(#res," insert into ",#tn,"(",#cns1,") values ('");
4: Simply makes res= " insert into emp(`id` , `ename` ,`did` ) values(" Here you can see why have I put separators (MySql Formatting is achieved)
set #temp := '';
set #q := concat("select group_concat(concat(",#cns2,") separator \"'),('\")
from ",dn,".",#tn, " into #temp");
Above is the most crucial statement It gets all data rows from table as rows of a single column and further these rows are merged being separated by '),('
5.1 concat(",#cns2,") gets values of all columns in a single one.
5.2 After outer most concat now #q is
#q = "select group_concat(`id`','`ename`','`,did` separator '),(' from
mydb.emp into #temp";
5.3 : group_concat will merge all rows of that combined column into one value.
Columns values will be joined through separators existing in #cns2 and rows level joining will be with '),('
prepare s1 from #q;
execute s1;deallocate prepare s1;
set #res = concat(#res,#temp,");");
#q is executed
set #res = concat(#res,#temp,");");
6 : And We will get result as
res was = insert into emp(`id`,`ename`,`did`) values ('
#temp = 1','e1','4'),('2','e2','4'),
('3','e3','2'),('4','e4','4'),('5','e5','3
And after #res = concat(#res,#temp,");"); we get
insert into emp(`id`,`ename`,`did`) values ('1','e1','4'),('2','e2','4'),
('3','e3','2'),('4','e4','4'),('5','e5','3);
select concat("insert into users (id,name,password) values ('",id,"'"),
concat(",'",username,"'"),
concat(",'",password,"'),") INTO OUTFILE 'c:\\datas\\asd.txt' from users
I have in a column names(notes) as
Notes:
John's Table
Smith's Window
Column contains an apostrophe in it. I am trying to run 2 queries.
Select query to get the column entries that have apostrophe.
Update those with apostrophe with empty string ie.John's Table replace to John Table
select notes from table1 where notes like ' '% ';
I get a syntax error , any help will be great.
Escape the apostrophe with a backslash;
select notes from table1 where notes like '%\'%';
And to update, use REPLACE()
UPDATE table1 SET notes = REPLACE(notes, '\'', '');
Did you try:
select notes from table1 where notes like "'%";