Skip to content
Education & Software

How to Use a DB in SQL: A Complete Guide to Database Management and Syntax

In this article

To use a database (DB) in SQL, you must first establish or identify the target database using commands like CREATE DATABASE database_name; and then select it as your active execution context using USE database_name; in systems like MySQL or Microsoft SQL Server. Once selected, all subsequent data definition and manipulation commands automatically execute within that specific database context.

Fundamental Concepts: What Does "Using a Database" Mean in SQL?

In Structured Query Language (SQL), "using a database" refers to establishing an active context within a Relational Database Management System (RDBMS). A single RDBMS server instance—such as MySQL, PostgreSQL, or Microsoft SQL Server—can host dozens or hundreds of distinct databases simultaneously. Each database acts as an isolated logical container holding its own collection of tables, views, stored procedures, indexes, and access control permissions.

When you connect to a database server, the server needs to know which logical container your queries should target. Setting the active database context prevents you from having to type the database name before every single table in your SQL queries. For example, without an active database context, querying a table requires specifying its fully qualified name, such as sales_db.public.orders. By explicitly setting the active database to sales_db, you simplify your SQL statements to target orders directly.

Understanding how database context works requires distinguishing between three structural layers:

  • Server Instance: The overarching database engine software running on a host machine or cloud instance.
  • Database (DB): The high-level logical container managed by the server instance.
  • Schema: A secondary organizational partition within a database (in engines like PostgreSQL and SQL Server) that groups related tables and security boundaries.
  • Database Objects: The actual tables, views, sequences, and stored procedures that reside inside a schema or database.

Step 1: Creating and Selecting a Database

Before manipulating data, you must either create a new database or select an existing one. The specific syntax varies slightly depending on whether you are working in MySQL, Microsoft SQL Server, PostgreSQL, or SQLite.

Creating a Database with CREATE DATABASE

To set up a brand-new storage container, use the standard Data Definition Language (DDL) command CREATE DATABASE. This command registers a new, empty database within the server instance.

CREATE DATABASE corporate_crm;

In production environments, database creation often includes optional parameters for character encoding, collation, and file storage locations. For instance, in MySQL or PostgreSQL, ensuring Unicode compatibility requires specifying UTF-8 encoding:

CREATE DATABASE corporate_crm CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Selecting an Active Database with USE

Once a database exists, you instruct your SQL session to target it using the USE keyword in compatible database systems.

USE corporate_crm;

Executing USE corporate_crm; updates your session state. Any subsequent table creation or data retrieval queries will implicitly execute inside corporate_crm until you change the context with another USE command or disconnect from the server.

Important Engine Variations: PostgreSQL and SQLite

Not all RDBMS platforms support the USE statement directly in standard SQL scripts:

  1. PostgreSQL: PostgreSQL does not implement the SQL-standard USE database_name; command because it maintains strict connection-level isolation between databases on the same server instance. To switch databases in PostgreSQL, you must either issue a command to change your client connection (such as \c database_name in the psql command-line interface) or connect directly to the target database in your application's connection string. Inside a single PostgreSQL database, context switching occurs at the schema level using SET search_path TO schema_name;.
  2. SQLite: SQLite is an embedded, file-based database engine that does not run a server daemon hosting multiple databases by default. To use a database in SQLite, you open a specific file on your file system. However, you can attach additional database files into an active session using the ATTACH DATABASE 'path/to/file.db' AS secondary_db; syntax.
How to Create a Front End for a SQL Server Database in 4 Steps
How to Create a Front End for a SQL Server Database in 4 Steps

Syntax Comparison Across Popular RDBMS Engines

Because different SQL database engines implement session context and database selection differently, the following table summarizes how to perform fundamental database management tasks across major RDBMS implementations.

Database Engine Select Active DB Syntax List All Databases Command Schema & DB Hierarchy Model Default Connection Port
MySQL / MariaDB USE db_name; SHOW DATABASES; Database and Schema are interchangeable terms. 3306
Microsoft SQL Server USE db_name; SELECT name FROM sys.databases; Server Instance > Database > Schema > Table 1433
PostgreSQL \c db_name (in psql) or reconnect SELECT datname FROM pg_database; Server Instance > Database > Schema > Table 5432
Oracle Database ALTER SESSION SET CURRENT_SCHEMA = schema_name; SELECT name FROM v$database; Container DB > Pluggable DB > Schema (User) > Table 1521
SQLite ATTACH DATABASE 'file.db' AS alias; .databases (in CLI tool) Single File = Single Database (Main schema default) N/A (Embedded)

