Creating and Modifying Tables
In this chapter we will be covering some of the most commonly used queries to create and modify tables in SQL.
Examples below are created via PostgreSQL.
1. Creating Tables
1.1. Basic Format (with no input data)
For all data types, please check PostgreSQL Documentation
1.2. Using Another Table (with input data)
1.3. Using SELECT Statement (with input data)
i. From a Different Table
ii. Manual
Table schemas for the tables created other than the 1st method (Basic Format) should be adjusted upon creation. Therefore, to create a table using a SELECT statement, first create the table with desired datatypes and constraints, and then transfer the data into newly created table: -- Step 1: Create a new table with a serial column.
CREATE TABLE employees_short (
emp_id serial PRIMARY KEY,
emp_name text );
-- Step 2: Copy data from the old table to the new one.
INSERT INTO employees_short(emp_name)
SELECT emp_name FROM employees;
2. Data Modifications
2.1. Inserting Rows (Populating Table)
2.2. Updating Rows
2.3. Deleting Rows
3. Table Modifications (Most Commonly Used)
3.1. Adding columns
3.2. Renaming the table
3.3. Dropping tables
Different databases offer different approaches to modify their tables. Therefore, it is advisable to refer to your database documentation before proceeding with any changes. Some of the most commonly used database systems: Postgres, MySQL, SQLite, and Microsoft SQL Server
4. Column Modifications (Most Commonly Used)
4.1. Renaming columns
4.2. Changing columns' datatype
4.3. Dropping columns
For complete list of PostgreSQL column modifications, please check the documentation.
If you need to see the datatype for existing tables in Postgres, please check the Displaying Existing Tables' Columns and Their DataTypes in the Data Types section.
5. Creating Views
A view
is a stored query that acts as a virtual table. Instead of storing data directly, views store queries that retrieve data from one or more underlying tables in the database. When you query a view, PostgreSQL dynamically executes the underlying query and presents the results as if they were stored in a table.
5.1. Creating View(s)
5.2. Deleting View(s)
Last updated