Simplify queries, WITH keyword
Parte de la sección Fundamentos del Journey de SQL de Coddy — lección 49 de 72.
Las consultas pueden volverse demasiado desordenadas al agregar muchas consultas internas. Por ejemplo, aquí hay una consulta que tiene muchas subconsultas:
SELECT * FROM table1
WHERE col2 IN (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
)
)Para hacerlo más fácil, podemos usar la palabra clave WITH query_name AS (...). Nos permite guardar una consulta con un nombre y usarla donde queramos:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1Aquí reutilizamos query1 en query2 y en la consulta principal.
Desafío
FácilTablas y columnas disponibles:
<strong>devices_specs</strong>:<strong>device_id</strong>,<strong>width</strong>,<strong>height</strong>,<strong>num_features</strong>,<strong>opinion</strong><strong>devices_score</strong>:<strong>device_id</strong>,<strong>score</strong>
escribe una consulta que:
- Primero identifica "dispositivos grandes" (dispositivos con
widthmayor que 200) - Luego calcula la puntuación promedio para estos dispositivos grandes. Llama a esta columna como
average_score
Usa la cláusula WITH para resolver este problema.
Hoja de referencia
Utilice WITH query_name AS (...) para crear subconsultas con nombre que se pueden reutilizar:
WITH query1 AS (
SELECT col5 FROM table3
WHERE col1 AND col3 OR col2
), query2 AS (
SELECT col1 FROM table2
WHERE col3 + col2 > 3 AND col5 LIKE '%test%' AND col6 IN query1
)
SELECT * FROM table1
WHERE col2 IN query2 AND col4 IN query1Esta aproximación hace que las consultas complejas con múltiples subconsultas sean más legibles y permite reutilizar la misma subconsulta varias veces.
Pruébalo tú mismo
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de Fundamentos
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns9Multiple tables
Basic Join Part 1Basic Join Part 2Recap - JoinSelf joinRecap - Self JoinUnionSimplify queries, WITH keywordRecap - With QueriesRecap - Real Estate Contractor