Question: I want to create an Won Opportunity in CRM but I am getting following error.

error:

> 
> Additional information: 3 is not a valid status code for state code
>  OpportunityState.Open on opportunity with Id
>  8e99128b-3ef0-e711-8145-e0071b6641f1.
> 
> 
> 

Code:

```
 public void CreateOpportunity()
    {
        Entity opportunity = new Entity("opportunity");
        opportunity["name"] = "ABC";           
        opportunity["statecode"] = new OptionSetValue(1);
        opportunity["statuscode"] = new OptionSetValue(3);
        crmService.Create(opportunity);
    }

```

Answer: 
The problem with `limit` is it must order **all** the rows in the table *before* returning only the last 50, so it's always going to be slow and will get slower as the table grows (not scaleable).

The fastest way to get the last 50 is:

```
SELECT 
  *
FROM
  `table`
WHERE id > (SELECT MAX(id) FROM `table`) - 50

```

This will use the index on `id` to get the max id and again to get the top 50.

---

You should also try this slightly more complicated but potentially better optimisable:

```
SELECT 
  *
FROM
  `table`
WHERE id BETWEEN (SELECT MAX(id) FROM `table`) - 49
    AND (SELECT MAX(id) FROM `table`)

```

Compare actual run times andcuse the fastest.
You can derived table instead of the limit using `IN` or `subquery` which can be followed by a dynamic `rownum` variable. But this may be very complex and slow alternative.  

So, I suggest you to use the **same query** for fetching the last row from your table instead of any other alternative. Becuase of if you want to use a subquery then be you have to track the max id data and maybe some of the data is deleted or removed then it's can't return a proper number of records.
And also you can use `col name` instead of `*` for more optimization.