SQL CREATE SCHEMA Statement

tags: #sql/basic_statements

What is a schema?

A schema is a collection of database objects including tables, viewstriggersstored proceduresindexes, etc. It defines the structure and organization of the data within the database, managed by a database management system.

Screen Shot 2023-04-07 at 7.00.51 PM.png

NOTE: In most relational database management systems (RDBMS), a database can have multiple schemas.

Why would we use multiple schemas?

Initializing a database schema

Rarely Used

This command is not used very commonly. Often times the company will already have a database created for you to work on.

The CREATE SCHEMA statement defines a schema:

CREATE SCHEMA <schema_name>

Within the same statement, we can grant privileges on objects:

CREATE SCHEMA <db_name> AUTHORIZATION "<authorization_name>"

How to add objects to a schema?

Once the schema has been defined, we can create objects for the schema.

Explicitly Creating an Object

To explicitly create object in a given database, we can use the dot notation following the given syntax after the command DATABASE_NAME.OBJ_NAME.

1. Creating tables
CREATE TABLE tableName
2. Creating views
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
3. Creating an index
CREATE INDEX index_name
ON table_name (column1, column2, ...);
4. Creating a trigger
// Before triggers (example task: insert or update on)
CREATE TRIGGER trigger_name
BEFORE INSERT OR UPDATE ON table_name
FOR EACH ROW
BEGIN
  -- statements here
END;


// After triggers
CREATE TRIGGER trigger_name
AFTER INSERT OR UPDATE ON table_name
FOR EACH ROW
BEGIN
  -- statements here
END;
5. Creating a function
CREATE FUNCTION function_name(param1 datatype, param2 datatype, ...) RETURNS return_datatype
BEGIN
  -- statements here
  RETURN value;
END;
Powered by Forestry.md