0

I was reading this question How to determine type of the sql query for jdbcTemplate in JAVA?. The correct answer says, a SELECT query can either start with a SELECT or a WITH.

Just for reference, the answer said:

// SELECT subqueries are irrelevant for the final result. So the command, the first verb is indicative of the result (int updateCount vs. ResultSet).

boolean isSqlSelect = sql.toUpperCase().startsWith("SELECT")
                   || sql.toUpperCase().startsWith("WITH");

So, now lets say I have a query

SELECT id, name, email FROM users;

Questions

  1. How can I rewrite that query starting with a WITH?
  2. And although the question was for JDBC, is it common for all SQL and ODBC/JDBC?
Chilarai
  • 1,842
  • 2
  • 15
  • 33

2 Answers2

6

WITH is the syntax for common table expressions (CTEs). This is standard SQL syntax supported basically by all reasonable databases (MySQL was the last to add such support).

CTEs are used to define subqueries that can be referenced multiple times in the query.

Note that CTEs can be used with UPDATE and DELETE statements as well as SELECT, so they do not necessarily indicate a SELECT.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
4

Since you also asked how you could rewrite your query using CTE...

with cte as

(select id, name, email 
 from users)

select * from cte;

I find it cleaner to define column names early on in the with clause so I save some space for my select

with cte (id, name, email) as

(select *
 from users)

select * from cte;
Radagast
  • 5,102
  • 3
  • 12
  • 27