Generate Union and Sub-Select SQL Queries Programmatically
Updated: Sep 3, 2023
DataPipeline contains a set of SQL builder classes to help in the construction of complex, dynamic queries. They enable you to specify query using Java objects and methods. This example shows how to generate queries involving `UNION` and subselect statement..
You can also view Generate SQL Queries Programmatically to see how selecting, filtering and sorting can be implemented using the other SQL builder classes.
Java Code Listing
package com.northconcepts.datapipeline.examples.cookbook; import com.northconcepts.datapipeline.jdbc.sql.SqlPart; import com.northconcepts.datapipeline.jdbc.sql.select.Select; import com.northconcepts.datapipeline.jdbc.sql.select.Union; public class GenerateUnionAndSubSelectSqlQueriesProgrammatically { public static void main(String[] args) { SqlPart select = new Select( new Union( new Select("employees").select("employee_id", "first_name"), new Select("contractors").select("employee_id", "first_name") ).setNestedAlias("employee_details")) .where("first_name = ?", "John"); System.out.println("Select query: " + select.getSqlFragment()); System.out.println("Query parameters: "); for (Object value : select.getParameterValues()) { System.out.println(value.toString()); } } }
Code Walkthrough
- Create a Select object containing another Union object as an argument.
- The Union combines the result set of two SELECT statements referenced by corresponding instances.
- Each Select instance has a table name as an argument.
select("employee_id", "first_name")
specifies the columns that are being selected. - The result of the union statement is given a table alias
employee_details
usingsetNestedAlias()
method. where("first_name = ?", "John")
adds a WHERE clause to the query, specifying one condition with a placeholder value.select.getSqlFragment()
retrieves the SQL fragment of the Select object, which represents the generated query. It is printed on the console.select.getParameterValues()
returns an array of parameter values used in the query. In our case,John
parameter is then printed on the console.
Console Output
Select query: SELECT * FROM ( SELECT employee_id, first_name FROM employees
UNION SELECT employee_id, first_name FROM contractors ) employee_details WHERE first_name = ? Query parameters: John