> For the complete documentation index, see [llms.txt](https://g4b0.gitbook.io/g4b0-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://g4b0.gitbook.io/g4b0-docs/documentation/hacking-web/sql/union.md).

# Union

Hasta ahora solo manipulabas la lógica de la query (con `OR` y comentarios). Ahora viene otro tipo de inyección: **ejecutar queries completas** junto a la original usando la cláusula `UNION` — lo que se conoce como **Union-based SQL injection**.

**¿Qué hace `UNION`?**

Combina los resultados de **varios `SELECT`** en una sola salida. Esto es poderoso porque te permite extraer datos de **otras tablas y bases** del DBMS:

```sql
SELECT * FROM ports UNION SELECT * FROM ships;
```

El resultado junta las filas de `ports` con las de `ships` en un solo output.

**Regla 1: mismo número de columnas**

`UNION` solo funciona si **ambos `SELECT` devuelven la misma cantidad de columnas**. Si no coinciden, da error:

```
ERROR 1222: The used SELECT statements have a different number of columns
```

Aplicado a una inyección — si la query original es:

```sql
SELECT * FROM products WHERE product_id = 'user_input'
```

Puedes inyectar un `UNION` para sacar datos de otra tabla (asumiendo que `products` tiene 2 columnas):

```sql
' UNION SELECT username, password FROM passwords-- '
```

**Regla 2: columnas desiguales → rellenar con "junk"**

Normalmente la tabla que quieres robar **no tiene** el mismo número de columnas que la query original. La solución es rellenar las columnas faltantes con **datos basura** para cuadrar el conteo.

Puedes usar strings o números. Por ejemplo, si solo quieres `username` pero necesitas 2 columnas:

```sql
' UNION SELECT username, 2 FROM passwords-- '
```

Si la query original usa una tabla de **4 columnas**, agregas más números:

```sql
' UNION SELECT username, 2, 3, 4 FROM passwords-- '
```

El resultado muestra tu dato (`username`) en la primera columna, y los números `2, 3, 4` rellenando el resto.

⚠️ Detalles clave:

* El **tipo de dato** del relleno debe coincidir con el de la columna, o da error.
* Usar **números** como relleno es práctico: además de cuadrar columnas, te sirven para **rastrear las posiciones** de tu payload (lo verás más adelante).

💡 Tip: en inyecciones avanzadas conviene usar **`NULL`** como relleno, porque encaja con **cualquier** tipo de dato.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://g4b0.gitbook.io/g4b0-docs/documentation/hacking-web/sql/union.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
