Copied from :

Just for Quick reference :

Sometimes, you really just want to delete the old one.  But the Object Model doesn’t have objects that go that deep.  Hence there are no way to do this via command-line either.

You need AppInstance to perform an uninstall.  If you can’t get an AppInstance, but the AppPackage is still in your Site Collection, you are pretty much stuck.

Let’s go check out the content database.  Disclaimer: Do this if you are curious.  Also, don’t do this on your production.

SELECT [PackageFingerprint]
  FROM [WSS_CONTENT_DB].[dbo].[AppPackages]

You want to know which Site Collection it is.  So figure out which AppPackage is the one SharePoint can’t delete – by cross-checking the SiteId

PackageFingerprint is an important field that we’ll need in a minute.  It acts like a unique identifier.
IsDownloadInvalidated is probably 0 (meaning it is valid).  You just can’t delete it.

SharePoint has a few nice store procedures.

exec [WSS_CONTENT_DB].[dbo].proc_App_InvalidatePackage
    @PackageFingerprint, @SiteId

-- example
exec [WSS_CONTENT_DB].[dbo].proc_App_InvalidatePackage

This stored procedure will flag the AppPackage as Invalid.  If you do SELECT * FROM AppPackages again, you’ll see it is now IsDownloadInvalidated = 1

So SharePoint now thinks there was something wrong with the download of this package :-)Let’s invoke SharePoint’s auto-immune system and nuke the AppPackage

exec [WSS_CONTENT_DB].[dbo].proc_App_DeleteInvalidatedDownloadApp
    @PackageFingerprint, @SiteId

-- same arguments.  

This one will nuke the AppPackage clean.

You can now go back to PowerShell and redeploy your App.

PS> $App = Import-SPAppPackage -Path <Path> -Site <Url> -Source <Source>
PS> Install-SPApp -Web <Url> -Identity $App