Trying to Order DB Column Alphabetically using CASE - mysql

I have a database table that contains a number of fields that have a value of NULL for a specific column called category.
Currently I am executing this statement that returns a list of all the entries with NULL appearing at the end. However, for some reason it is not sorting them alphabetically and I'm wondering If someone can help me?
This is my script:
SELECT c.* FROM `directorycolumn` c
WHERE `c`.`directorycompany_id` = 740
ORDER BY CASE WHEN `category` IS NULL THEN 0 ELSE 1 END DESC
This outputs The category column with NULL values at the end but not in alphabetical order. I.e The first entry category begins with a T...but I have categories beginning with A.
Any help is much appreciated.

Just add a second Order By clause:
SELECT c.* FROM `directorycolumn` c
WHERE `c`.`directorycompany_id` = 740
ORDER BY CASE WHEN `category` IS NULL THEN 0 ELSE 1 END DESC, `category` ASC

Related

Count empty text fields in CASE sentence in MySQL

My column contains categories A, B, C or "empty" ( which means the record is not categorized).
I want to show the total number of A's, B's and C's and the total number of records "Not categorized", and have tried the query below.
It does not work, however. It shows the correct number of A, B and C's but not the number of not categorized.
SELECT count(*) AS Quantity,
CASE
WHEN cf_ab_contacts.col_621 = '' THEN "Uncategorized"
ELSE cf_ab_contacts.col_621
END AS `Category`
FROM ...
WHERE ...
GROUP BY `cf_ab_contacts`.`col_621`;
Thanks for all help.
I'm really sorry - but the query did work as intended - there was an error in my WHERE section which excluded empty columns.
Thanks to Ankit for your patience.
I'm not sure if I can delete this thread - I should never have posted it in the first place.
Considering By Empty you mean NULL not a single space value, You have to test the condition with IS NULL predicate -
SELECT count(*) AS Quantity,
CASE
WHEN cf_ab_contacts.col_621 IS NULL THEN "Uncategorized"
ELSE cf_ab_contacts.col_621
END AS `Category`
FROM ...
WHERE ...
GROUP BY CASE
WHEN cf_ab_contacts.col_621 IS NULL THEN "Uncategorized"
ELSE cf_ab_contacts.col_621
END;

MySQL Get One Column Only Once

I have 2 MySQL tables in which I get data from in one query
"tables" table:
"checks" table:
The query I have been trying and the result of it:
SELECT tables.tableName, tables.tableRes, tables.tableResFor, checks.chkID, checks.chkDate, checks.chkStatus
FROM tables
LEFT JOIN checks ON tables.tableID=checks.chkTable
WHERE tables.tableID=3
ORDER BY checks.chkStatus DESC, checks.chkID ASC
Here are the problems
If there were no results from the query, I need the tableName column which comes out never null, so other columns can be null (works now)
I don't want to get the rows after first row, if the chkStatus column is 1 or 0 or null, shortly I need the rows with 2 on chkStatus, if the first row is 0, 1 or null, I don't need the other rows...
Thanks in advance, I have been working on this problem for more than 10 hours...
I need the other checks where chkStatus is 2 so, add the condition to the join
SELECT
tables.tableName
, tables.tableRes
, tables.tableResFor
, checks.chkID
, checks.chkDate
, checks.chkStatus
FROM tables
LEFT JOIN checks ON tables.tableID = checks.chkTable AND chkStatus = 2
WHERE tables.tableID = 3

How do I search for a value in a column and also get count of the column in a single SQL query

