As it is possible to select top N rows from table, is there any way to select first N columns from MySQL database tables?
Thanks for your replies and maybe some parts of code in PHP.
SQL requires that you name the columns you want, or else use the * wildcard. In relational theory, there is no concept of "first N columns" because columns have no implicit order.
To select columns, choose one of the following options: Type SELECT , followed by the names of the columns in the order that you want them to appear on the report. Use commas to separate the column names.
If you want to select only specific columns, replace the * with the names of the columns, separated by commas. The following statement selects just the name_id, firstname and lastname fields from the master_name table.
Please have a look at Bill Karwin's answer first. But if you know how to order your column names there could be a solution that makes use of a dynamic query.
To select all column names from a table, you can use a query like this:
SELECT `column_name`
FROM `information_schema`.`columns`
WHERE `table_schema`=DATABASE()
AND `table_name`='yourtablename';
(please have a look at this answer). And making use of GROUP_CONCAT:
GROUP_CONCAT(CONCAT('`', column_name, '`') ORDER BY column_name)
we can return all column names in a single row, separated by commas:
`col1`, `col2`, `col3`, ...
(I also added quotes around the name of the column, and please notice that we have to order our list of columns somehow, otherwise there are no guarantees about the order in which column names are returned).
Then we can cut the returned string, using SUBSTRING_INDEX, in order to get, for example, the first 2 column names:
SUBSTRING_INDEX(columns, ',', 2)
and our final query, that concatenates 'SELECT '
, the selected columns above, and ' FROM Tab1'
, and inserts the resulting string into the @sql
variable is this:
SELECT
CONCAT(
'SELECT ',
SUBSTRING_INDEX(
GROUP_CONCAT(CONCAT('`', column_name, '`') ORDER BY column_name),
',',
2),
' FROM Tab1'
)
FROM
information_schema.columns
WHERE
table_schema=DATABASE()
AND table_name='Tab1'
INTO @sql;
It's value will be something like this:
@sql = "SELECT `col1`, `col2` FROM Tab1"
and you can then prepare your statement, and execute it:
PREPARE stmt FROM @sql;
EXECUTE stmt;
Please see fiddle here.
SQL requires that you name the columns you want, or else use the *
wildcard.
In relational theory, there is no concept of "first N columns" because columns have no implicit order. Of course in any concrete implementation of SQL, they must have some storage order, but the SQL language doesn't have any support for fetching columns by "position" in the table, nor is there any support for fetching sequences of columns (except for *
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With