I was working with PHP and mysql a table was given and I was given a table to sort which had a enum field
enum('Pending','Acive','INACTIVE');
I did not understand how the table was sorted?
Enumeration Sorting
ENUM values are sorted based on their index numbers, which depend on the order in which the enumeration members were listed in the column specification. For example, 'b' sorts before 'a' for ENUM('b', 'a'). The empty string sorts before nonempty strings, and NULL values sort before all other enumeration values.
To prevent unexpected results when using the ORDER BY clause on an ENUM column, use one of these techniques:
Specify the ENUM list in alphabetic order.
Make sure that the column is sorted lexically rather than by index number by coding ORDER BY CAST(col AS CHAR) or ORDER BY CONCAT(col).
Reference: http://dev.mysql.com/doc/refman/5.6/en/enum.html#enum-sorting
You can sort like this in Sql
ORDER BY CASE status
WHEN 'Pending' THEN 1
WHEN 'Acive' THEN 3
ELSE 2
END
Related
I have table.
Table structure is
And now I run the query
SELECT * FROM `studentregistrations`
ORDER BY `studentregistrations`.`studentID` DESC, `studentregistrations`.`studentName`
And the result I am getting is
I want an explanation how it is working. Because I am confusing that it should give result like studentID is in descending order and studentName is in ascending order.
I checked below answer but not getting any proper explanations
mysql query order by multiple items
PHP MySQL Order by Two Columns
I think your expectations are that the columns are sorted independently, so that all student names are in alphabetic order and all student ids are in descending order, independently on the names. If that would happen, you would get results where a student id is next to the wrong name, so fortunately that doesn't happen.
Instead, it sorts by the first column first and then by the next column. The secondary sort only applies to groups that have the same value in the first column.
So if you would have 10 students with the same ID, then for that ID their names would be alphabetically sorted.
But since the ID is unique, the secondary sorting is useless.
It would be useful, for example, to use
ORDER BY UniversityId, StudentName
That way, you would have a list where all students of the same university are grouped together, and within these groups they are sorted alphabetically by name.
When you sort using multiple columns, the order of the second column only influences the order when two or more values are equal in the first column. If all values in the first column are unique, the other order columns do not matter.
Your query first orders by student id, and then following that, orders any 'ties' by student name.
It's impossible to have both of your order by's honoured in full, because then there would be row/column mismatches.
I'm currently porting SQL queries into PHP to interact directly with an access DB.
What I need to do is sort a field if the value of column 1 is greater than zero and if not sort the field based on the text description of column 2. I already have this as a calculated field in Access sorted Ascending and hidden but the direct port to SQL isn't working.
In Access it looks like:
IIf((Round(SLA.SLA-SLAMins)/60,2))>0,'A'
& Format(999999-(Round(SLA.SLA-SLAMins)/60,2)),'000000.00'),'B000000.00')
& Left([SrFreetext],10)
Any ideas on how I can keep the calculated field for sorting purposes?
I usually solve this through a union. Without a schema, I can't give you a precise answer, but it's something like:
select *,
1 as sortingColumn
from tableName
where Round(SLA.SLA-SLAMins)/60,2))>0
union
select *,
0 as sortingColumn
from tableName
where Round(SLA.SLA-SLAMins)/60,2)) <= 0
order by sortingColumn, textDescriptionField
On this MySQL Query the ordering is sorting all results digit by digit. What I want is to simply return the smallest number first. Am I going about this wrong, or is it just the way PHP sorts?
MySQL:
$history = mysqli_query($con,"SELECT id,credits,timeadded FROM users ORDER by credits ASC);
Returned Result (Credits only):
1,13,14,16,2,24,29,3,31
Desired Result:
1,2,3,13,14,16,24,29,31
Your credits column must be a string. So MySQL use string comparison to order your results. And, when you compare, for example, 11 and 2 strings, 2 is 'bigger' than 11 (2 is a bigger char than 1).
You should to something like this :
SELECT id,credits,timeadded FROM users ORDER by CAST(credits AS UNSIGNED)
Then MySQL will make the comparison considering credits as a number : 11 will be bigger than 2.
BTW, if you only store numbers into this column, why it is VARCHAR type ?
You can change it with an ALTER TABLE statement :
ALTER TABLE users MODIFY credits INTEGER;
As mentioned by OlivierH
Your credits column must be a string. So MySQL use string comparison
to order your results.
Modify your table so that 'credtis' column will be INT or as needed but still a number so MySql will treat it as such and will return results as you want them (sorted numerically not by string comparison)
Why when i use order by seriq asc and have numbers like "10000" "100000" "97000"
script show me the results:
1: 10000
2: 100000
3: 97000
?
because they are stored in your column as strings
1- try to change the column seriq from VARCHAR/CHAR to INT.
2- You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS SIGNED);
Your seriq column must be a numeric column for values to be sorted numerically. If it's a text column, values will be sorted in alphabetical order as per their collation. For example:
CREATE TABLE Test
(
Foo int
);
INSERT INTO Test VALUES (10000);
INSERT INTO Test VALUES (100000);
INSERT INTO Test VALUES (97000);
select * from Test order by Foo asc;
Fiddle
The quick fix is to have MySQL convert the string to a numeric value in the ORDER BY clause.
Change your query to:
ORDER BY seriq+0 ASC
Note that MySQL will attempt to convert any string to a numeric value, reading characters up to the first "invalid" character, e.g. '123A' will be converted to a numeric value 123.
Changing the column type to int is the best solution as it will give you the best data storage and performance. However, if that is not an option, the following workaround is possible:
select * from foo order by seqid+0
This forces a type cast of the order by column to int, and the sort happens numerically.
I have this table:
I need to query the table and ask the following questions:
How many rows matching uri 'x' exist with unique IP addresses between 'y' and 'z' dates.
I was experimenting with COUNTs but I couldn't seem to get the result I needed...
Try using COUNT(DISTINCT())
Returns a count of the number of rows with different non-NULL expr values.
So your query would be something like
SELECT COUNT( DISTINCT( user_ip ) )
FROM table
WHERE timestamp BETWEEN Y and Z
The DISTINCT keyword enforces that only unique entries are returned in the query. As the above answer by ConroyP mentions you can nest DISTINCT within other functions in SQL. Note that this is has a different function from 'UNIQUE' which enforces uniqueness constraints in the Data Definition Language part of SQL. Some databases also allow you to substitute the keyword UNIQUE for DISTINCT in the query - but this doesn't seem to work everywhere.