When is the SQL Server database ready to accept queries?

The SQL Server database is ready to accept queries as soon as:

SELECT DATABASEPROPERTYEX(N'database name', 'Collation')

does not return NULL.

From the documentation for DATABASEPROPERTYEX (Transact-SQL):

Note: The ONLINE status may be returned while the database is being opened and is not yet recovered. To identify when a database can accept connections, query the Collation property of DATABASEPROPERTYEX. The database can accept connections when the database collation returns a non-null value. For Always On databases, query the database_state or database_state_desc columns of sys.dm_hadr_database_replica_states.


SQL Server databases start up, but then they need to analyze the transaction log to roll transactions forward & backward. This process can take anywhere from milliseconds to hours (even days!) in the event of a long-running transaction, many (think thousands) of user databases, or databases with lots (think tens of thousands) of virtual log files.

If you only want the app to get in when recovery is done and the database is ready, have the application retry its connection.

If you want the app to be able to get into SQL Server immediately, but maybe not be able to run any queries yet, set its default database to TempDB instead of a user database. It'll likely be online right away even when user databases are unavailable.