I have a function which takes an argument that is used in where clause
function(string x)-->Now this will create a sql query which gives
select colname from tablename where columnname=x;
Now I want this function to give all rows i.e. query equivalent to
select colname from tablename;
when I pass x="All".
I want to create a generic query that when I pass "All" then it should return me all the rows else filter my result.
Just leave the where condition out.
If you really want it that complicated use
where columnname LIKE '%'
which will only filter nulls.
select colname from tablename
where columnname=(case when #x ="All" then columnname
else #x end)
Try this
select colname from tablename where 1=1
hope the above will work
where 1=1 worked for me, Although where clause was being used all records were selected.
You can also try
[any_column_name]=[column_name_in_LHL]
(LHL=left hand side.)
refer my answer for more details
I had the same issue some time ago and this solution worked for me
select colname from tablename where columnname=x or x = 'ALL'
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;
Any of the above query will return all records from table.
In Node.js where I had to pass conditions as parameter I used it like this.
const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
It's unclear what language you're using for your function, but you have to somehow parse the 'All' prior to getting to sql:
public void query(String param) {
String value = "":
switch (param) {
case 'All':
value = "*";
break;
default:
value = param;
}
String sql = "select colname from tablename where colname="+value;
//make the query
}
If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.
An example of a piece of code to do this would be;
IF x = 'ALL'
THEN
SELECT COLNAME FROM TABLENAME;
ELSE
SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
Give a conditional check in your code(assuming Java) to append the WHERE clause only when x != 'All'
mySqlQuery = "SELECT colname FROM tablename" +
(x.equals("All") ? "" : "WHERE columnname = "+x);
Related
I'm creating custom JPQL queries to fetch some data.
I have certain cases where I would like to add a where clause depending on if the parameter value is non null.
For example equivalent sql query:
//If parameter status is not null.
SELECT sum(A.sal) FROM TABLE A WHERE A.STATUS = 'X' GROUP BY A.CURRENCY;
//else
SELECT sum(A.sal) FROM TABLE A GROUP BY A.CURRENCY;
Can someone help me with it.
The two queries:
//If parameter status is not null.
SELECT sum(A.sal) FROM TABLE A WHERE A.STATUS = 'X' GROUP BY A.CURRENCY;
//else
SELECT sum(A.sal) FROM TABLE A GROUP BY A.CURRENCY;
can be compacted to one.
First lets declare a named parameter statusParam. This param can take any value (like 'X' or null from above). So the two queries above can be re-written to:
SELECT sum(A.sal) FROM A WHERE (A.STATUS = :statusParam OR :statusParam is null ) GROUP BY A.CURRENCY;
Come on, JPQL is just normal String :)
You want something like this?
private String generateHql(String status) {
String jpql = "SELECT sum(A.sal) FROM TABLE A ";
if (null != status) {
jpql += "WHERE A.STATUS = " +status ;
}
jpql += " GROUP BY A.CURRENCY "
return jpql;
}
I am having three parameters $page, $date, $search. i need a single select sql query where i have to check all the three variables one by one whether any of these variables is having some value or not or if all of the three variables is having some value. According to which it will match from the database and give the result. Please help me out.
You can make where clause as follows in your Select query.(Below is MS SQL format, you can modify CASE statement equivalent with MY SQL)
SELECT * FROM TABLE (if more than one table, you can use join)
WHERE TABLE.search_COLUMN = case when #search <> '' then #search else TABLE.search_COLUMN end
AND
TABLE.page_value_COLUMN = case when #page_value <> '' then #page_value else TABLE.page_value_COLUMN end
AND
TABLE.date_value_COLUMN = case when #date_value <> '' then #date_value else TABLE.date_value_COLUMN end
An input and script in index.php
<input type="text" class="filter" id="frClientName" name="cl_name">
<script>
$(".filter").on('change keydown keyup', function(){
var clname;
clname = document.getElementById("frClientName").value;
$("#spravaContent").load("php/search_results/sprava.php?cl_name=" + clname;
});
</script>
php/search_results/sprava.php
$clname = '';
if ( isset ( $_GET['cl_name'] ) ) {
$clname = $_GET['cl_name'];
}
$sql = ("
SELECT * FROM `db`.`table`
WHERE cl_full_name LIKE '%".$_GET['cl_name']."%'
");
How can I use WHERE clause right and only if variable isn't empty?
Thank you for some direction.
EDIT:
$sql = ("
SELECT * FROM `db`.`table`
ORDER BY {$oby} {$ohow}
WHERE cl_full_name LIKE '%".$_GET['cl_name']."%'
OR '' = '".$_GET['cl_name']."'
LIMIT $start_sprava,$per_page_sprava
");
It's a bit hacky, but I've handled situations like this with a CASE statement. You evaluate your argument and if it doesn't meet the condition you require, you use an obviously true statement like 1=1 which has the net effect of keeping that part of the WHERE clause from participating in filtering the result set.
SELECT *
FROM `db`.`table`
WHERE CASE WHEN TRIM('".$_GET['cl_name']."') IS NOT NULL THEN cl_full_name LIKE '%".$_GET['cl_name']."%'
ELSE 1=1
END
ORDER BY {$oby} {$ohow}
LIMIT {$start_sprava}, {$per_page_sprava}
;
Don't forget to police your inputs so you don't wind up with a Little Bobby Tables problem. Also, the ORDER BY and LIMIT clauses generally come after the WHERE clause.
Make the where clause work whether set or not.
Assuming your app language returns the text "null" if variable is not set:
"SELECT * FROM `db`.`table`
WHERE cl_full_name LIKE '%".$_GET['cl_name']."%'
OR 'null' = '".$_GET['cl_name']."'"
I want to write mysql query to display all records if text field value = "All" or else display records similar to keyword value. I have written code below to just to give an idea.
if (keyword = 'All' )
select * from ItemMain
else if (keyword like %itemname%)
select * from ItemMain
Ok, assuming PHP as the front-end language you can put it all in one query like this (forgive the curly braces; I'm never sure when they're needed or not so I tend to over-use them):
$query = <<< ENDSQL
SELECT *
FROM ItemMain
WHERE ('{$keyword}' = 'All') OR (your_textfield like '%{$keyword}%')
ENDSQL;
... execute the query
But really I'd go with the suggestion from #cjg and use two different queries:
$query = "";
if ($keyword == 'All') {
$query = "SELECT * FROM ItemMain";
} else {
$query = "SELECT * FROM ItemMain WHERE your_textfield LIKE '%{$keyword}%'";
}
... execute the query
If itemname is your column name, and your search string parameter replaces the ? in your code. Then your statement should look something like this if you are searching for all itemnames containing your search string:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname LIKE '%?%'
Or this if you are looking for an exact match:
SELECT *
FROM ItemMain
WHERE ? = 'All' OR itemname = ?
Here is my query:
SELECT
CASE
WHEN hbn.users.showDistance = 'T'
THEN hbn.distance(u2.lat, u2.lon, hbn.users.lat, hbn,users,lon)
ELSE 0
END as distance,
hbn.users.id,
hbn.users.username,
From hbn.users,
(select hbn.users.lat, hbn.users.lon from hbn.users where hbn.users.id = '1') AS u2
where hbn.users.Id = '8';
This does not work!
I need to use output of the second select statement as input for distance() function.
It looks like you have commas instead of full-stops in the last parameter to hbn.distance?