My SQL query not retrieving all the data from the database - mysql

I have a table in my database with the name contact. It has the following columns: name, mobile and twon. The problem is that I'm trying to get all the twon='Dubai', but when I execute my query it only retrieves 81000 rows but the total was 130000. The other remaining rows are not appearing in my query.
My Query:
SELECT * FROM `contact` WHERE `twon` = 'Dubai'
Can anyone tell me where I am going wrong or help me to access all the data from table?

= will fetch the record only if the column value is exactly 'dubai'.
Try with LIKE,TRIM and LOWER:
SELECT * FROM `contact` WHERE LOWER(TRIM(`twon`)) LIKE '%dubai%'
This query will fetch the records if twon column contains the word 'dubai'.

Different things could be wrong.
If you post examples of rows that should be returned, it would help us.
Case Sensitivity
If case sensitivity is a problem (e.g. 'dubai' or 'DUBAI' are not returned), you can use the LOWER function
SELECT * FROM `contact` WHERE LOWER(`twon`) = 'dubai'
Extra blanks
In some cases, extra blanks in the column content would fail, for instance ' Dubai' and ' Dubai '. You can use the TRIM function to get rid of trailing and leading blanks.
SELECT * FROM `contact` WHERE TRIM(`twon`) = 'Dubai'
Combination
Combining the two will work, too.
SELECT * FROM `contact` WHERE LOWER(TRIM(`twon`)) = 'dubai'

Related

How can I retrieve the column names from an empty MySQL select query result

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';

Concatenation is not working in select query

We are fetching list of ordered products from database including join with order table.
We want to list all orders with how many quantity of products order in each order on the basis of passed product ids. We also want to display customer name which was placed the order. So, as per our knowledge we have created an query to get items as:
SELECT
`main_table`.*,
`order`.*,
SUM(main_table.qty_ordered - main_table.qty_canceled) AS `custom_qty`,
SUM(main_table.row_total) AS `custom_row_total`,
SUM(main_table.tax_amount) AS `tax_amount`,
SUM(main_table.hidden_tax_amount) AS `hidden_tax_amount`,
SUM(main_table.discount_amount) AS `discount_amount`,
CONCAT(order.customer_firstname, ' ' ,order.customer_middlename, ' ', order.customer_lastname) AS full_name
FROM `sales_flat_order_item` AS `main_table`
INNER JOIN `sales_flat_order` AS `order` ON main_table.order_id=order.entity_id
WHERE (((((main_table.product_id = '902') OR (main_table.product_id = '903') OR (main_table.product_id = '904'))))) AND (main_table.store_id = '1') AND (CONCAT(order.customer_firstname, order.customer_middlename, order.customer_lastname) like '%rag%')
GROUP BY `main_table`.`sku`
All the aggregate functions used in above query working fine except concat(). Every time we will get the value of full_name column as NULL even we have name the corresponding concatenated columns.
Please any one helps me to figure out why this is not working. Are we doing something wrong in the above query?
Thanks in advance.
As CONCAT() returns NULL if any argument is NULL I'm guessing maybe one of the three arguments is NULL?
Try using the CONCAT_WS() function instead (as you use separators anyway) which skips null values.
CONCAT_WS(' ', order.customer_firstname, order.customer_middlename, order.customer_lastname) AS full_name
See the documentation for more information.
On a side note: you might want to look into how you can use table aliases to shorten the query text and make it more readable.
Are you sure EVERY column has an value? (Middlename?)
The MYSQL manual says:
SELECT CONCAT('My', NULL, 'QL')
-> NULL

MySQL returns all rows when field=0 from SECOND Select query

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.)

How can I get just the column names for a given mysql query?

I am creating a utility which lets users enter a SQL query for the purposes of importing data to my database.
The first step is to show a list of resulting fields so the user can route them to the destination fields.
When users import from MSSQL, I can use SET FMTONLY ON to fetch the list of output columns that the query would produce if ran (assuming the query is valid in the first place).
I haven't been able to find a way to do this for MySQL. EXPLAIN doesn't list the resulting fields.
Given the following query:
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
ORDER BY name ASC;
I ultimately need to get a list of output fields only, like this:
{ "name", "age", "foo" }
How can I do this in MySQL?
SET FMTONLY ON still requires you to get the column names and types manually, it just generates an empty result set.
For MySQL, add a WHERE FALSE somewhere
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
WHERE FALSE
ORDER BY name ASC;
You get this lovely execution plan
"id";"select_type";"table";"type";"possible_keys";"key";"key_len";"ref";"rows";"Extra"
"1";"SIMPLE";NULL;NULL;NULL;NULL;NULL;NULL;NULL;"Impossible WHERE"
Then parse the columns as you would set fmtonly on with MSSQL
For complex queries (nested, group by, limit-ed), wrap it in a subquery
select * from (
<your wonderful brilliant complex query>
) x where false
MSSQL would have complained if the inner query contains ORDER BY without TOP, MySQL is ok with it.
I think you need to look at the resultsetmetada. I carries the number of columns, column name, and a few more about the result set.
I think you're looking for DESC {table_name}

I need some help getting MySql to output some results using a subquery

I'm storing a list of numbers inside a table as a varchar(255) and want to use this list in another query's "IN() clause.
Here's what I mean:
Table Data:
CREATE TABLE IF NOT EXISTS `session_data` (
`visible_portf_ids` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `session_data` (`visible_portf_ids`) VALUES
('45,44,658,659,661,45,44,658,659,661')
I want to run a query like this to return a list of portfolio's "QUERY #1":
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN
(
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
)
ORDER BY name ASC
The result of the query above returns only 1 row, when there are a total of 3 that should have been returned.
If I run the subquery alone like this:
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
it will return a list like this:
45,44,658,659,661,45,44,658,659,661
But, when I run Query #1 above, only one row of data, which is associated with the "visible_portf_ids" of "45" is returned.
If I replace the subquery with hard coded values like this:
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN (45,44,658,659,661,45,44,658,659,661)
ORDER BY name ASC
then I get all 3 rows I'm expecting.
I'm guessing that MySql is returning the list as a string because its stored as a varchar() and so it stops processing after the first "visible_portf_ids" is found, which is "45", but I'm not really sure.
Anyone got any ideas how I can fix this?
Thanks in advance.
You should think about restructuring your tables storing each value in a new row, instead of concatenating them.
Until then, you can use the FIND_IN_SET() function:
AND FIND_IN_SET(leaf_node_portf_id,
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog'
LIMIT 1)
) > 0
Unfortunately MySQL does not have a function to split a delimited string. Your IN argument is a single string with the result of your subquery. The reason it works when you hard-code it is that MySQL is parsing the values.
I suggest that you redesign your data base to store the visible ports list as separate rows in a separate table. Then you can retrieve them and use them in subqueries like you tried.