I am running some SQL queries from command line as follows:
cat my_query.sql | mysql --defaults-file=my_conf.cnf
I need to print column names whether the query returns any data or not.
Currently when there is no data to return, i.e when query returns an empty result set this command does not print anything.
For example my query is:
-- id=-1 doesn't exist
SELECT col1, col2 FROM table WHERE id=-1
I need this query to return
col1 col2
Instead it returns nothing.
Is it possible to do that using purely mysql and standard unix commands?
Thanks.
Adding a UNION ALL to a SELECT with "dummy"/blank data might work:
SELECT col1, col2 FROM table WHERE id=-1
UNION ALL
SELECT '', '' -- OR 0, 0 whatever is appropriate
;
I don't run queries from the command line, so this is assuming it normally would give you the column names if you had at least one row in the results.
Related
I have a big data raw(bronze) table with ~400 columns. In preparation for this table moving forward to other level tables in prepared (or silver level), I am picking up, let's say, 395 columns from the raw table; however, I don't like to type the name of all 399 columns in my SQL query.
Is there any solution in SQL to save some time?
Instead of
SELECT col1, col2, col3, ..., col395 FROM table
something like
SELECT * EXCEPT col400 FROM table
SELECT CONCAT_WS(' ',
'SELECT',
GROUP_CONCAT(column_name),
'FROM database_name.table_name') query_text
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'database_name'
AND table_name = 'table_name'
AND column_name NOT IN ('excess_column_1', 'excess_column_2', ...);
Insert your database and table names, fill the list of the columns to be excluded, execute the query - and it will produce needed query text.
You may convert this to the stored procedure which composes and executes needed query dynamically and call this SP instead of the query.
First do
EXPLAIN SELECT * FROM tbl;
SHOW WARNINGS;
Then edit the output to remove the column(s) you don't want.
(Next time, think about whether it is wise to have that many columns in a table; 400 is very high.)
Is there a way to show row values as column values.
Lets say I have a table called A and which contains 5 records with 3 columns. Below image show the data set. Rows always 5.
In Here I need to show value column values in a line with temporary column names
If I use simple select query as
Select row1.value as col1, row2.value as col2, row3.value as col3, row4.value as col4, row5.value as col5
so my expected result need to show as below
Please tell me how to use select query to get this result in MySQL
I have a table with 50 columns. This table contains nulls in all the columns but in random. I want to update all the nulls with 'no data'. If there are nulls in 2 columns I can do it with
update tableName
set col1 = 'nodata'
where col1 is null
But, I have 50 columns like this, instead of writing an update command for all the columns, is there any other technique to complete it in a single line query.
You can use coalesce():
update tableName
set col1 = coalesce(col1, 'nodata'),
col2 = coalesce(col2, 'nodata'),
. . .;
If most rows have data in all columns, you can add a where clause:
where col1 is not null or col2 is not null or . . .
Note: This answers your question, but I don't think it is a good idea. NULL is a perfectly good way to represent "no data" in a SQL database. There is no need to update the values. In addition, this assumes that all columns are strings. This method will not work on other data types -- you will likely get a type conversion error.
My database is in MySQL
I have a table, let's say of 4 columns.
I would like to know if it's possible, and how to implement the following: fill the 4th column according to the value of the column 2 and column 3
In Excel I have a formula, let's give an example: if column2 value is set to "grey" and column3 value is set to "car", then column 4 value should be set to "super"
I just say this as an example.
My real formula in Excel looks like this: =IF(K4=4;"Maximal";IF(K4>4;"Maximal";IF(K4=3;"Important";IF(K4>3;"Important";IF(K4=2;"Limited";IF(K4>2;"Limited";IF(K4=1;"Forgettable";IF(K4>1;"Forgettable";"error"))))))))
However I want to do it in SQL.
I was thinking of creating my table until the column 3, set column 4 to NULL or empty, then open a GUI written in Java and maybe there do a piece of code to automatically fill the column 4 according to what is in column 2 and column 3 (these values will be choosable via Choicelist).
But if there is a way to do it directly in SQL, I am interested
Thx a lot in advance for your help.
regards
Yes. you can easily update your NULL-values according to some requirements for the other values in other columns of a particular row with the Update statement
UPDATE <tablename>
SET <column> = 'value'
WHERE <condition>
The only drawback here might be that you have to create an update statement for each of the combinations of your values in column2 and column3. (however, it's not much work for your amount of conditions).
I created an example (demo):
Creating a table in SQL according to your example could look like this,I used a temporary one for the sake of an example:
CREATE GLOBAL TEMPORARY TABLE demoTable (
"Col1" VARCHAR2(50 BYTE) NOT NULL,
"Col2" VARCHAR2(50 BYTE) NOT NULL,
"Col3" VARCHAR2(50 BYTE) NOT NULL,
"Col4" VARCHAR2(50 BYTE) DEFAULT NULL
)
ON COMMIT PRESERVE ROWS
I also inserted some dummy data:
INSERT INTO demoTable VALUES ('Charles', 'grey', 'car', NULL);
INSERT INTO demoTable VALUES ('Alice', 'grey', 'bike', NULL);
INSERT INTO demoTable VALUES ('Bob', 'red', 'car', NULL);
The result:
Now, create the update statements like this, for example:
UPDATE demoTable dt
SET dt."Col4" = 'super'
WHERE dt."Col2" = 'grey' AND dt."Col3" = 'car';
The result
You can try like this;
select * from mytable
COL1 COL2
---- --------------------
0 -
1 -
2 -
3 -
4 -
4 record(s) selected.
update mytable Set Col2 =
Case
When Col1<1 Then 'error'
When Col1=1 Then 'Forget'
When Col1=2 Then 'Limited'
When Col1=3 Then 'Important'
When Col1=4 Then 'Maximal'
End"
select * from mytable"
COL1 COL2
---- --------------------
0 Error
1 Forget
2 Limited
3 Important
4 Maximal
4 record(s) selected.
You can create a sql function, lets say udfGetColumn4Value taking in the column2, column3 as parameters to it and return a value.
Now you can run a select column2, column3, udfGetColumn4Value(column2, column3) from table or a query as desired. Hope this helps.
You were not very precise regarding which DBMS you're using. And also about the exact logic behind using your two columns.
Still here comes a probable SQL-Server solution, where I have taken one statement using CASE WHEN with your example and concatenated your two columns col2 and col3 (you can apply your further logic of here) otherwise:
UPDATE TableName
SET Col4 = CASE WHEN col2 = 'red' AND col3 = 'car' THEN 'super' ELSE col2 + col3 END;
You should replace col2 + col3 with your further logic.
Seems that a simple UPDATE-Query could address your problem:
update things set result = "super" where thing = "car" and color = "grey";
The where-clause does what you desire to do by saying
fill the column 4 according to what is in column 2 and column 3
I created a test table here on turorialspoint, there you can check if it fits your needs.
I have a question about query data with vertical format, I tried it with \g or \G .
I referenced "4.5.1.6.2 Displaying Query Results Vertically" at https://dev.mysql.com/doc/refman/5.5/en/mysql-tips.html
But it not working and show error syntax at "\G"
My query :
select * from mytable \G . Always wrong.
From that, I just want to build final query like this:
Select "A","B","C","D" as "ColumnName" \G
Expect:
ColumnName
A
B
C
D
I tried with UNION or UNION ALL. but with several thousand record, it's slow performance.
And mysql version is : Server version- 5.6.17 - MySQL Community Server (GPL)
# Bernd Buffen
I show my query:
Select C.* from
(
( Select * from (Select "Value1" as newcolumn UNION ALL Select "Value2" as newcolumn UNION ALL ...<200.000 UNION ALL>) ) A
left join
(SELECT key,column1,column2,colum3 FROM supplier ) B
on A.newcolumn = B.key
) C
And handle query to database, I debug time from Begin to End, it spend from 1.30 to 2 minutes. It is not good.
The \G and \g features are just features of the command line client (as mentioned in the comments.)
MySQL when used from a programming API (even another program, like phpMyAdmin or a MySQL GUI) does not support \g or \G. It doesn't even "display" data. Display is done by the GUI program, instead.
However, even if you ran this query:
SELECT 'A', 'B', 'C', 'D' AS "ColumnName"\G
In the command line client, it would actually produce:
*************************** 1. row ***************************
A: A
B: B
C: C
ColumnName: D
1 row in set (0.01 sec)
This is because you've selected 4 columns in that query, and only named the last one 'ColumnName'.
If you want to see the rows of the table you would run:
SELECT *
FROM table_name\G
And then it would list each column, then a :, then the value.
Nevertheless, this would only work with the command line client.
If you're wanting to retrieve a key, value from the database via a programming API, the problem is definitely a bit trickier. A UNION is going to end up being what you want, e.g.:
SELECT 'column_name_1' AS key, GROUP_CONCAT(column_name_1) AS value
FROM table_name
UNION ALL
SELECT 'column_name_2' AS key, GROUP_CONCAT(column_name_2) AS value
FROM table_name
But yes, it's not likely to be efficient.
This isn't really the way databases are meant to be used - they're meant to be used as a table of data. I'd suggest you change the data to this format after you've retrieved it from MySQL. You might do this in an array, or similar.
Here is one more Sample.
DROP TEMPORARY TABLE IF EXISTS TMPV;
CREATE TEMPORARY TABLE `TMPV` (
`newcolumn` VARCHAR(32) NOT NULL DEFAULT '',
PRIMARY KEY (`newcolumn`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO `TMPV` VALUES ('Value1'),('Value2'),('Value3'),('Value4'),('Value5'),('Value6');
SELECT A.*, s.`key`, s.`column1`, s.`column2`, s.`column2`
FROM `TMPV` A
LEFT JOIN supplier s
ON A.newcolumn = s.key;