Updated on 2024-10-23 GMT+08:00

Querying ClickHouse Data

This section describes the sample code for querying ClickHouse data.

Query statement 1 querySql1 queries any 10 records in the tableName table created in Creating a ClickHouse Table. Query statement 2 querySql2 uses a built-in function to combine the year and month fields in the tableName table created in Creating a ClickHouse Table.

The following code snippet is provided in the queryData method of the Demo class in the com.huawei.clickhouse.examples package.

private void queryData(String databaseName, String tableName) throws Exception {
    String querySql1 = "select * from " + databaseName + "." + tableName + "_all" + " order by age limit 10";
    String querySql2 = "select toYYYYMM(date),count(1) from " + databaseName + "." + tableName + "_all" + " group by toYYYYMM(date) order by count(1) DESC limit 10";
    ArrayList<String> sqlList = new ArrayList<String>();
    sqlList.add(querySql1);
    sqlList.add(querySql2);
    ArrayList<ArrayList<ArrayList<String>>> result = util.exeSql(sqlList);
    for (ArrayList<ArrayList<String>> singleResult : result) {
        for (ArrayList<String> strings : singleResult) {
            StringBuilder stringBuilder = new StringBuilder();
            for (String string : strings) { 
               stringBuilder.append(string).append("\t");
            }
            log.info(stringBuilder.toString());
        }
    }
}