How to get two random records with Django

The order_by(‘?’)[:2] solution suggested by other answers is actually an extraordinarily bad thing to do for tables that have large numbers of rows. It results in an ORDER BY RAND() SQL query. As an example, here’s how mysql handles that (the situation is not much different for other databases). Imagine your table has one billion … Read more

Alphanumeric sorting with PostgreSQL

The ideal way would be to normalize your design and split the two components of the column into two separate columns. One of type integer, one text. With the current table, you could: SELECT col FROM tbl ORDER BY (substring(col, ‘^[0-9]+’))::int — cast to integer , substring(col, ‘[^0-9_].*$’); — works as text The same substring() … Read more

Order results by COUNT without GROUP BY

You need to aggregate the data first, this can be done using the GROUP BY clause: SELECT Group, COUNT(*) FROM table GROUP BY Group ORDER BY COUNT(*) DESC The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.

PostgreSQL ORDER BY issue – natural sort

Since Postgres 9.6, it is possible to specify a collation which will sort columns with numbers naturally. https://www.postgresql.org/docs/10/collation.html — First create a collation with numeric sorting CREATE COLLATION numeric (provider = icu, locale=”en@colNumeric=yes”); — Alter table to use the collation ALTER TABLE “employees” ALTER COLUMN “em_code” type TEXT COLLATE numeric; Now just query as you … Read more

TSQL – Is it possible to define the sort order?

It’s incredibly clunky, but you can use a CASE statement for ordering: SELECT * FROM Blah ORDER BY CASE MyColumn WHEN ‘orange’ THEN 1 WHEN ‘apple’ THEN 2 WHEN ‘strawberry’ THEN 3 END Alternately, you can create a secondary table which contains the sort field and a sort order. TargetValue SortOrder orange 1 apple 2 … Read more

SQL Show most recent record in GROUP BY?

Start with this: select StudentId, max(DateApproved) from tbl group by StudentId Then integrate that to main query: select * from tbl where (StudentId, DateApproved) in ( select StudentId, max(DateApproved) from tbl group by StudentId ) You can also use this: select * from tbl join (select StudentId, max(DateApproved) as DateApproved from tbl group by StudentId) … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)