I want to SELECT DISTINCT on a table to return a string.
If the string is blank, I don't want to know about that row.
To make matters worse, some users ahve been inputting whitespace and I want to ignore those rows too.
(How) can I do this? Thanks (MySql)
SELECT DISTINCT col_name
FROM table_name
WHERE TRIM(col_name) != ''
You can use COALESCE in MySQL to get the first non-NULL column.
Additionally, you can also make use of CASE statements to check if either column is NULL or an empty string and have a conditional query based off that.
Related
I have tried to select something with SQL, and I've a problem with it.
What I want:
SQL SELECT * FROM table WHERE ? = '5';
Select everything which = 5, BUT not specify from which column.
Example:
From this ""database"", you should receive the 1st and the last row.
Is that possible?
You have to list the columns but you can use in. The where clause looks like:
where 5 in (price, height)
Note: This assumes that the columns have the same type. You could get type conversion errors if they are not.
Also, given the names of the column and the data, I assume that the columns are stored as numbers. Hence, I dropped the single quotes around 5. If they are really strings, then use the single quotes.
you need to add a condition to your query with or keyword so if any of them match the row will be shown as a result
SELECT * FROM tablename WHERE price =5 or height= 5
better you list your columns by name instead of using * after SELECT
I have a table and in that I want to sort a column in that table. But I’m unable to get the sorted order because there are different kinds of characters in the first place of the string. Some of them have horizontal tab, some of them have spaces, and some of them are empty. I have tried trim method but it doesn’t work for me. I have nearly 200000 records in that table. I cant update the table. I need a select query which should give the result neglecting all the unnecessary things and should sort the columns.
I think this might work
SELECT *
FROM table_name
ORDER BY IF(coloum_name LIKE "_%", substr(coloum_name, 1), coloum_name);
Explanation:
We use the IF function to strip the first character from the beginning of the string before returning the string to the ORDER BY clause. For more complex rules we could create a user-defined function and place that in the ORDER BY clause instead. Then you would have ...ORDER BY MyFunction(coloum_name)
For SQL Server, do this:
SELECT *
FROM table_name
ORDER BY CASE WHEN coloum_name LIKE "_%" THEN substr(coloum_name, 1) ELSE coloum_name END
Consider the following table:
SELECT id, Bill_Freq, Paid_From, Paid_To, Paid_Dt, rev_code FROM psr_20160708091408;
The requirement is to fetch the row which has rev_code populated with the string **SUM**.
I've also noticed that for every row with rev_code populated as **SUM** its Bill_Freq won't be either null or zero.
So I wrote two queries to fetch the row with the lowest id
Query based on string check in where clause:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**";
Query based on true condition:
select
min(id) as head_id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where bill_freq;
I haven't seen anyone use the second type, would like to know its reliability and circumstance of failure.
If by "second type" you mean a where clause with no explicit condition, then there is a good reason why you do not see it.
The SQL standard -- and most databases -- require explicit conditions in the where. MySQL allows the shorthand that you use but it really means:
where not billing_freq <=> 0
or equivalently:
where billing_freq <> 0 or billing_freq is null
(The <=> is the null-safe comparison operator.
The more important issue with your query is the min(). I presume that you actually want this:
select p.*
from psr_20160708091408 p
where rev_code = '**SUM**'
order by id
limit 1;
Also, you should use single quotes as string delimiters. That is the ANSI standard and there is rarely any reason to use double quotes.
Actually you can use the second type of query, but as your requirement is based on rev_code, it is always good to have condition with rev_code, because of 2 reasons
Bill_Freq having no NUlls or Zeros might be assumption based on current data
Even if it is true, in future, your application logic might change and it might have a scenario having NULL or zero, which will break your logic in future.
So my suggestion is to use first query with Rev_code
Please try to use below query
select
id,
bill_freq,
Paid_From,
Paid_To,
Paid_Dt
from
`psr_20160708091408` where rev_code = "**SUM**" ORDER BY ASC LIMIT 0,1;
Thanks.
The requirement says it itself.
The requirement is to fetch the row which has rev_code populated with
the string '**SUM**'
In the scenario that bill_freq IS NOT NULL and rev_code is populated with
the string '**SUM**' then your logic will obviously fail.
Go for
where rev_code = "**SUM**";
Is there a way to retrieve the column names of a query that returns no data?
The result of this query would be empty.
Is there a way how to find the column names when there's no result?
Please note that I'm aware of solutions using DESCRIBE and select column_name from information_schema.columns where table_name='person';
but I need a more flexible solution that will fit these multicolumn queries.
Please also note that I am still using the original PHP MySQL extention (so no MySQLi, and no PDO).
If you wrap your query with the following SQL, it will always return the column names from your query, even if it is an empty query result:
select myQuery.*
from (select 1) as ignoreMe
left join (
select * from myTable where false -- insert your query here
) as myQuery on true
Note: When the results of the subquery are empty, a single row of null values will be returned. If there is data in the subquery it won't affect the output because it creates a cross-product with a single row...and value x 1 = value
Execute following command if the result of your previous query is empty
SHOW columns FROM your-table;
For more details check this.
I'm not sure if it will satisfy you but you can do this
SELECT *, COUNT(*) FROM table;
It will return null values (except last column which you can ignore) if the query is empty and you will be able to access all columns. It's not proper way of doing it and selecting names from INFORMATION_SCHEMA would be much better solution.
Please note that result is aggregated and you need to use GROUP BY to get more results if there are any.
You should ,
Select COLUMN_NAME From INFORMATION_SCHEMA.COLUMNS
Where TABLE_SCHEMA='yourdb'
AND TABLE_NAME='yourtablename';
This case is similar to: S.O Question; mySQL returns all rows when field=0, and the Accepted answer was a very simple trick, to souround the ZERO with single quotes
FROM:
SELECT * FROM table WHERE email=0
TO:
SELECT * FROM table WHERE email='0'
However, my case is slightly different in that my Query is something like:
SELECT * FROM table WHERE email=(
SELECT my_column_value FROM myTable WHERE my_column_value=0 AND user_id =15 LIMIT 1 )
Which in a sense, becomes like simply saying: SELECT * FROM table WHERE email=0, but now with a Second Query.
PLEASE NOTE: It is a MUST that I use the SECOND QUERY.
When I tried: SELECT * FROM table WHERE email='( SELECT my_column_value FROM myTable WHERE my_column_value=0 LIMIT 1 )' (Notice the Single Quotes on the second query)
MySql SCREAMED Errors near '(.
How can this be achieved
Any Suggestion is highly honored
EDIT1: For a visual perspective of the Query
See the STEN_TB here: http://snag.gy/Rq8dq.jpg
Now, the main aim is to get the sten_h where rawscore_h = 0;
The CURRENT QUERY as a whole.
SELECT sten_h
FROM sten_tb
WHERE rawscore_h = (
SELECT `for_print_stens_rowscore`
FROM `for_print_stens_tb`
WHERE `for_print_stens_student_id` =3
AND `for_print_stens_factor_name` = 'Factor H' )
The result of the Second Query can be any number including ZERO.
Any number from >=1 Works and returns a single corresponding value from sten_h. Only =0 does not Work, it returns all rows
That's the issue.
CORRECT ANSWER OR SOLUTION FOR THIS
Just in case someone ends up in this paradox, the Accepted answer has it all.
SEE STEN_TB: http://snag.gy/Rq8dq.jpg
SEE The desired Query result here: http://snag.gy/wa4yA.jpg
I believe your issue is with implicit datatype conversions. You can make those datatype conversions explicit, to gain control.
(The "trick" with wrapping a literal 0 in single quotes, that makes the literal a string literal, rather than a numeric.)
In the more general case, you can use a CAST or CONVERT function to explicitly specify a datatype conversion. You can use an expression in place of a column name, wherever you need to...
For example, to get the value returned by my_column_value to match the datatype of the email column, assuming email is character type, something like:
... email = (SELECT CONVERT(my_column_value,CHAR(255)) FROM myTable WHERE ...
or, to get the a literal integer value to be a string value:
... FROM myTable WHERE my_column_value = CONVERT(0,CHAR(30)) ...
If email and my_column_value are just indicating true or false then they should almost certainly be both BIT NOT NULL or other two-value type that your schema uses for booleans. (Your ORM may use a particular one.) Casting is frequently a hack made necessary by a poor design.
If it should be a particular user then you shouldn't use LIMIT because tables are unordered and that doesn't return a particular user. Explain in your question what your query is supposed to return including exactly what you mean by "15th".
(Having all those similar columns is bad design: rawscore_a, sten_a, rawscore_b, sten_b,... . Use a table with two columns: rawscore, sten.)