I've been curious. What are the differences between these respective queries:
SELECT * FROM `tablename`
SELECT * FROM `tablename` WHERE 1
SELECT * FROM `tablename` WHERE 1=1
2 and 3 are the same in MySQL, functionally 1 is also the same.
where 1 is not standard so, as others have pointed out, will not work in other dialects.
People add where 1 or where 1 = 1 so where conditions can be easily added or removed to/from a query by adding in/commenting out some "and ..." components.
i.e.
SELECT * FROM `tablename` WHERE 1=1
--AND Column1 = 'Value1'
AND Column2 = 'Value2'
As you know, all three produce the same results. (In a boolean context, MySQL treats the integer "1" as true -- in fact, any number that is not "0" is treated as true).
The MySQL optimizer is explicitly documented to remove constant conditions in the WHERE clause:
Constant condition removal . . .:
(B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6)
-> B=5 OR B=6
Hence, all three will be compiled into exactly the same code.
They are all functionally equivalent and should have the same performance characteristics.
That said, the first and third are standard SQL. The second will cause some sort of boolean expression error in many databases. So, I would advise you to avoid that (I'm not sure whether it works or not in MySQL's strict SQL mode).
Often the third is used when constructing dynamic WHERE clauses. It makes it easy to add additional conditions as AND <condition> without worrying about lingering ANDs.
If you are asking about the differences in performances and results, there isn't any , 2 and 3 are the same WHERE TRUE , and they will result the same as the first one.
1 - SELECT * FROM table_name
Results in all the data from table_name (no filter)
2 - SELECT * FROM table_name WHERE 1
1 will be evaluated as TRUE , therefore - no filter - every record will be returned .
3 - SELECT * FROM table_name where 1=1
Same as the last one, 1=1 is a TRUE expression , therefore - no filter - every record will be selected.
All are the same but 2 and 3 are used to easily handle AND/OR conditions
like:
SELECT * FROM `tablename` WHERE 1=1 AND (columnname1 = 'Value' OR columnname2 = 'Value')
In 1, MySQL does not need to evaluate any WHERE conditions.
In 2 and 3, the where condition is static and not based on the rows' values. It will be evaluated with boolean logic and always be true.
Functionally, there is no difference. You should choose 1 for code clarity.
All are the same but 2 and 3 are used to create Dynamic queries for AND/OR conditions
sqlquery =" SELECT * FROM `tablename` where 1 =1 "
we use 2 and 3 format to make dynamic query so we already know "where" keyword is added and we keep adding more filters .
Like
sqlquery = sqlquery + "and columna =a"
"AND columna =a " then
after few lines if we have new filters we add "AND coulmnb =b " and so on
You don't have to check the sql query for where keyword as its placed in first or initial query
SELECT * FROM `tablename` WHERE 1=1 AND (columnname1 = 'Value' OR columnname2 = 'Value')
Otherwise we can write sqlquery = "SELECT * FROM tablename"
then
if there is no 'where' clause in sqlquery then
sqlquery = sqlquery + "where columna =a"
else
sqlquery = sqlquery + "and columna =a"
They all output the same answer. However the way 2 and 3 are written is mostly is in order to have control of the "Where" statement so it would make it easier to add it or remove it later.
I think that the first and third way are the proper way of writing it. If you need a where statement you do like in number 3 otherwise number 1 would be good enough.
In MS SQL 1 and 3 are same , however, option 2 will not work , option 2 is an invalid statement as in MS SQL, WHERE is used to compare some values. For Example:
Select * from 'myTable where ID = 3 (valid)
Select * from 'myTable where 1 = 1 is same as Select * from 'myTable where 2= 2 is same as Select * from 'myTable where 3= 3 you get the idea (valid) is same as Select * From 'myTable'
SELECT * FROM table_name : it will give you all the records of the
table with running any where statement.
SELECT * FROM table_name WHERE 1 : this where condition is always
true, its mostly used by hacker to get into any system. If you heard
about sql injections than 2 & 3 are scenarios which are forced to
build by hacker to get all the records of table.
SELECT * FROM table_name where 1=1 : This will give you all the
records of the table but it will compare the where statement and
then move forward, it's basically added to add or removed more
statements after that.
Result - Gives all the records in the table specified instead of tablename for all three queries
SELECT * FROM tablename WHERE 1 - Check this answer
SELECT * FROM tablename WHERE 1=1 - Check this answer
For more Info about WHERE clause optimizations check these : MYSQL, SQLite, SQL
Related
I have a little problem selecting queries, namely when I want to check the first condition with the code below
select * from VL_Faktura_Queue where FAK_KundenNr=127849 AND (FAK_BoMatNr LIKE '%verk%' AND FAK_VerrechnetBis ='0001-01-01')
, it shows me one position, but when I add a condition where I want to check if there is a FAK_KundenNr with FAK_BomatNr LIKE '% Verk%' OR FAK_BoMatNr Like 'Zus%' also throws me different values that do not fall under FAK_KundenNr = 127849, as I can easily check that it returns my values for this KundenNr, where there is 1 OR 2 condition.
this is my query:
select * from VL_Faktura_Queue where FAK_KundenNr=127849
AND (FAK_BoMatNr LIKE '%verk%' AND FAK_VerrechnetBis ='0001-01-01') --this would be the first condition
or FAK_BoMatNr like 'Zus%' --and this the second condition
This is the individual selection I should get but in one query at the end
so my question is how can i get in one query select from these two query from the picture, thanks everyone for the help
Your parentheses are not sufficient. AND has precedence over OR, so you have FAK_KundenNr = 127849 AND (<first condition)> OR FAK_BoMatNr like 'Zus%'.
SELECT *
FROM VL_Faktura_Queue
WHERE FAK_KundenNr = 127849
AND
(
(FAK_BoMatNr LIKE '%verk%' AND FAK_VerrechnetBis = '0001-01-01')
or
FAK_BoMatNr LIKE 'Zus%'
);
In your requirement, you need to combine the "AND" operator with other logical "OR" operator.
SELECT *
FROM VL_Faktura_Queue
WHERE
(
( FAK_BoMatNr LIKE '%verk%'
AND FAK_VerrechnetBis = '0001-01-01'
) -- 1st Condition
or
(FAK_BoMatNr LIKE 'Zus%') -- 2nd Condition
)
AND FAK_KundenNr = 127849;
Please check if this solution is working for you.
If I make a search for instance
"Candy" in where statement I retrieve 12 hits however if I write "candy" I retrieve 0 hits.
Is it possible to make the database or table to be case insensitive?
If yes, how?
Thank you
A simple solution might be to convert both the search string and the column you are searching on to lowercase using the LOWER() function in SQL Server. Something like:
SELECT whatever
FROM yourTable
WHERE LOWER(whatever) = LOWER(#searchString)
If you want to make your where clause case insensitive . convert left and right to the same case and then put condition .
If I take table as mytable with attributes X and Y . where filter is on Y then
select X , Y from mytable where UPPER(Y) = UPPER(#toSearch)
or
`select X , Y from mytable where LOWER(Y) = LOWER(#toSearch)`
In your case, maybe its easier to understand if i use your where clause ,example:
SELECT *
FROM yourTable
WHERE LOWER(whatever) = 'candy' or
SELECT *
FROM yourTable
WHERE UPPER(whatever) = 'CANDY'
I'm trying to read a column from a database using a SQL query. The column consists of empty string or numbers as strings, such as
"7500" "4460" "" "2900" "2640" "1850" "" "2570" "9050" "8000" "9600"
I'm trying to find the right sql query to extract all the numbers (as integers) and removing the empty ones, but I'm stuck. So far I've got
SELECT *
FROM base
WHERE CONVERT(INT, code) IS NOT NULL
Done in program R (package sqldf)
If all columns are valid integers, you could use:
select * , cast(code as int) IntCode
from base
where code <> ''
To prevent cases when field code is not a valid number, use:
select *, cast(codeN as int) IntCode
from base
cross apply (select case when code <> '' and not code like '%[^0-9]%' then code else NULL end) N(codeN)
where codeN is not null
SQL Fiddle
UPDATE
To find rows where code is not a valid number, use
select * from base where code like '%[^0-9]%'
select *
from base
where col like '[1-9]%'
Example: http://sqlfiddle.com/#!6/f7626/2/0
If you don't need to test for the number being valid, ie. a string such as '909XY2' then this may run marginally faster, more or less depending on the size of the table
Is this what you want?
SELECT (case when code not like '%[^0-9]%' then cast(code as int) end)
FROM base
WHERE code <> '' and code not like '%[^0-9]%';
The conditions are repeated in the where and case on purpose. SQL Server does not guarantee that where filters are applied before logic in the select, so you can get an error with conversions. More recent versions of SQL Server have try_convert() to fix this problem.
Using sqldf with the default sqlite database and this test data:
DF <- data.frame(a = c("7500", "4460", "", "2900", "2640", "1850", "", "2570",
"9050", "8000", "9600"), stringsAsFactors = FALSE)
try this:
library(sqldf)
sqldf("select cast(a as aint) as aint from DF where length(a) > 0")
giving:
aint
1 7500
2 4460
3 2900
4 2640
5 1850
6 2570
7 9050
8 8000
9 9600
Note In plain R one could write:
transform(subset(DF, nchar(a) > 0), a = as.integer(a))
I am having another problem this time and its about DB2 query, running in NWDS.The specification of database which I am using are:
Database:- EP1,
Schema:- W2HCMSC,
Tablespace:- W2HCMTS,
Table:- TESTEMPLOYEE,
Cloumns:- ZONE, Workshop, Year, Employee Name, Designation, DOB.
The snapshot of the database with values is the select statement which I want to run is a select query with where clause but its not returning any row.
These are the details:
select * from w2hcmsc.testemployee
(4 rows returning)
select * from w2hcmsc.testemployee where 'w2hcmsc.Zone' = '1'
(0 row returning)
select * from w2hcmsc.testemployee where 'Zone' = 1
(SQL0420N Invalid character found in a character string argument of the
function "DECFLOAT". SQLSTATE=22018)
select * from w2hcmsc.testemployee where zone = 1
SQL0206N "ZONE" is not valid in the context where it is used. SQLSTATE=42703
select * from w2hcmsc.testemployee where Zone = 1
SQL0206N "ZONE" is not valid in the context where it is used. SQLSTATE=42703
select * from w2hcmsc.testemployee where 'Zone' = '1'
(0 record(s) selected).
Please tell me why the select query with where clause is not working. And do I have to write it in any differnt manner?
try the fully qualified name of the column:
select * from w2hcmsc.testemployee where w2hcmsc.testemployee.ZONE = 1
or create an alias for the table and use it:
select * from w2hcmsc.testemployee AS t1 where t1.ZONE = 1
Your column name appears to be in mixed case. It's generally a good idea to avoid using mixed case in your column names – While DB2 supports this, it creates headaches such as this.
The solution is to quote your column names using double quotes (not single quotes):
select * from w2hcmsc.testemployee where "Zone" = 1
or, using a table correlation name:
select * from w2hcmsc.testemployee as t1 where t1."Zone" = 1
The output of query has to return records where company is not equal to 'CABS' OR substring of company until empty space (eg CABS NUTS).The company name can the CABS, COBS, CABST , CABS NUTS , CAB
SELECT *
FROM records
WHERE UPPER(SUBSTR(company, 0, (INSTR(company,' ')-1))) <> 'CABS'
OR COMPANY <> 'CABS'
But the above query is returing CABS NUTS along with COBS , CAB.
I tried using "LIKE CABS" it looks fine but if the company name is "CAB" it will not return "CABS" and CABS NUTS because of like. So LIKE is completely ruled out.
Can anyone please suggest me.
So you want all records where the first 4 characters of the Company field are not "CABS". Okay.
WHERE left(company, 4) != 'CABS'
SELECT
*
FROM
Records
WHERE
LEFT(Company, 4) <> 'CABS'
AND Company <> 'CABS'
Note: Basic TSQL String Comparison is case-insensitive
Can quite work out which ones you do want returns, but have you considered LIKE 'CABS %'
select * from records where company NOT IN (SELECT company
FROM records
WHERE UPPER(SUBSTR(company, 0, (INSTR(company,' ')-1))) = 'CABS'
OR COMPANY = 'CABS')
I think this will fetch the desired records from the records table
RECORDS:
COMPANY
=====================
CAB
CABST
COBS
First, I think you should use AND instead of OR in your compound condition.
Second, you could simplify the condition this way:
WHERE UPPER(SUBSTR(company, 0, (INSTR(company || ' ',' ') - 1))) <> 'CABS'
That is, the company <> 'CABS' part is not needed in this case.
The problem you are getting comes about because the result of the SUBSTR is null if there is not a space. And thanks to three value logic, the result of some_var <> NULL is NULL, rather than TRUE as you might expect.
And example of this is shown by the query below:
with mytab as (
select 1 as myval from dual union all
select 2 as myval from dual union all
select null as myval from dual
)
select *
from mytab
where myval = 1
union all
select *
from mytab
where myval <> 1
This example will only return two rows rather than three rows that you might expect.
There are several ways to rewrite the condition to make it ignore the null result from the substr function. These are listed below. However, as mentioned by one of the other respondents, the two conditions need to be joined using the AND operator rather than OR.
Firstly, you could explicitly check that the column has a space in it using the set of conditions below:
(INSTR(company,' ') = 0 or
UPPER(SUBSTR(company, 0, (INSTR(company,' ')-1))) <> 'CABS') and
COMPANY <> 'CABS'
Another option would be to use the LNNVL function. This is a function that I only recently found out about. It return TRUE from a condition when the result of the condition provided as the input is FALSE or NULL.
lnnvl(UPPER(SUBSTR(company, 0, (INSTR(company,' ')-1))) = 'CABS') and
COMPANY <> 'CABS'
And another option (which would probably be my preferred option) is to use the REGEXP_LIKE function. This is simple, to the point and easy to read.
WHERE not regexp_like(company, '^CABS( |$)')