My top tip is, run your SQL directly against the database using whatever tool makes that easier (some form of SQL GUI).
There's no point trying to cobble together SQL inside your code without actually
testing whether that SQL works.
You will make mistakes (typos at a minimum) that will be a pain to figure out if you do that.
So construct and test the SQL away from Java, and then copy/paste it into your code.