I have a table of following structure in MySQL 5.7:
CREATE TABLE `post_like` (
`post_title_id` varchar(255) NOT NULL,
`user_name` varchar(50) NOT NULL,
PRIMARY KEY (`post_title_id`,`user_name`),
) ENGINE=InnoDB;
and I have the following data
post_title_id user_name
new-story mani27
new-story manipal
some-story manipal
I am trying to get the count of likes for a particular story and also if a particular user has liked the story in a function likeStatus(user_name, post_title_id)
Suppose likeStatus(mani27, new-story) would result in:
count status
2 1
I am using the following query right now and it works right:
SELECT COUNT(user_name) AS count,
COUNT(CASE WHEN `user_name` = ? THEN 1 ELSE null END) as status
FROM post_like WHERE post_title_id = ?
But this would execute the case function on all the rows in the table rather than searching the indexed column user_name.
I could use two different queries to get count and status of username liking a post, but that would take much more time than this. So, is there an optimised way to get this output?
I didn't check the query but this should give you an idea. Try Group By
SELECT COUNT(user_name) AS count,
COUNT(CASE WHEN `user_name` = ? THEN 1 ELSE null END) as status
FROM post_like GROUP BY post_title_id HAVING post_title_id=?
But this would execute the case function on all the rows in the table
rather than searching the indexed column user_name
When you group by basing on post_title_id= and then applying count functions on them, number of row searches for username can be reduced to rows in that group
Add your condition inside CASE not in WHERE, then make sure you use DISTINCT to avoid duplicates:
SELECT COUNT(DISTINCT user_name) AS count,
COUNT(CASE WHEN `user_name` = ? AND post_title_id = ? THEN 1 ELSE null END) as status
FROM post_like
You don't have to scan all the records to see if a user liked the post. Just use a subquery on the select list. That should use the primary key index.
Something like this should work
SELECT COUNT(*),
(SELECT COUNT(*) FROM post_like WHERE postid=? AND userid=?)
WHERE postid=?

MYSQL - COUNT() NULL Values

This has been racking my head. I've scoured the internet (including this place) and can't find a solution. So as a last resort I was hoping the good people of this forum might be able to help me out.
I have two tables:
TableA
Order_detailsID
OrderID
TitleID
Return_date
TableB
TitleID
Title_name
Quantity_in_stock
And would like to run a query that shows the remaining 'Quantity_in_stock'.
If the 'Return_date' is set to NULL then it means the item is currently out -- so I have been trying to use the count() function for the NULL values and subtract it from the 'Quantity_in_stock'.
This is the script I have so far:
DELIMITER //
CREATE PROCEDURE InStock()
BEGIN
Select TableB.TitleID,
TableB.Title_name,
TableB.Quantity_in_stock AS 'Total_Stock',
COUNT(TableA.return_date IS NULL) AS 'Rented_Out',
TableB.Quantity_in_stock - COUNT(TableA.return_date IS NULL) AS 'Remaining Stock'
From TableB
LEFT JOIN TableA
ON TableA.TitleID = TableB.TitleID
GROUP BY TableB.TitleID;
END//
This works if there is one of more of the TitleIDs at NULL, however if there are no values at NULL, then the Count() is still returning a value of 1 when it should be 0.
What am I doing wrong?
Instead of:
COUNT(TableA.return_date IS NULL)
use this:
SUM(CASE
WHEN TableA.TitleID IS NULL THEN 0
WHEN TableA.return_date IS NOT NULL THEN 0
ELSE 1
END)
The problem with the TableA.return_date IS NULL predicate is that it's true in two completely different situations:
When there is no matching record in TableA
When there is a matching record but TableA.return_date value of this exact record is NULL.
Using the CASE expression you can differentiate between these two cases.
I will like to mention a simple concept here, just keep counting the rows when that particular column is null.
select count(*) from table_name where column_name is null

how to get other column when we use distinct in mysql query

When I use Distinct function in mysql query then I can get only one column from the table. This is example query that I am using:
SELECT DISTINCT (subcategory.title), common_cat. * FROM `subcategory`
LEFT JOIN common_cat ON ( subcategory.title = common_cat.ctitle )
It returns records as below :
title mid wid ctitle
Tops 17 5 Tops
Dresses NULL NULL NULL
Pants/Shorts 18 6 Pants/Shorts
Skirts NULL NULL NULL
Swimwear 24 8 Swimwear
Outerwear 21 9 Outerwear
In above data "Title" field coming from subcategory table.Now I also want to get id column
from subcategory table. How I can get this.
DISTINCT works by getting all the data of the columns you mentioned in a table row and then filtering out the duplicate rows and showing the unique rows with same values in ALL columns.
As such you can simply add the column subcategory.id to the column list and it will work.
SELECT DISTINCT subcategory.title, subcategory.id, common_cat.* FROM `subcategory`
JOIN common_cat ON ( subcategory.title = common_cat.ctitle )
Please note, in a distinct command it is not recommended to use * to pickup all columns as the more the number of columns in the query the more the load on the database server and hence a slower output. You may want to mention only the column names required in the distinct list and remove the common_cat.* from the query.