MYSQL: How to refer to the 1st column - mysql

SELECT first_name FROM user WHERE FIRST_COLUMN = '10'
What I need to know is how to reference "FIRST_COLUMN" in MYSQL syntax. The first column can be any name and so I need to make it flexible as long it should get the 1st column of any table. thanks

The short answer is : you can't. (in a portable way, there are 'tricks' to look up the name of the first column and similar workarounds)
Many projects use as convention to name the first column ID and use that as the primary key.
By the query it looks like you are uing it as a primary key.
I recommend reading an introduction to relational databases as this is a rather strange request in the context of a relational database.

The relational model does not care one tiny little bit what order columns are in within a table, nor (without an ordering clause) what order rows are returned.
Your requirement makes little sense. What if the first column were a varchar or a date?
The whole point of having named columns is that you reference them by name.
Now DBMS' often contain metadata in system tables, like DB2's sysibm.systables and sysibm.syscolumns, but you need to extract not just the names but all the other metadata as well (column type, size, nullable, and so on) in order to use them properly. We'd probably understand better what you were after if you told us the reason behind doing this.

SELECT COLUMN_NAME FROM information_schema.COLUMNS
WHERE TABLE_NAME = 'tablename'
AND ORDINAL_POSITION =1

Related

How do I get the output of a SELECT statements in MariaDB/MySQL workbench to name columns in "table.column" format instead of just "column"?

I have to explore undocumented schemas to come up with query statements that will satisfy some business need.
When I SELECT * FROM foo JOIN bar ON foo.barid=bar.id; I get back a list of columns and I could guess where the columns from one table end and the next begin. But it would be awfully convenient if it just used the columns' full names i the output. i.e, every column would display as foo.columnname or bar.columnname.
yes, that's bulkier than optimal, and no I'd never use it in a production solution. but for exploratory pokings and prodings it would make things easier when I'm trying to figure out why a query isn't working right.
How do I turn that on by default?
CLARIFICATION: No. I'm not looking for "how to list all columns in a table/schema. I want to run queries joining tables together, and see the results, and see unambiguously and easily, what table a given field came from.
You can query the database information_schema to help you figure out what is what in your database. Running the following will get you close:
select table_name, column_name from information_schema.columns
https://dev.mysql.com/doc/refman/8.0/en/information-schema-columns-table.html
If you must use * you can qualify by table for example
select foo.*,'//',bar.*
will display all columns from foo first then a divider then all columns from bar and within foo the display left to right represents the ordinal position of the columns in foo. If the display columns are left justified then the column datatype is string of some description (varchar,char,text etc) if right justified then a number of some sort (int,decimal,float etc) . If a number is left justified then the underlying datatype is string. Date datatypes in mysql are in the form yyyy-mm-dd so if you see this then the underlying dataype is likely to be date. Similarly datetime
To understand the actual datatypes and find the indexes,constraints and foreign keys on a table then show create table tablename . If you want all table definitions use workbench export or mysqldump utility.
Also do read up on what information_schema https://dev.mysql.com/doc/refman/8.0/en/information-schema.html can do for you and consider reverse engineering your DB in workbench.

Find all table names in database which has a column which contains a certain value, MySQL

I want to find all the table names where i have a certain value, like:
SELECT table_name FROM information_schema WHERE column_name = "MyColumnName" AND MyColumnName = "value";
I have problem searching for a value in the column, how should i write the last part..
AND MyColumnName = "value";
..?
You cannot do this in 1 query. Your first query should identify all the tables that you need to query. You then need to query all the tables and you can either do this by hand or write a dynamic sql script to generate the table queries. I'm not going to do this for you since this looks like coursework (it's surprising how often this comes up - must be the time of year so I'm sure you can find further help if you search SO)

How to get a highest value from Nth colum withouth knowing column name

