CAST in Subquery
CAST in Subquery is a SQL statement in the Subqueries category. Type casting within subqueries ensures compatible data types for comparison or aggregation. The syntax is SELECT * FROM t1 WHERE col = (SELECT CAST(col AS type) FROM t2);. It returns cast-safe subquery result. A typical example: SELECT * FROM orders WHERE customer_id = ( SELECT CAST(id AS INT) FROM temp_import WHERE status = 'latest' ); -- temp_import.id might be VARCHAR, cast to INT for comparison -- Common casting scenarios: SELECT * FROM products WHERE price > ( SELECT AVG(CAST(price_str AS DECIMAL(10,2))) FROM imported_prices ); -- CAST functions: -- MySQL: CAST(expr AS type), CONVERT(expr, type) -- PostgreSQL: expr::type, CAST(expr AS type) -- SQL Server: CAST(expr AS type),… A close relative is Scalar Subquery, which a subquery that returns a single value (one row, one column). Can be used in SELECT, WHERE, HAVING clauses. A close relative is Correlated Subquery, which a subquery that references columns from the outer query. Evaluated for each row of the outer query.