Querying Across Databases Using Fully Qualified Names

You do not always need to switch your active database context to access data stored in another database on the same server instance. Standard SQL supports multi-part object identifiers, commonly called fully qualified names.

A fully qualified name explicit outlines the full navigational path to a specific object. The complete structure follows this pattern:

[database_name].[schema_name].[table_name]

Example: MySQL / MariaDB

In MySQL, where database and schema are synonymous, fully qualified table access uses a two-part naming convention:

SELECT order_id, total_amount FROM sales_db.orders WHERE order_status = 'Completed';

In this query, even if your active database is set to inventory_db, SQL successfully retrieves data from the orders table located inside sales_db.

Example: Microsoft SQL Server

SQL Server supports a three-part (and sometimes four-part for linked servers) naming convention:

SELECT e.employee_id, e.last_name, d.department_name FROM HR_Production.dbo.employees AS e INNER JOIN HR_Central.dbo.departments AS d ON e.department_id = d.department_id;

This capability allows developers to write cross-database joins inside a single SQL query block, provided the database user account holds sufficient reading permissions across all referenced databases.

Managing Database Structure and Executing DML

After selecting your database context, you perform structural operations using Data Definition Language (DDL) and operational data updates using Data Manipulation Language (DML).

Creating Tables inside the Active Database

When a database context is selected via USE db_name;, executing a table creation statement automatically creates the table within that active container:

USE corporate_crm; CREATE TABLE customers ( customer_id INT PRIMARY KEY AUTO_INCREMENT, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );

Performing Data Operations

Subsequent DML statements interact directly with the tables stored inside the selected database context:

-- Inserting data into the active database table INSERT INTO customers (first_name, last_name, email) VALUES ('Jane', 'Doe', 'jane.doe@example.com'); -- Querying data from the active database table SELECT customer_id, email FROM customers WHERE last_name = 'Doe';

Programmatic Database Connections in Software Applications

In modern software development, developers rarely issue raw USE db_name; queries manually. Instead, applications configure the target database directly within connection strings managed by database drivers (such as JDBC for Java, psycopg2 or asyncpg for Python, mysql2 for Node.js, or ADO.NET for C#).

Standard Connection String Formats

Most SQL database drivers accept a Database URL format that defines the database engine, host, port, authentication credentials, and default target database in a single string:

  • PostgreSQL URI: postgresql://username:password@localhost:5432/corporate_crm
  • MySQL URI: mysql://username:password@127.0.0.1:3306/corporate_crm
  • SQL Server Connection String: Server=myServerAddress;Database=corporate_crm;User Id=myUsername;Password=myPassword;

When an application opens a connection using these parameters, the driver establishes an authenticated TCP/IP session and automatically sets the active database to corporate_crm. This eliminates the need to send an explicit USE corporate_crm; command before executing queries inside application code.

Permissions, Security, and Database Access Control

Using a database requires appropriate privileges granted by a Database Administrator (DBA). RDBMS platforms implement granular access controls using standard SQL security statements like GRANT and REVOKE.

Granting Access to a Database

To allow a database user to switch to and interact with a database, an administrator must explicitly grant access rights.

In MySQL:

GRANT SELECT, INSERT, UPDATE, DELETE ON corporate_crm.* TO 'app_user'@'localhost'; FLUSH PRIVILEGES;

In PostgreSQL:

GRANT CONNECT ON DATABASE corporate_crm TO app_user; GRANT USAGE ON SCHEMA public TO app_user; GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_user;

Applying the Principle of Least Privilege

When configuring user access:

  • Never run application connections using administrative accounts (such as root in MySQL or postgres in PostgreSQL).
  • Grant permissions only on the specific databases and schemas required for the application's function.
  • Separate read-only privileges (for reporting tools) from read-write privileges (for transactional web applications).

Troubleshooting Common SQL Database Context Errors

Working with databases in SQL can lead to distinct session context and access errors. Understanding how to resolve these issues speeds up debugging.

1. Error: "No database selected" (MySQL Error 1046)

This error occurs when you attempt to execute DDL or DML statements (like CREATE TABLE, SELECT, or INSERT) without explicitly setting a database context or using fully qualified table names.

  • Fix: Execute USE database_name; before running your query, or specify fully qualified table names (database_name.table_name).

2. Error: "Unknown database 'db_name'"

This error signifies that the database name specified in your USE statement or connection string does not exist on the connected server instance, or contains a typo.

  • Fix: Verify available databases by running SHOW DATABASES; (MySQL) or SELECT name FROM sys.databases; (SQL Server), and check for case-sensitivity discrepancies.

3. Error: "Permission denied for database"

This occurs when the authenticated user attempts to connect to or query a database without sufficient privilege assignments.

  • Fix: Have a DBA issue appropriate GRANT statements for the target database and user host.

Best Practices for SQL Database Administration

Following structured guidelines ensures consistent performance, clean data modeling, and seamless operational maintenance across database environments.

  1. Use Consistent Case Conventions: SQL keywords are case-insensitive, but database, schema, and table names often depend on the underlying host file system (especially on Linux environments). Adopt a consistent naming convention, such as lower_snake_case (e.g., sales_reporting_db), across all database identifiers.
  2. Script Database Initialization: Never rely entirely on manual GUI client operations to set up databases. Store all database definition commands (CREATE DATABASE, CREATE SCHEMA, initial table definitions) in version-controlled SQL migration scripts.
  3. Isolate Environments into Separate Databases: Maintain complete logical separation between development, testing, staging, and production environments by using separate databases or distinct database server instances.
  4. Monitor Active Database Connections: Unused open database connections consume system RAM and thread capacity. Use connection pools with configured connection lifespans and timeouts in high-throughput applications.

Frequently Asked Questions

What happens if I execute a query without selecting a database?

If you execute a table-level query without selecting a database context, most RDBMS engines (such as MySQL) throw an error stating that no database was selected. However, if your query only references system functions or arithmetic (e.g., SELECT 1 + 1; or SELECT CURRENT_TIMESTAMP;), the query executes successfully without needing an active database context.

How do I switch databases in PostgreSQL if USE does not work?

In PostgreSQL, you cannot switch databases within an active SQL transaction block using a standard SQL statement. In the psql command-line utility, use the meta-command \c database_name to establish a new connection to the desired database. In client applications, configure your connection pool to open separate connection handles for each target database.

Can I query two different databases in a single SQL query?

Yes, provided both databases reside on the same server instance (or are connected via linked server bridges) and your database user account holds SELECT permissions on both databases. You reference tables across databases by writing fully qualified table names, such as SELECT * FROM db_one.table_a INNER JOIN db_two.table_b ON db_one.table_a.id = db_two.table_b.id;.

How do I delete or drop a database in SQL?

To completely delete a database along with all of its contained tables, schemas, and stored data, execute the DROP DATABASE database_name; command. Exercise extreme caution when running this command, as dropping a database is irreversible without restoring from a backup.

What is the difference between a database and a schema in SQL?

A database is the top-level logical container managed by an RDBMS server instance, while a schema is an organizational namespace inside a database. In engines like PostgreSQL and SQL Server, a single database can contain multiple schemas (such as public, sales, and hr), allowing teams to organize objects and enforce granular permissions within one database. In MySQL, the terms "database" and "schema" are synonymous.

Strategic Next Steps for Database Management

To build proficiency in SQL database administration and usage, move from basic context selection to structured schema management and automation:

  1. Master Database Migration Tools: Transition from manual SQL scripts to structured database migration engines such as Liquibase, Flyway, or ORM-integrated migration tools (like Prisma, Alembic, or EF Core) to version-control database structural changes.
  2. Audit Security Policies: Inspect your database access controls by querying system catalog tables to ensure database users hold only the exact permissions needed for their applications.
  3. Implement Connection Pooling: Ensure backend services use production-ready database connection pooling mechanisms to manage database server sessions efficiently and avoid connection resource exhaustion.