Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

PostgreSQL Create Table


Connect to the Database

To create a new database table using the SQL Shell, make sure you are connected to the database. If not, follow the steps in the Get Started chapter of this tutorial.

Once you are connected, you are ready to write SQL statements!


Create Table

The following SQL statement will create a table named cars in your PostgreSQL database:

CREATE TABLE cars (
  brand VARCHAR(255),
  model VARCHAR(255),
  year INT
);

When you execute the above statement, an empty table named cars will be created, and the SQL Shell application will return the following:

CREATE TABLE

In the SQL Shell application on your computer the operation above might look like this:


SQL Statement Explained

The above SQL statement created an empty table with three fields: brand, model, and year.

When creating fields in a table we have to specify the data type of each field.

For brand and model we are expecting string values, and string values are specified with the VARCHAR keyword.

We also have to specify the number of characters allowed in a string field, and since we do not know exactly, we just set it to 255.

For year we are expecting integer values (numbers without decimals), and integer values are specified with the INT keyword.


Display Table

You can "display" the empty table you just created with another SQL statement:

SELECT * FROM cars;

Which will give you this result:

 brand | model | year
-------+-------+------
(0 rows)

In the SQL Shell application on your computer the operation above might look like this:

In the next chapters we will learn how to insert data into a table, and also more on how to retrieve data from a table.


PostgreSQL Exercises

Test Yourself With Exercises

Exercise:

Write the correct SQL statement to create a new table called "cars":

 (
  brand VARCHAR(255),
  model VARCHAR(255)
);
        

Start the Exercise


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.