How to get a highest value from the second column in a table, without knowing column name? In a single SQL query?
I got a set of tables where the value I'd like to get is always in a second column (that's part of the way tables are always made), but the name of this column is different in each table. So I could use some simple SQL query that can obtain this value. Any ideas? I know it's doable with PHP and additional query to extract the names of columns, but I'm looking for elegant, purely SQL solution :)
It's gonna be a tedious process. But, if it's necessary, you may use ORDINAL_POSITION column in the information_schema.columns table to get the Nth column name.
SELECT column_name
FROM information_schema.columns
WHERE table_name = "your table name"
AND ordinal_position = 1 --replace 1 with your N
Check this.
The obvious solution is to change the data structure. making it relational and normalized.
In a properly designed database such a question like your just simple can't be.
There is always one field which you can query for the highest value. And position in the field list absolutely doesn't matter.
As a side effect of refactoring your database structure, you will have a solution for the hundreds other problems you will have in the future.

MySQL: How to speed up that join?

I have 2 tables and I need to join them. Unfortunately, I dont have ids that I could use, the only criteria are some varchar column. This is the "on" part of the join:
join sales_flat_order_address sfoa on
concat(lower(trim(sfoa.firstname)), lower(trim(sfoa.lastname))) = concat(lower(trim(so.firstname)), lower(trim(so.lastname)))
I know that this is not the fastest way, but is there a way to spped this up a bit more? Or maybe a workaround I cant think of right now?
Thanks!
Indexing firstname and lastname columns would be a start.
First of all though I would run your query with EXPLAIN in front of it and see if there are any indexes you may already have and think are being used which actually might not be being used.
Secondly, JOINing on varchar is never going to be 'super' quick compared to joining on an int for example.
http://dev.mysql.com/doc/refman/5.5/en/explain.html
You could try to use this:
ON trim(sfoa.firstname) = trim(so.firstname)
AND trim(sfoa.lastname) = trim(so.lastname)
of course, you could try to index firstname and lastname in both tables.
You could add an "and" between first name and last name so as to avoid the concat. Also you can use indexes on these columns (firstname and lastname) so as to speed thing a lot (especially if you use the comparison a lot).
join sales_flat_order_address sfoa on
trim(sfoa.firstname) = trim(so.firstname) and trim(sfoa.lastname) = trim(so.lastname)
This query is essentially doing a cross join on the table, and then matching the condition. To fix this, you could:
Add a new column into each table called full name.
Give this the value of something like:
concat(lower(trim(firstname)), lower(trim(lastname))).
Build an index on the value.
Actually, you could do this on only one of the tables, and MySQL will use the index for the comparison (still requiring a full table scan on the first table.
You could also have a "full names" table, and use a foreign key from each of these tables to get the full name.
Indexing the names independently won't affect the query. The names are being accessed inside functions, which generally turns off the ability to use an index.
At a minimum, you should create an index on firstname and lastname in both tables. Also, run an explain on your query. That can show you inefficiencies.

Do i really need to include table names or AS in JOINS if columns are different?

I noticed te other day I can joins in mysql just as easily by doing,
SELECT peeps, persons, friends FROM tablea JOIN tableb USING (id) WHERE id = ?
In stead of using,
SELECT a.peeps, a.persons, b.friends FROM tablea a JOIN tableb b USING (id) WHERE id = ?
It only works if there is no matching column names, why should I do the second rather than the first?
No, you don't need to, but in my humble opinion you really should. It's almost always better in my experience to be explicit with what you're trying to do.
Consider the feelings of the poor guy (or girl) who has to come behind you and try to figure out what you were trying to accomplish and in which tables each column resides. Explicitly stating the source of the column allows one to look at the query and glean that information without deep knowledge of the schema.
Query 1 will work (as long as there are no ambiguous column names).
Query 2 will
be clearer
be more maintainable (think of someone who doesn't know the database schema by heart)
survive the addition of an ambiguous column name to one of the tables
So, don't be lazy because of that pitiful few saved keystrokes.
It's not necessary if you have no duplicate column names. If you do, the query will fail.