Select last added number in postgres

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghjk
    Contributor
    • Jan 2008
    • 250

    Select last added number in postgres

    When I insert a new data I want to check whether user already exist and also I want to take the last inserted record number and increment it by one. How can I check both conditions in one select statement? This is my code.
    Code:
    $result = pg_query($dbconn, "SELECT \"No\",\"Name\" FROM \"User\" ORDER BY \"No\" ASC;");
    while($row = pg_fetch_array($result)){
    	$Name=$row['Name'];
         if($Name==$FullName)
    		{
    			echo "User already exist!";
    		}
    }
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    You don't do that last criteria in the same SQL, besides being next to impossible (yes you can do it with Unions and stuff, i know) but it's now how you do it.

    You primary key field (the one you want to increment I assume) should be auto_increment. in mysql there is mysql_insert_id () which gives you the last insert in that session.



    postgres should have something similar, I just don't know it.

    1. Check user doesn't exist
    2. Do your insert
    3. Get the last insert id (if you need it)

    Dan

    Comment

    Working...