Getting all results using where clause

Viewed 26004

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.

9 Answers

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

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);
}
Related