SQL: Structured Query LanguageSQL FundamentalsDatabase Schemas and Namespaces

What is a schema in a relational database?

Question 6 of 30 · Updated

On this page

A schema is the structural definition of a relational database or, in database systems such as PostgreSQL, a named namespace that groups database objects. The term has two related meanings: the logical blueprint describing tables, columns, relationships and constraints, and a named container used to organize and qualify objects inside a database.

For example, an online store might have a logical schema describing customers, orders and their relationships. In PostgreSQL, it could organize these objects into named schemas such as sales and inventory within the same database. Understanding the two meanings prevents a common interview mistake: confusing the database's design with a particular namespace.

1. Schema as the logical blueprint#

Imagine a university enrollment application. Before storing actual student or course data, you decide the structure:

TableImportant columnsStructural rules
studentsstudent_id, namestudent_id identifies each student
coursescourse_id, titlecourse_id identifies each course
enrollmentsstudent_id, course_idBoth identifiers reference existing records; the pair can be unique

This blueprint describes the database schema. It defines how data is represented and what rules it must follow. Actual records, such as student 101 enrolling in course 7, are instances of data stored under that structure.

A schema can include definitions of tables, columns, data types, keys, constraints, relationships and other database objects such as views. An entity-relationship diagram may communicate the conceptual design; SQL data definition language (DDL) implements an actual database structure. Physical implementation details such as storage layout are a separate concern, although some database design documentation also includes indexes and physical design choices.

Schema versus instance: A table definition can remain unchanged while its rows change thousands of times. Inserting a new student changes the data instance; adding a new required column changes the schema. Even an empty database can have a fully defined schema.

2. Schema as a named namespace in PostgreSQL#

In PostgreSQL, a database can contain multiple named schemas. Each schema can contain tables, views, functions, sequences, types and other supported objects. The namespace permits two objects of the same kind with the same name to exist in different schemas.

Consider the following simplified organization:

Database: company
  sales
    tickets
  support
    tickets
  public
    shared_reference_data

sales.tickets and support.tickets are distinct tables, even though their unqualified names are identical. The prefix before the dot identifies the schema, while the suffix identifies the table. The word public here is the name of a PostgreSQL schema, not a guarantee that everyone can access its objects.

A schema is not a separate PostgreSQL database. An ordinary PostgreSQL connection selects one database; within that database, SQL can reference objects in multiple schemas, subject to permissions. Querying another PostgreSQL database generally requires another connection or an explicitly configured mechanism such as a foreign data wrapper.

3. Practical example: organize tables with the same name#

Run this PostgreSQL-specific setup in a fresh, disposable database using a role that can create schemas and tables. Do not execute it in an existing production database. The two CREATE SCHEMA commands below are illustrative PostgreSQL DDL and were not executed in this session.

SQL
CREATE SCHEMA sales; CREATE SCHEMA support; CREATE TABLE sales.tickets ( ticket_id INTEGER PRIMARY KEY, subject TEXT NOT NULL ); CREATE TABLE support.tickets ( ticket_id INTEGER PRIMARY KEY, subject TEXT NOT NULL ); INSERT INTO sales.tickets (ticket_id, subject) VALUES (1, 'Pricing request'); INSERT INTO support.tickets (ticket_id, subject) VALUES (1, 'Login issue');

The tables have the same column definitions, and both contain ticket ID 1. Their primary keys are independent because they belong to separate tables. The schemas provide unambiguous object names, not a shared uniqueness rule across tables.

Query each table explicitly:

SQL
SELECT ticket_id, subject FROM sales.tickets ORDER BY ticket_id; SELECT ticket_id, subject FROM support.tickets ORDER BY ticket_id;
Query sourceticket_idsubject
sales.tickets1Pricing request
support.tickets1Login issue

You can also combine data from multiple schemas in the same database. This query uses UNION ALL to append both result sets and adds a source label so that the otherwise identical ticket IDs remain distinguishable.

SQL
SELECT 'sales' AS source, ticket_id, subject FROM sales.tickets UNION ALL SELECT 'support', ticket_id, subject FROM support.tickets ORDER BY source, ticket_id;
sourceticket_idsubject
sales1Pricing request
support1Login issue

Validation and dialect note: The two qualified SELECT queries, UNION ALL, CREATE TABLE definitions and INSERT statements were tested successfully in an isolated SQLite 3.46.1 in-memory connection using attached databases as a namespace analogue. SQLite does not implement PostgreSQL CREATE SCHEMA. To reproduce the tested setup in SQLite, replace only the two CREATE SCHEMA statements with:

SQL
ATTACH DATABASE ':memory:' AS sales; ATTACH DATABASE ':memory:' AS support;

Then execute the remaining CREATE TABLE, INSERT and SELECT statements unchanged in the same connection. These attached databases are separate SQLite databases, not PostgreSQL schemas; the test establishes qualified naming and the expected query results, not equivalence of database architecture or permission semantics.

