SQL query comparison - sql

1) select name from city where countrycode="JPN" ;
2) select name from city where countrycode='JPN' ;
3) select name from city where countrycode="jPn" ;
all the above queries are working in query 2 i am using single quotes and in 3 query i am using mixture of upper case and lowercase character . why it is producting correct output??.

I guess I misread the original question. Some database implementations are case insensitive are some aren't. Usually reserved keywords like SELECT, WHERE, etc.. are case-insensitive.
It might be worth forcing to lower or uppercase for your WHERE clause.
Consider using LOWER or UPPER to force lower or upper case
SELECT name from city where LCASE(countrycode) = "jpn"
I haven't used it personally so it might be worth benchmarking for speed.

Related

How run Select Query with LIKE on thousands of rows

Newbie here. Been searching for hours now but I can seem to find the correct answer or properly phrase my search.
I have thousands of rows (orderids) that I want to put on an IN function, I have to run a LIKE at the same time on these values since the columns contains json and there's no dedicated table that only has the order_id value. I am running the query in BigQuery.
Sample Input:
ORD12345
ORD54376
Table I'm trying to Query: transactions_table
Query:
SELECT order_id, transaction_uuid,client_name
FROM transactions_table
WHERE JSON_VALUE(transactions_table,'$.ordernum') LIKE IN ('%ORD12345%','%ORD54376%')
Just doesn't work especially if I have thousands of rows.
Also, how do I add the order id that I am querying so that it appears under an order_id column in the query result?
Desired Output:
Option one
WITH transf as (Select order_id, transaction_uuid,client_name , JSON_VALUE(transactions_table,'$.ordernum') as o_num from transactions_table)
Select * from transf where o_num like '%ORD12345%' or o_num like '%ORD54376%'
Option two
split o_num by "-" as separator , create table of orders like (select 'ORD12345' as num
Union
Select 'ORD54376' aa num) and inner join it with transf.o_num
One method uses OR:
WHERE JSON_VALUE(transactions_table, '$.ordernum') LIKE IN '%ORD12345%' OR
JSON_VALUE(transactions_table, '$.ordernum') LIKE '%ORD54376%'
An alternative method uses regular expressions:
WHERE REGEXP_CONTAINS(JSON_VALUE(transactions_table, '$.ordernum'), 'ORD12345|ORD54376')
According to the documentation, here, the LIKE operator works as described:
Checks if the STRING in the first operand X matches a pattern
specified by the second operand Y. Expressions can contain these
characters:
A percent sign "%" matches any number of characters or
bytes.
An underscore "_" matches a single character or byte.
You can escape "\", "_", or "%" using two backslashes. For example, "\%". If
you are using raw strings, only a single backslash is required. For
example, r"\%".
Thus , the syntax would be like the following:
SELECT
order_id,
transaction_uuid,
client_name
FROM
transactions_table
WHERE
JSON_VALUE(transactions_table,
'$.ordernum') LIKE '%ORD12345%'
OR JSON_VALUE(transactions_table,
'$.ordernum') LIKE '%ORD54376%
Notice that we specify two conditions connected with the OR logical operator.
As a bonus information, when querying large datasets it is a good pratice to select only the columns you desire in your out output ( either in a Temp Table or final view) instead of using *, because BigQuery is columnar, one of the reasons it is faster.
As an alternative for using LIKE, you can use REGEXP_CONTAINS, according to the documentation:
Returns TRUE if value is a partial match for the regular expression, regex.
Using the following syntax:
REGEXP_CONTAINS(value, regex)
However, it will also work if instead of a regex expression you use a STRING between single/double quotes. In addition, you can use the pipe operator (|) to allow the searched components to be logically ordered, when you have more than expression to search, as follows:
where regexp_contains(email,"gary|test")
I hope if helps.

Remove unnecessary Characters by using SQL query

Do you know how to remove below kind of Characters at once on a query ?
Note : .I'm retrieving this data from the Access app and put only the valid data into the SQL.
select DISTINCT ltrim(rtrim(a.Company)) from [Legacy].[dbo].[Attorney] as a
This column is company name column.I need to keep string characters only.But I need to remove numbers only rows,numbers and characters rows,NULL,Empty and all other +,-.
Based on your extremely vague "rules" I am going to make a guess.
Maybe something like this will be somewhere close.
select DISTINCT ltrim(rtrim(a.Company))
from [Legacy].[dbo].[Attorney] as a
where LEN(ltrim(rtrim(a.Company))) > 1
and IsNumeric(a.Company) = 0
This will exclude entries that are not at least 2 characters and can't be converted to a number.
This should select the rows you want to delete:
where company not like '%[a-zA-Z]%' and -- has at least one vowel
company like '%[^ a-zA-Z0-9.&]%' -- has a not-allowed character
The list of allowed characters in the second expression may not be complete.
If this works, then you can easily adapt it for a delete statement.

Regular Expression "a{2}" not working

