Puru Vijay
Puru Vijay

Reputation: 5

php,mysql-select last content in id column using mysql

Hey In a site Pokeheroes,there is a thing "Registered users: 54,805 .".I know that it sees last id in the users database and shows it here.I want to know how this feature of sql works that it checks what the last number in ID is and then shows it.Please help me

Upvotes: 0

Views: 72

Answers (3)

Exception
Exception

Reputation: 787

There are two possibilities to fetch total number of users present in you database. 1. get the last inserted id 2. get total number of rows in the table(there may be possibilities some users list may get deleted from table)

Bernd Buffen answer is smart . you can also use another query if you want & this is-

SELECT id AS max_userid
FROM table_name
ORDER BY id DESC 
LIMIT 1

and for point no 2 I will suggest viam's answer is good because this will give how ACTUAL users are present in your db instead of showing last inserted id you can show actual users.

Upvotes: 1

Rahul
Rahul

Reputation: 77926

You got it already by using MAX() aggregate function but there is another way by using ORDER BY clause like below; which will order the ID column in descending order and so the maximum ID number will be at top and from there you can use LIMIT clause to get the top result.

SELECT ID AS MAX_ID
FROM USERS
ORDER BY ID DESC
LIMIT 1;

Upvotes: 1

Bernd Buffen
Bernd Buffen

Reputation: 15057

@viam

If you use count(*), it returns only the number of records in the table. so it is better to use:

SELECT MAX(id) AS max_userid
FROM USERS;

Upvotes: 3

Related Questions