Select the ROW having the Maximum Value of a certain Column - mysql

For example, if my query returns two rows or more, I would like to select the row having the most recent date.
I'm doing something like this:
SELECT * FROM Table1 WHERE Name=Mark AND MAX(TIMESTAMP(date(str_to_date(DATE_REGISTERED,'%d/%m/%Y'))))
The error returned is:
#1111 - Invalid use of group function

To limit your results to only the most recent (based on a field named DATE_REGISTERED as per your example) you would do
SELECT * FROM Table1 WHERE Name='Mark' ORDER BY STR_TO_DATE(DATE_REGISTERED,'%d/%m/%Y') DESC LIMIT 1

you should use the order by statement:
SELECT * FROM Table1 WHERE Name=Mark
order by str_to_date(DATE_REGISTERED,'%d/%m/%Y') DESC LIMIT 1

Related

How to get the first item and the last item in a single sql statement

I was wondering how to grab the first item and the last item in a MySQL database. I know these two lines will do the work, but I am trying to limit it down to one line.
SELECT * FROM `test_table` order by ID asc limit 0,1
SELECT * FROM `test_table` order by ID desc limit 0,1
For example there is a table called test_table and it has 5 rows. I would like to get row number 1 and row number 5 in the same statement. This will save me from using many PHP if statements and will shorten up my code. Any help would be appreciated.
The following SQL does not get the first item:
SELECT * FROM `test_table` limit 0,1
It returns an arbitrary row. SQL tables and result sets are unordered, so limit without order by returns an indeterminate row.
The syntax to do what you want is:
(SELECT t.* FROM `test_table` t ORDER BY id ASC LIMIT 1)
UNION ALL
(SELECT t.* FROM `test_table` t ORDER BY id DESC LIMIT 1);
Note: If the table has only one row, this returns two rows, because the same row is the "first" and "last". If you want only one in this situation, you could use UNION rather than UNION ALL.
use union it will combine both sql queries and you the expected result
SELECT * FROM `test_table` limit 0,1
union
SELECT * FROM `test_table` order by ID desc limit 0,1
You can use the min and max ID if it's monotonically increasing -
SELECT * FROM `test_table`
WHERE ID IN ((SELECT MIN(ID) FROM `test_table`), (SELECT MAX(ID) FROM `test_table`));
I'd suggest running the explain for the query to see if it performs as per your expectation.

want to get total count of records in a table using COUNT(*) in MySQL

I have a mysql query which will return all the details from table along with i need max_row count i.e total no of rows in a table using COUNT(*) in a single select query without using cross join.
Note: MySQL version is earlier version of 8
Query :
SELECT * FROM tablename ORDER BY column name DESC LIMIT 0,10;
The total count of a table is simple, when you want to add it to every row.
SELECT
*
,(SELECT COUNT(*) FROM tablename ) count1
FROM tablename
ORDER BY column name
DESC LIMIT 0,10;,

Get last record from group data. MySql

Can anyone please help to get last record from the group.enter image description here
I think you need this:
select * from t where col = 85 order by id desc limit 1
According to your comment, this should get last records for every group: (this assumes that id is unique and "last record" means record, with highest id)
select t.* from t
inner join (select max(id) as maxid from t group by col) s
on t.id = s.maxid
To fetch the 1 row from mysql use 'limit' keyword.
MySQL supports the LIMIT clause to select a limited number of records, while Oracle uses ROWNUM.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
E.g.:
From your screenshot, subscription id is same for multiple id's you want to get last record which id is greater. The below query gets your result, grouped by subscription_id and ordered by id desc and limiting to 1 makes fetching only 1 row from database.
select * from tableName group by subscription_id order by id desc limit 1
You can used last() function.
SELECT LAST(CustomerName) AS LastCustomer FROM Customers;

mysql random rows

how to form a query to select 'm' rows randomly from a query result which has 'n' rows.
for ex; 5 rows from a query result which has 50 rows
i try like as follows but it errors
select * from (select * from emp where alphabet='A' order by sal desc) order by rand() limit 5;
u can wonder that why he needs sub query, i need 5 different names from a set of top 50 resulted by inner query.
SELECT * FROM t
ORDER BY RAND() LIMIT 5
or from your query result:
SELECT * FROM ( SELECT * FROM t WHERE x=y ) tt
ORDER BY RAND() LIMIT 5
This will give you the number to use as 'm' (limit)
TRUNCATE((RAND()*50),0);
...substitute 50 with n.
To check it try the following:
SELECT TRUNCATE((RAND()*50),0);
I should warn that this could return 0 as a result, is this ok for you?
For example you could do something like this:
SELECT COUNT(*) FROM YOUR_TABLE
...and store the result in a variable named totalRows for example. Then you could do:
SELECT * FROM YOUR_TABLE LIMIT TRUNCATE((RAND()*?),0);
where you substitute the '?' with the totalRows variable, according to the tech stack you are using.
Is it clearer now? If not please add more information to your question.

How do I use group by showing the newest row of data

Can someone please tell me how to use the group by clause, grouping by one of the keys in the table but yet having the newest timestamp at the top? I have multiple rows of data but I only want to show the newest row
If you want only the most recent one per group:
SELECT somefield
FROM table t1
WHERE timestamp = (SELECT MAX(timestamp)
FROM table t2
WHERE t1.somefield = t2.somefield);
Or just the latest most recent one:
SELECT somefield
FROM table
GROUP BY somefield
ORDER BY MAX(timestamp) DESC
LIMIT 1;
I think you're looking for the ORDER BY clause.
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
If you're grouping by a column, you're probably returning aggregate data. If the timestamp is unique for each row of aggregate data, you may need to use the MAX function (or the like) to return a single timestamp for each group. For example:
SELECT Foo.TypeID, SUM(Foo.Price) AS Price, MAX(Foo.OrderDate) AS LastOrder
FROM Foo
GROUP BY Foo.TypeID
ORDER BY MAX(Foo.OrderDate) DESC
If you only want the first row, you can use the LIMIT clause:
SELECT Foo.Bar, Foo.SomeTimestamp
FROM Foo
ORDER BY Foo.SomeTimestamp DESC
LIMIT 0, 1
This starts at row 0 and returns at most 1 row.