Does each queries create new connection in database

In most databases, each query does not necessarily create a new connection. Instead, a connection is typically established when the database is first connected to, and then reused for subsequent queries.

Here's how it usually works:

  1. Connection establishment: When your application (e.g., a web server, a script, or a program) connects to a database, a new connection is established. This involves creating a socket, authenticating the user, and setting up the communication channel.
  2. Query execution: When you send a query to the database, it is executed on the existing connection. The database server processes the query and returns the results to your application.
  3. Connection reuse: The connection remains open and is reused for subsequent queries, as long as the connection remains idle for a certain period of time (known as the "connection timeout"). This is done to improve performance and reduce the overhead of establishing a new connection.

However, there are some scenarios where a new connection might be created for each query:

  1. Connection pooling: Some databases, like Oracle, use connection pooling, where multiple connections are created and managed by the database server. In this case, each query might use a different connection from the pool.
  2. Connectionless protocols: Some databases, like MongoDB, use connectionless protocols, where each query is sent as a separate request, and a new connection is established for each query.
  3. Error handling: If an error occurs during query execution, the connection might be closed, and a new connection might be established for the next query.
  4. Database configuration: Some databases, like MySQL, allow you to configure the connection behavior. For example, you can set the connect_timeout parameter to control how long a connection remains idle before being closed.

In summary, while each query does not necessarily create a new connection, there are scenarios where a new connection might be created for each query. The specific behavior depends on the database system, connection pooling, and configuration settings.