SQL is used to manage and manipulate relational databases, which are made up of schemas, tables, and records. Understanding the relationship between databases, tables, and schemas is fundamental to effectively organizing and querying data.
A database is a collection of organized data that can be accessed, managed, and updated. It serves as the top-level structure in SQL, holding multiple schemas and tables.
-- Create a database CREATE DATABASE CompanyDB; -- Use the database USE CompanyDB;
A schema is a logical container within a database. It organizes objects such as tables, views, and stored procedures. Schemas help manage permissions and separate different parts of a database.
-- Create a schema CREATE SCHEMA HR; -- Create a table within the schema CREATE TABLE HR.Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(50), Position VARCHAR(50), Salary DECIMAL(10, 2) );
A table is a collection of rows and columns used to store data. Each column represents an attribute of the entity, and each row represents a record.
-- Create a table in the default schema CREATE TABLE Departments ( DepartmentID INT PRIMARY KEY, DepartmentName VARCHAR(100), ManagerID INT );
Databases contain schemas, which in turn contain tables. This hierarchy allows for a structured and scalable way to organize data.
-- Insert data into a table within a schema INSERT INTO HR.Employees (EmployeeID, Name, Position, Salary) VALUES (1, 'Alice Johnson', 'Manager', 80000.00); -- Query data from the table SELECT * FROM HR.Employees;
When querying tables across schemas, you must specify the schema name.
SELECT e.Name, d.DepartmentName FROM HR.Employees e JOIN Departments d ON e.EmployeeID = d.ManagerID;
Databases, schemas, and tables are fundamental concepts in SQL. Understanding their relationships and how to interact with them is key to managing and organizing data efficiently in a relational database system.