Mark
Mark

Reputation: 402

Maximum value in a column

Is there a more efficient way to do this? I want the maximum value of a column (int) in a given MySQL table using PHP.

$results = $conn->query("SELECT statement_id FROM statement ORDER BY statement_id DESC LIMIT 1");
$next_statment_id = $results->fetch_assoc();
$next_statment_id = $next_statment_id['statement_id'];
echo $next_statment_id;

Upvotes: 2

Views: 81

Answers (2)

Strawberry
Strawberry

Reputation: 33935

Consider the following:

SELECT COUNT(*) FROM test;
+----------+
| COUNT(*) |
+----------+
| 10000000 |
+----------+

SELECT i FROM test ORDER BY i DESC LIMIT 1;
+----------+
| i        |
+----------+
| 18482903 |
+----------+
1 row in set (0.00 sec)

SELECT MAX(i) FROM test;
+----------+
| MAX(i)   |
+----------+
| 18482903 |
+----------+
1 row in set (0.00 sec)

See. Not much in it.

Upvotes: 1

Shashank Shah
Shashank Shah

Reputation: 2167

MAX is an OK method too

SELECT MAX(statement_id) AS statementIdentity 
  FROM statement;

output produce something like this:-

+-------------------+
| statementIdentity |
+-------------------+
|       4           |
+-------------------+

Upvotes: 2

Related Questions