4. What happens if a schema name is omitted?#

PostgreSQL has a session-level setting called search_path, which determines how unqualified names are resolved. For example, if both sales and support contain a table named tickets, a query using only tickets can resolve to different objects depending on the effective search path.

SQL
-- PostgreSQL illustration; run only in the disposable example session. SET search_path TO sales, support; SELECT ticket_id, subject FROM tickets; SET search_path TO support, sales; SELECT ticket_id, subject FROM tickets; RESET search_path;

Assuming the example tables exist and are accessible, with no shadowing temporary object, the first SELECT is expected to return the Pricing request and the second the Login issue. The database resolves the unqualified table name using the effective lookup order; changing the search path does not move or copy data. PostgreSQL has additional lookup rules for system catalogs and temporary schemas, so the configured list is not always the entire effective lookup order.

This PostgreSQL search-path demonstration is illustrative and was not executed. In application queries and migrations, explicitly qualifying important object names is often clearer and avoids accidentally targeting a same-named object. Be particularly careful with writable schemas in a privileged session's search path: object shadowing can lead to unexpected or unsafe name resolution.

5. Inspect schemas using database metadata#

Relational databases often provide metadata about their structure. PostgreSQL exposes standard information-schema views that can help you inspect schemas, tables and columns.

The following read-only query lists two standard PostgreSQL schemas:

SQL
SELECT schema_name FROM information_schema.schemata WHERE schema_name IN ('information_schema', 'pg_catalog') ORDER BY schema_name;

| schema_name | |---| | information_schema | | pg_catalog |

information_schema provides standards-oriented metadata views; pg_catalog contains PostgreSQL's system catalog objects and other built-in objects. Visibility of metadata can depend on the current user's privileges.

To inspect two metadata views in the information schema itself:

SQL
SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema = 'information_schema' AND table_name IN ('columns', 'tables') ORDER BY table_name;
table_schematable_name
information_schemacolumns
information_schematables

Both exact catalog queries were executed successfully against PostgreSQL using read-only system metadata; they did not read application records or create or modify schemas. The isolated SQLite tests above passed all three expected query-result assertions. Full PostgreSQL DDL and search-path tests were unavailable in the isolated environment.

6. Why organize objects into schemas?#

  • Organization: Keep sales, billing, inventory and support objects grouped by purpose instead of putting every object in one namespace.
  • Name collision avoidance: Separate modules can have a settings or tickets table without requiring every table name to be globally unique across the database.
  • Maintenance: Schema-qualified names make migrations and ownership responsibilities clearer. Grouping by domain can help engineers understand which component owns an object.
  • Access control: In PostgreSQL, schema-level USAGE and CREATE privileges control aspects of namespace access, and object-level privileges control operations on individual tables or other objects. Row-level security can enforce row-specific access policies where appropriate.

Important: A schema is not automatically a security boundary. Creating a private schema does not guarantee that its contents are inaccessible, and naming a schema after a tenant does not by itself enforce tenant isolation. Permissions, ownership, role configuration, application access patterns and, where applicable, row-level security must be designed and verified together. For Supabase specifically, exposing a schema through the Data API is an additional configuration decision; avoid unnecessarily broad grants or exposing internal objects.

7. Database vs schema vs table#

ConceptPostgreSQL-oriented meaningExample
DatabaseA named database selected by a connectioncompany
Schema (namespace)Named grouping of objects within a databasesales
TableNamed object containing rows and columnssales.tickets
ColumnA named attribute in a tablesubject
RowOne data occurrence in a table(1, 'Pricing request')

Terminology differs across products. PostgreSQL and SQL Server support named schemas inside a database; MySQL generally treats SCHEMA as a synonym for DATABASE. In SQLite, qualifiers such as main, temp and attached database names refer to database namespaces rather than PostgreSQL-style schemas. Do not assume that identical syntax or permissions work across engines.

8. Common interview mistakes#

  • Saying a schema is the actual collection of rows rather than the structural definition or namespace.
  • Treating schemas and databases as interchangeable in every SQL product.
  • Assuming every table name is unique across all schemas in PostgreSQL.
  • Believing an unqualified query always targets the intended table, regardless of search path.
  • Treating the existence of a private or tenant-specific schema as proof of secure access isolation.
  • Confusing a schema migration, which changes structural definitions, with an ordinary INSERT or UPDATE that changes data.

9. Interview-ready answer#

A schema describes how a relational database is structured, including its tables, columns, data types, relationships and constraints. In systems such as PostgreSQL, a schema is also a named namespace inside a database that groups objects and allows same-named tables to coexist in different namespaces, such as sales.tickets and support.tickets. Schema-qualified names make object references explicit. The database contains the data, while the logical schema defines its structure. Schemas help with organization and permission management, but access must be enforced through appropriate privileges and policies. Exact schema terminology varies by database engine.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning