patternsqlModerate
MySQL metadata function to get projected column type in query?
Viewed 0 times
columnqueryfunctionprojectedtypemysqlgetmetadata
Problem
Is it possible to get the field type from a MySQL query, in the same way you can get it from a table with the
Given the above query, is there a function or something that I can use to get the type of x? PostgreSQL makes this available with the System Information Functions
I am not looking for metadata on a table, but from the result of query. With
SHOW COLUMNS command? Such as from a derived table,SELECT x -- presumedMetaFn(x) -- returns "int"
FROM (
SELECT 1 AS x
UNION SELECT 2
) AS t;Given the above query, is there a function or something that I can use to get the type of x? PostgreSQL makes this available with the System Information Functions
pg_typeofSELECT x, pg_typeof(x)
FROM ( VALUES (1),(2) ) AS t(x);
x | pg_typeof
---+-----------
1 | integer
2 | integer
(2 rows)I am not looking for metadata on a table, but from the result of query. With
psql on PostgreSQL 11+, this is also possible by running \gdesc after the query.Solution
Within MySQL, you can get this information by creating a temporary table, then using
We cannot just use
DESCRIBE on that temporary table:CREATE TEMPORARY TABLE `temp`
SELECT ...
FROM ...
LIMIT 0;
DESCRIBE `temp`;We cannot just use
DESCRIBE on the original table because the column we want to know the type of is a calculated column, not something being directly pulled from a table. Likewise, we cannot use DESCRIBE directly on the query, because DESCRIBE can only be used on tables. Creating a temporary table solves both of those problems.Code Snippets
CREATE TEMPORARY TABLE `temp`
SELECT ...
FROM ...
LIMIT 0;
DESCRIBE `temp`;Context
StackExchange Database Administrators Q#30141, answer score: 14
Revisions (0)
No revisions yet.