I'm failing to translate a SQL query which was designed for MySQL into Postgres syntax. This is the query:
select if(sendonly = true, 'REJECT', 'OK') AS access from accounts where username = '%u' and domain = '%d' and enabled = true LIMIT 1;
This nice little function "if()" is not available in Postgres. My first attempts with some CASE clauses failed. What needs to be modified to make this query run in Postgres?
As you noted, you could use a case expression:
SELECT CASE WHEN sendonly = true THEN 'REJECT' ELSE 'OK' END AS access
FROM accounts
WHERE username = '%u' AND domain = '%d' AND enabled = true
LIMIT 1;
Or, as Postgres can evaluate booleans directly, you could trim this query down a bit:
SELECT CASE WHEN sendonly THEN 'REJECT' ELSE 'OK' END AS access
FROM accounts
WHERE username = '%u' AND domain = '%d' AND enabled
LIMIT 1;
Related
Here Problem is make sql query is not check case sensitive latters
Here SQL Version;
VERSION(): 8.0.15
Sql Query for login user:
SELECT COUNT(*) as cnt FROM accounts WHERE (number = 'AdMin' OR email = 'AdMin') AND password = '******' AND type IN (1) AND deleted = 0
Database store name='admin'
here how to set case sensitive sql query for mysql 8.0 and stop login when username ='AdMin'
You need to use the BINARY operator to make your search case sensitive:
SELECT COUNT(*) as cnt
FROM accounts
WHERE (number = BINARY 'AdMin' OR email = BINARY 'AdMin') AND password = '******' AND type IN (1) AND deleted = 0
Demo on dbfiddle
This is my code.. Query working when i search with mysql query(find it in screenshot).But failed with hiberbate query.
EmployeeAttendanceMaster masterEmployeeFromRepository = masterEmployeeRepository.findById(employee, date);
if (masterEmployeeFromRepository == null) {
System.out.println("SignIn Successfully");
}else System.out.println("You are already Logged In");
masterEmployeeRepository:
#Query("select me from EmployeeAttendanceMaster me where me.employee = ?1 and Date(me.date) = ?2 order by me.date desc")
EmployeeAttendanceMaster findById(Employee employee,Date date);
mysql db screenshot in with same query
Data with same date there in db..So it shoudnot go through if condition.It should follow else condition.But as long as i tried this it prints "SignIn Successfully"
Thanks advance
You are using the Spring Data JPA #Query annotation (as discerned from the full data type you have provided in the comments to your question). The query you specify with #Query (select me from EmployeeAttendanceMaster me ...) must be a valid JPA Query Language (JPQL) statement. From what I know and remember, JPQL does not have a Date() function. So, your query is invalid because it contains Date(me.date) which refers to a non-existent JPQL Date() function, even if you can run it directly on MySQL.
You can change your query declaration to:
#Query(value = "select * from EmployeeAttendanceMaster where employee_id = ?1 and Date(date) = ?2 order by date desc", nativeQuery = true)
This will force the JPA provider (Hibernate in your case) to treat the query as a native SQL query and will be executed on the underlying database without any translation. You will lose database independence though.
I need to check if the column exam has a value of true. So I set this up but it doesn't work...
#exam_shipments = Shipment.where("exam <> NULL AND exam <> 0 AND customer_id = ?", current_admin_user.customer_id)
# This one gives me error "SQLite3::SQLException: no such column: true:"
#exam_shipments = Shipment.where("exam = true AND customer_id = ?", current_admin_user.customer_id)
#exam_shipments = Shipment.where("exam = 1 AND customer_id = ?", current_admin_user.customer_id)
You should really just stick to AR syntax:
#exam_shipments = Shipment.where(:exam => true, :customer_id => current_admin_user.customer_id)
Assuming :exam is a boolean field on your Shipment model. ActiveRecord takes care of converting your query to the proper syntax for the given database. So the less inline SQL you write, the more database-agnostic and portable your code will be.
Why do you need do execute SQL?
It's much easier just to do
#exam_shipments = Shipment.find_by_id(current_admin_user.customer_id).exam?
I have a somewhat complex mySQL query I am trying to execute. I have two parameters: facility and isEnabled. Facility can have a value of "ALL" or be specific ID. isEnabled can have value of "ALL" or be 0/1.
My issue is that I need to come up with logic that can handle the following scenarios:
1) Facility = ALL AND isEnabled = ALL
2) Facility = ALL AND isEnabled = value
3) Facility = someID AND isEnabled = ALL
4) Facility = someID AND isEnabled = value
The problem is that I have several nested IF statements:
IF (Facility = 'ALL') THEN
IF (isEnabled = 'ALL') THEN
SELECT * FROM myTable
ELSE
SELECT * FROM myTable
WHERE isEnabled = value
END IF;
ELSE
IF (isEnabled = 'ALL') THEN
SELECT * FROM myTable
WHERE facility = someID
ELSE
SELECT * FROM myTable
WHERE facility = someID AND isEnabled = value
END IF;
END IF;
I would like to be able to combine the logic in the WHERE clause using either a CASE statement or Conditional's (AND/OR) but I am having trouble wrapping my head around it this morning. Currently the query is not performing as it is expected to be.
Any insight would be helpful!
Thanks
You could do this...
SELECT
*
FROM
myTable
WHERE
1=1
AND (facility = someID OR Facility = 'ALL')
AND (isEnabled = value OR isEnabled = 'ALL')
However, this yields a poor execution plan - it's trying to find one size fits all, but each combination of parameters can have different plans depending on data, indexes, etc.
This means that it is better to build the query dynamically
SELECT
*
FROM
myTable
WHERE
1=1
AND facility = someID -- Only include this line if : Facility = 'ALL'
AND isEnabled = value -- Only include this line if : isEnabled = 'ALL'
I know it can feel dirty to use dynamic queries, but this is a good corner case as to when then really can excel. I'll go find a spectacularly informative link for you now. (It's a lot to read, but it's very worth learning from)
Link : Dynamic Search
This is the code I am using
# update db
client = Mysql2::Client.new(:host => "localhost", :username => "jo151", :password => "password", :database => "jo151")
details.each do |d|
if d[:sku] != ""
price = d[:price].split
if price[1] == "D"
currency = 144
else
currency = 168
end
cost = price[0].gsub(",", "").to_f
if d[:qty] == ""
qty = d[:qty2]
else
qty = d[:qty]
end
results = client.query("SELECT * FROM jos_virtuemart_products WHERE product_sku = '#{d[:sku]}' LIMIT 1;")
if results.count == 1
product = results.first
client.query("UPDATE jos_virtuemart_products SET product_sku = '#{d[:sku]}', product_name = '#{d[:desc]}', product_desc = '#{d[:desc]}', product_in_stock = '#{qty}' WHERE virtuemart_product_id =
#{product['virtuemart_product_id']};")
client.query("UPDATE jos_virtuemart_product_prices SET product_price = '#{cost}', product_currency = '#{currency}' WHERE virtuemart_product_id = '#{product['virtuemart_product_id']}';")
else
client.query("INSERT INTO jos_virtuemart_products( product_sku, product_name, product_s_desc, product_in_stock) VALUES('#{d[:sku]}','#{d[:desc]}','#{d[:desc]}','#{d[:qty]}');")
last_id = client.last_id
client.query("INSERT INTO jos_virtuemart_product_prices(virtuemart_product_id, product_price, product_currency) VALUES('#{last_id}', '#{cost}', #{currency});")
end
end
end
`query': Duplicate entry '' for key 3 (Mysql2::Error) on line 35:
client.query("INSERT INTO jos_virtuemart_products( product_sku, product_name, product_s_desc, product_in_stock) VALUES('#{d[:sku]}','#{d[:desc]}','#{d[:desc]}','#{d[:qty]}');")
last_id = client.last_id
Putting in raw SQL statements with arbitrary strings inlined like this is extremely dangerous. You absolutely must escape any values put into them for your application to work at all. The first description you get with an apostrophe will cause your SQL to fail.
In this case you would use client.quote on each and every one of the strings. No exceptions. You have probably seen tons of press about Sony getting hacked, and it's because of mistakes like this that serious breaches happen.
You should investigate using an ORM to help with this, even something as simple as Sequel or DataMapper, as they provide facilities to make this easy.
The reason you are getting a duplicate key is because you have a unique index on one of the columns you're inserting into, or one of the columns is not specified and has a default value that collides with an existing row.