querying WHERE condition to character length? - sql

I have a database with a large number of words but i want to select only those records where the character length is equal to a given number (in example case 3):
$query = ("SELECT * FROM $db WHERE conditions AND length = 3");
But this does not work... can someone show me the correct query?

Sorry, I wasn't sure which SQL platform you're talking about:
In MySQL:
$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");
in MSSQL
$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");
The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.
Edit
I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.
So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():
CREATE TABLE words (
word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;
INSERT INTO words(word) VALUES('快樂'), ('happy'), ('hayır');
SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;
+--------+-----------+----------------+
| word | num_bytes | num_characters |
+--------+-----------+----------------+
| 快樂 | 6 | 2 |
| happy | 5 | 5 |
| hayır | 6 | 5 |
+--------+-----------+----------------+
Be careful if you're dealing with multi-byte characters.

I think you want this:
select *
from dbo.table
where DATALENGTH(column_name) = 3

SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";

Related

How to replace rows containing alphabets and special characters with Blank spaces in snowflake

I have a column "A" which contains numbers for example- 0001, 0002, 0003
the same column "A" also contains some alphabets and special characters in some of the rows for example - connn, cco*jjj, hhhhhh11111 etc.
I want to replace these alphabets and special characters rows with blank values and only want to keep the rows containing the number.
which regex expression I can use here?
If you want to extract numbers from these values (even if they end or start with non digits), you may use something like this:
create table testing ( A varchar ) as select *
from values ('123'),('aaa123'),('3343'),('aaaa');
select REGEXP_SUBSTR( A, '\\D*(\\d+)\\D*', 1, 1, 'e', 1 ) res
from testing;
+------+
| RES |
+------+
| 123 |
| 123 |
| 3343 |
| NULL |
+------+
I understand that you want to set to null all values that do not contain digits only.
If so, you can use try_to_decimal():
update mytable
set a = null
where a try_to_decimal(a) is null
Or a regexp match:
update mytable
set a = null
where a rlike '[^0-9]'

SQL: Select rows that contain a word

The goal is to select all rows that contain some specific word, can be in the beginning or the end of the string and/or surrounded by white-space, should not be inside other word, so to speak.
Here are couple rows in my database:
+---+--------------------+
| 1 | string with test |
+---+--------------------+
| 2 | test string |
+---+--------------------+
| 3 | testing stringtest |
+---+--------------------+
| 4 | not-a-test |
+---+--------------------+
| 5 | test |
+---+--------------------+
So in this example, selecting word test, should return rows 1, 2 and 5.
Problem is that for some reason, SELECT * FROM ... WHERE ... RLIKE '(\s|^)test(\s|$)'; returns 0 rows.
Where am I wrong and maybe, how it could be done better?
Edit: Query should also select the row with just a word test.
The answer to my first question is:
I haven't escaped special characters, so \s should be \\s.
Working query: SELECT * FROM ... WHERE ... RLIKE '(\\s|^)test(\\s|$)';. (or just a space ( |^)/( |$), also works)
Hi you could grab with trailing space and with leading space
SELECT * from new_table
where text RLIKE(' test')
union
SELECT * from new_table
where text RLIKE('test ')
REGEXP_INSTR() function, which's is an extension of the INSTR() function, might be used for version 10.0.5+ case-insensitively as default :
SELECT *
FROM t
WHERE REGEXP_INSTR(str, 'TeSt ')>0
OR REGEXP_INSTR(str, ' tESt')>0
Demo
SELECT * FROM ...
WHERE ... LIKE 'test';
This should do the trick.
Is this what you want?
SELECT * FROM ... WHERE ... LIKE
'%test%';
Use word boundary tests:
Before MySQL 8.0, and in MariaDB:
WHERE ... REGEXP '[[:<:]]test[[:>:]]'
MySQL 8.0:
WHERE ... REGEXP '\btest\b'
(If that does not work, double up the backslashes; this depends on whether the client is collapsing backslashes before MySQL gets them.)
Note that this solution will also work with punctuation such as the comma in "foo, test, bar"

A query with a reverse LIKE condition

There is a table with column name "phone" and has different numbers in different formats.
Example:
id | number
1 | 03439879098
2 | 01109890032
3 | +91 932 3233237
Now if I want to search "3233237" then the query will be:
select * from table where number like '%3233237%';
Result will be:
id | number
3 | +91 932 3233237
But in my case I want the reverse
String search = "+92 343 9879098"
select * from table where number like search
The result should be:
id | number
1 | 03439879098
Because the column number and search string has a common string, which is 9879098.
Query should be designed in such a way that it looks for a record that both search string and column value has a common sub string
Kindly give me some idea.
This was a tricky one. You can do it in pure SQL executing:
select * from table where '+92 343 9879098' like '%' || number || '%';
Here we're concatenating the number column with the wildcards %.
*Also You could resolve it programatically:
String search = "+92 343 9879098";
String query = "select * from table where ";
String[] parts = search.split( "\\s+" );
for ( String oneNumber : parts ) {
query += " number like '%" +oneNumber+ "%' OR";
}
query += " false"; // this, or trim the last OR calculating the string length
Cheers.
Have you tried NOT LIKE so it'd be something like
select * from table where name not like search

SQL update statement to change the value of a field and not replace it

I'm in the process of migrating some databases. I have this table that has a couple of hundred rows, and has a filename column. To each record in this table, the filename column needs to be altered and part of a path needs to be prepended to the value that is in that field.
The table is like:
| 1 | filename1 |
| 2 | filename2 |
and needs to become:
| 1 | path/filename1 |
| 2 | path/filename2 |
I am not an SQL guru, but I know the basics. This eludes me though. Is there a way to do something like:
update table
set filename = 'path/' + filename
where id = 1;
You pretty much have it right there. You don't need to specify a where clause if you want to do it for all the rows, so then it would just be:
update table set filename = 'path/' || filename;
(|| is the concatenation operator in PostgreSQL)
They have told you how to write teh concatenation, I suggest you run this selct first to see waht your results will be:
select filename, 'path/'|| filename from table
where id = 1;
I think this should work:
UPDATE table SET filename = CONCAT("path/", filename);
UPDATE table
SET filename = 'path/' || filename
WHERE id = 1

Select all table entries which have a fully capitalized string in a specific column?

I have a database table with a few thousand entries. A part of the entries (~20%) have been entered with a fully capitalized strings in the 'name' column.
Example:
id | name
---------
1 | THOMAS GOLDENBERG
2 | Henry Samuel
3 | GIL DOFT
4 | HARRY CRAFT
5 | Susan Etwall
6 | Carl Cooper
How would an SQL query look like that selects all entries with a fully capitalized string in the name column? (i.e. in the example: those with the ID 1,3,4)
In MySQL it would be:
SELECT id FROM table WHERE name = UPPER(name);
I think this would work the same way in SQL Server, DB2 and Postgres.
What database system?
In theory you can do a simple SELECT ... WHERE name = UPPER(name); but that does not always work. Depending on the collation of your data, you may found that all records satisfy this condition because the comparison used may be case insensitive.
You need to ensure you compare using a case sensitive collation, and the correct answer depends on the database platform you use. For example, using SQL Server syntax:
SELECT ... WHERE Name COLLATE Latin1_General_100_CS_AS = UPPER(Name);
This also works in MySQL with the condition that you use a collation name valid on MySQL.
select * from your_table where name = upper(name)
Here's a MySql function to convert uppercase to title case:
example:
update your_table set name = tcase(name) where name = upper(name);
function:
CREATE FUNCTION `tcase`(str text) RETURNS text CHARSET latin1
DETERMINISTIC
BEGIN
DECLARE result TEXT default '';
DECLARE space INT default 0;
DECLARE last_space INT default 0;
IF (str IS NULL) THEN
RETURN NULL;
END IF;
IF (char_length(str) = 0) THEN
RETURN '';
END IF;
SET result = upper(left(str,1));
SET space = locate(' ', str);
WHILE space > 0 DO
SET result = CONCAT(result, SUBSTRING(str, last_space+2, space-last_space-1));
SET result = CONCAT(result, UPPER(SUBSTRING(str, space+1, 1)));
SET last_space = space;
SET space = locate(' ', str, space+2);
END WHILE;
SET result = CONCAT(result, SUBSTRING(str, last_space+2));
RETURN result;
END $$
DELIMITER ;