I have a record with emp_name = "Rajat" and it is not getting returned.
My query is -
SELECT * FROM employees WHERE emp_name regexp "a{2}"
Please explain why it is not working
Your regex search for aa
https://www.regex101.com/r/yA1qA2/1
What you need is:
a.*a
https://www.regex101.com/r/hA5yS8/1
a{2} means two consecutive as. Your string doesn't match it.
To match a string with two a characters that might not be consecutive characters you should use a.*a.
a{2} will match two straight a characters, i.e.: aa.
To match 2 alternate a characters you can use:
select * from employees where emp_name REGEXP "^.*a.*a.*$";
I think all you need is LIKE with %:
LIKE - Simple pattern matching
Character Description
% Matches any number of characters, even zero
characters
_ Matches exactly one character
LIKE pattern match... succeeds only if the pattern matches the entire value
So, you can use a more specific
select * from employees where emp_name like '%a_a%';
Or, a more "generic" (allowing more characters than 1 between a and a:
select * from employees where emp_name like '%a%a%';
However, since in MySQL, SQL patterns are case-insensitive by default, so, you might have to use REGEXP with BINARY to narrow down your search results:
Prior to MySQL 3.23.4, REGEXP is case sensitive.
From MySQL 3.23.4 on, if you really want to force a REGEXP comparison
to be case sensitive, use the BINARY keyword to make one of the
strings a binary string.
SELECT * FROM employees WHERE emp_name REGEXP BINARY 'a.*a';

VB6 Syntax Question

Can anyone tell me what this Asterisk(*) is for. ...tblpersonal where empid like '" & idNumber & "*'". What if I replace it with Percent sign(%), what would be the outcome?
The LIKE condition allows you to use wildcards in the where clause of an SQL statement. This allows you to perform pattern matching. The LIKE condition can be used in any valid SQL statement - select, insert, update, or delete.
The patterns that you can choose from are:
% allows you to match any string of any length (including zero length)
_ allows you to match on a single character
Next, let's explain how the _ wildcard works. Remember that the _ is looking for only one character.
For example,
SELECT * FROM suppliers
WHERE supplier_name like 'Sm_th';
This SQL statement would return all suppliers whose name is 5 characters long, where the first two characters is 'Sm' and the last two characters is 'th'. For example, it could return suppliers whose name is 'Smith', 'Smyth', 'Smath', 'Smeth', etc.
Here is another example,
SELECT * FROM suppliers
WHERE account_number like '12317_';
The same way u can use asterisk (*) instead of (%)
I hope its help to you
The Percent (%) sign in SQL says "match any number of characters here". E.g. LIKE '%test' will match abctest, LIKE 'test%' will match testabc
The Asterisk character looks like it'll match a literal *, e.g. matching all empids ending with an asterisk (depending on the version of SQL - see below)
EDIT: See Microsoft Jet wildcards: asterisk or percentage sign? for a more in depth answer on * vs %
This is much more a SQL syntax question than a VB6 one. :-)
You haven't mentioned what database this is talking to (I assume it's talking to a DB). The asterisk is not generally special in SQL (or VB6 strings), and so that query will look for empid being like whatever's in your idNumber followed by an asterisk. Probably not what was intended. If you replace it with a %, you'll be looking for any empid that starts with whatever's in your idNumber variable. If the column is numeric, it will be converted to text before the comparison.
So for instance, if idNumber contains 100, say, and there are empid values in the database with the values 10, 100, 1000, and 10000, the query would match all but the first of those, since "100", "1000", and "10000" are all like "100%".

Use '=' or LIKE to compare strings in SQL?

There's the (almost religious) discussion, if you should use LIKE or '=' to compare strings in SQL statements.
Are there reasons to use LIKE?
Are there reasons to use '='?
Performance? Readability?
LIKE and the equality operator have different purposes, they don't do the same thing:
= is much faster, whereas LIKE can interpret wildcards. Use = wherever you can and LIKE wherever you must.
SELECT * FROM user WHERE login LIKE 'Test%';
Sample matches:
TestUser1
TestUser2
TestU
Test
To see the performance difference, try this:
SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name
SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name
Comparing strings with '=' is much faster.
In my small experience:
"=" for Exact Matches.
"LIKE" for Partial Matches.
There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):
ILIKE, which is a case insensitive LIKE match:
select * from people where name ilike 'JOHN'
Matches:
John
john
JOHN
And if you want to get really mad you can use regular expressions:
select * from people where name ~ 'John.*'
Matches:
John
Johnathon
Johnny
Just as a heads up, the '=' operator will pad strings with spaces in Transact-SQL. So 'abc' = 'abc ' will return true; 'abc' LIKE 'abc ' will return false. In most cases '=' will be correct, but in a recent case of mine it was not.
So while '=' is faster, LIKE might more explicitly state your intentions.
http://support.microsoft.com/kb/316626
For pattern matching use LIKE. For exact match =.
LIKE is used for pattern matching and = is used for equality test (as defined by the COLLATION in use).
= can use indexes while LIKE queries usually require testing every single record in the result set to filter it out (unless you are using full text search) so = has better performance.
LIKE does matching like wildcards char [*, ?] at the shell
LIKE '%suffix' - give me everything that ends with suffix. You couldn't do that with =
Depends on the case actually.
There is another reason for using "like" even if the performance is slower: Character values are implicitly converted to integer when compared, so:
declare #transid varchar(15)
if #transid != 0
will give you a "The conversion of the varchar value '123456789012345' overflowed an int column" error.