…
…
SQL and Database Fundamentals · Lesson 28 / 41 · Creating tables and constraints
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Student Affairs also wants to keep student clubs in the database: each club's name, founding date, yearly budget, and whether it is active. Until now you have queried tables that were already built; in this lesson you will design and create your own table for the first time. You will build the club system step by step through this unit, and the first step is the club table.
This is the first lesson of a new unit. So far you have always asked questions of tables that someone else built: student, course, and enrollment were ready, and you only pulled data out of them. In this unit you move to the other side of the desk. A person who designs a database first answers these questions: Which pieces of information will be stored? Which column will hold each one? What kind of value can go into that column? The six lessons of this unit are parts of the same job: in this lesson you build the table, then you add rules to it, connect tables to each other, model the whole system, separate repeated data, and finally change an existing table.
In this lesson you will:
CREATE TABLE command.information_schema.columns and save the result of a query as a new table with CREATE TABLE AS.First, an important note about the working environment of this course: every command you write here runs inside a transaction that is rolled back at the end. So the table you create disappears as soon as the commands finish, and the case database always returns to its original state. This way you can experiment without fear of breaking anything. But it creates a problem: if the table disappears right away, how will you see that it was created? The answer is the check query: right below the command that creates the table, in the same run, you write a SELECT that shows the structure of that table. Every example and every exercise in this lesson ends with a check query like this.
A table starts with a sentence. This is what Student Affairs asks for: "For each club, we will store its name, founding date, yearly budget, and whether it is active." There are four pieces of information in this sentence, and each one becomes a column. You also add a number that tells each club apart from the others; as you saw in lesson 2, every table needs a column that distinguishes its rows from each other. So the list has five columns: club number, name, founding date, budget, and active or not.
Then you give each column a name and a type. The name should be short and clear: id, name, founded_on, budget, is_active. The type decides which values can be written to that column; the types you saw in lesson 25 now go to work. The name is a text of at most 60 characters, the founding date is a day on the calendar, the budget is money with cents, and the active flag is yes or no. Match each part of the requirement with its column.
Match each part of the requirement sentence with its column name and type.
For each row, pick its match from the list, then check.
Tables are created with the CREATE TABLE command. The command takes the name of the table first, then the name and type of each column inside parentheses. Column definitions are separated by commas; there is no comma after the last column. In lesson 1 you divided SQL commands into groups: CREATE TABLE belongs to the definition commands (DDL). It does not create data; it creates the container for data.
When the command runs, an empty table is created: it has columns but no rows. You will add rows later. Below you see the command that creates the club table, and right under it the check query. The check query reads a view called information_schema.columns; you will see this view in detail in section 6. For now, all you need to know is this: it returns one row for each column of the table.
Example 1 (case): The club table
CREATE TABLE club ( id INTEGER, name VARCHAR(60), founded_on DATE, budget NUMERIC(10, 2), is_active BOOLEAN ); SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'club' ORDER BY ordinal_position;
| column_name | data_type |
|---|---|
| id | integer |
| name | character varying |
| founded_on | date |
| budget | numeric |
| is_active | boolean |
(5 rows)
Five columns came back, in the order you wrote them. ordinal_position is the position of the column in the table; sorting by it shows the columns in the order you defined them. character varying is the long name of VARCHAR, as you remember from lesson 25. You do not have to write each column on a separate line or align the types; you can write everything on one line. But in long tables, separate lines make it easier to see which column has which type and where the commas are. Speaking of commas:
Why does this command give an error?
CREATE TABLE club (id INTEGER, name VARCHAR(60),);
Putting the parts of the command in the right order is a good way to make the syntax stick in your mind. The lines below create an events table and check it; pay attention to the position of the line without a comma.
Put the lines of the command that creates and checks the event table in order. Column order: id, title, event_date.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
In table and column names, use lowercase letters, digits, and underscores; separate words with an underscore (enrollment_date, playlist). Do not use accented characters or spaces. A table name is usually singular, so it describes one record: student, club, event. This is not a rule, but it is a common habit that the case database follows too.
Why are capital letters not recommended? Because PostgreSQL converts names written without quotes to lowercase before storing them. If you write CREATE TABLE Club (Name VARCHAR(10));, the database stores a table named club and a column named name. When you look at information_schema.columns, you see club and name. So Club, CLUB, and club are the same table; capital letters only look different to the person writing. The easiest way to avoid confusion is to write names in lowercase from the start.
If you want to keep a space or a capital letter in a name, you can put the name in double quotes: CREATE TABLE "Club List" (...). This works, but it has a cost: from now on you must write this table in every query in the same way, with double quotes and letter by letter. If you write SELECT * FROM Club List;, PostgreSQL stops at the space and gives the error relation "club" does not exist; if you write club_list, it cannot find such a table either. Only SELECT * FROM "Club List"; works. With plain names, none of these troubles happen.
Choosing a type is the most important decision in a design, because changing it later is hard and a wrong type quietly produces wrong results. You met the types in lesson 25. The question to ask here is not what the value looks like, but what will I do with this column? These questions make the decision:
| Question | If yes, type | Example from the case |
|---|---|---|
| A whole number you will calculate with? | INTEGER | year, credits, capacity |
| A decimal number that must be exact (money, grades)? | NUMERIC(p, s) | gpa NUMERIC(3,2), budget NUMERIC(10, 2) |
| An ID or a code, even if it is made of digits? | VARCHAR(n) | student_no, phone, postal code |
| A text of limited length? Unlimited? | VARCHAR(n) / TEXT | name VARCHAR(60), description TEXT |
| A point on the calendar? | DATE |
It is important to read the two numbers in NUMERIC(p, s) correctly: p is the total number of digits and s is the number of digits after the decimal point. NUMERIC(10, 2) means 10 digits in total; 2 of them go to the cents, so 8 digits remain before the decimal point. The largest value is 99,999,999.99. If you try to write 123456789.99 into it, you get the error numeric field overflow; if you write 12.345, it is rounded to the two digits after the decimal point and stored as 12.35. So if a price is "at most $9,999.99", you need 6 digits: NUMERIC(6, 2).
The belief that "every value made of digits is a number" shows up most often with phone numbers. See what happens when you try to store a phone number in a number type. (You will see the command that adds rows in detail in lesson 34; here the ready-made row shows what the table accepts.)
OutputCREATE TABLE phonebook (phone INTEGER);
INSERT INTO phonebook VALUES (07911123456);
ERROR: integer out of range
CREATE TABLE phonebook (phone BIGINT);
INSERT INTO phonebook VALUES (07911123456);
SELECT * FROM phonebook;
phone
------------
7911123456An 11-digit number is above the limit of INTEGER, which is about 2.1 billion. It fits into BIGINT, but the leading 0 disappears: for numbers a leading zero means nothing, and 0791 and 791 are the same number. A number that starts with +44 cannot be written at all. Besides, you never add phone numbers or take their average. Make the decision yourself in the scenario below.
You will store the phone numbers of club members. The numbers are 11 digits and start with 0791; some members write them starting with +44. Which type do you choose for the phone column?
Pick an option and see what happens. There are no points; you can try the other options too.
The same logic applies to student numbers, postal codes, national ID numbers, and product codes. It is not a coincidence that the student_no column in the case is VARCHAR(9).
A type is not only a label, it is a guard: it rejects a value that does not fit the column. If you try to write a 10-character value into a VARCHAR(9) column, PostgreSQL does not cut the value and store it; it rejects it directly:
OutputERROR: value too long for type character varying(9)This is good: a wrong value is stopped at the door. But the guard knows only the rules of its type. If you store a date as text, the guard becomes a text guard and knows nothing about the calendar. Imagine that the dates in a table are stored in a VARCHAR(10) column in the form '01/05/2026', and look at what happens when it is sorted with ORDER BY event_date:
| Sorting with VARCHAR(10) | Sorting with DATE |
|---|---|
| 01/05/2026 | 2025-11-20 |
| 02/14/2026 | 2026-01-05 |
| 11/20/2025 | 2026-02-14 |
The order on the left is wrong: the date in November 2025 fell to the end, because texts are compared character by character, as you saw in lesson 27, and the month comes first: '11' sorts after '01' and '02'. The DATE column on the right gives the calendar order. A text column has one more flaw: it also accepts a day that does not exist on the calendar. See this yourself in the cell below.
Try it now· not graded; doesn't affect progress
The text column accepts the value 02/31/2026 without a problem: 10 characters, within the limit. The DATE column rejects the same day: date/time field value out of range: "2026-02-31". Only the date type knows that there is no February 31. The rule: a date is always stored as DATE (or TIMESTAMP if it has a time).
The database also keeps information about its own tables in tables. The information_schema.columns view stores, row by row, the information about all columns in the database: the table it belongs to (table_name), its name (column_name), its type (data_type), its position (ordinal_position), and more. information_schema is the name of the part where the database keeps information about itself; it also holds other views, such as the list of tables (information_schema.tables). The only thing the check query does is filter this view with the name of your table.
Next to the type, you can also see the limits. character_maximum_length shows the maximum number of characters a text column accepts, and numeric_precision and numeric_scale show the total digits of the number and the digits after the decimal point.
Example 2 (case): Length and digit information
CREATE TABLE club ( id INTEGER, name VARCHAR(60), founded_on DATE, budget NUMERIC(10, 2), is_active BOOLEAN ); SELECT column_name, character_maximum_length, numeric_precision, numeric_scale FROM information_schema.columns WHERE table_name = 'club' ORDER BY ordinal_position;
| column_name | character_maximum_length | numeric_precision | numeric_scale |
|---|---|---|---|
| id | NULL | 32 | 0 |
| name | 60 | NULL | NULL |
| founded_on | NULL | NULL | NULL |
| budget | NULL | 10 | 2 |
| is_active | NULL | NULL | NULL |
(5 rows)
name is limited to 60 characters; budget has 10 digits, 2 of them after the decimal point. The 32 for id tells you that INTEGER is stored with 32 bits in the binary system; it is not a count of decimal digits, so do not get confused. A NULL in a field shows that the information does not apply to that type: a date has no character limit, and a text has no digit count. This view shows not only your tables but also the ready-made tables of the case; in the Examples section you will look at the structure of the course table. Now use the check query yourself.
Try it now· not graded; doesn't affect progress
The first run returns 4 rows. When you add the is_active column, there are 5 rows, and the last row shows is_active | boolean. When you change the length, character_maximum_length in the name row becomes 80.
Sometimes, instead of defining the columns one by one, you want to save the result of a query as it is: a report table, a backup, or the state of a list on that day. In lessons 20 and 21 you learned to use the result of a query like a table. CREATE TABLE AS is the permanent version of this: it saves the result of a query as a new table. It takes the column names and types from the query and copies the rows too.
Example 3 (case): Table of scholarship students
CREATE TABLE scholarship_student AS SELECT student_no, first_name, last_name, department_id FROM student WHERE has_scholarship; SELECT COUNT(*) FROM scholarship_student;
| count |
|---|
| 28 |
(1 row)
28 scholarship students were copied to the new table. Is the copy the same as the original? The column names and types are the same, and the rows are the same. But one thing is missing: in the original student table, all four columns student_no, first_name, last_name, and department_id cannot be left empty. This information is in the is_nullable column of information_schema.columns: if it is NO, the column does not accept NULL; if it is YES, it does. In the original table, all four are NO. What do you see in the copy?
Does the student_no column of the scholarship_student table accept NULL values?
SELECT column_name, is_nullable FROM information_schema.columns WHERE table_name = 'scholarship_student' ORDER BY ordinal_position;
It is important to read this result correctly. is_nullable = YES does not say "there is a NULL in this column"; student_no is filled in all 28 rows, because they came from the original table. What it says is that if a row without a number is written to this table from now on, no rule will stop it. Copy tables are useful for reports and backups, but if they are meant to replace the original table, the rules must be added separately. You will see the rules in the next lesson.
The two errors you will meet most often with CREATE TABLE are a table with the same name that already exists and a type name that does not exist. In the case, the student table already exists:
OutputCREATE TABLE student (id INTEGER);
ERROR: relation "student" already existsrelation is the general name PostgreSQL uses for tables and similar structures. If you want to create the table when it does not exist and do nothing when it does, you add IF NOT EXISTS: CREATE TABLE IF NOT EXISTS student (id INTEGER); does not give an error and passes silently. It does not touch the existing table: if you then write SELECT COUNT(*) FROM student;, you still see 120 students. Know this, because you may think "the command ran without an error" and believe the table was built with your definition; but the old table is still there as it was.
The other error is a habit that comes from other languages. In some programming languages the text type is called string; PostgreSQL has no such type:
OutputCREATE TABLE club (id INTEGER, name STRING);
ERROR: type "string" does not existFor text, write VARCHAR(n) or TEXT. The error message tells you the name of the type in quotes; reading the message is half of the fix.
Designing a table follows the same steps in every field. The Earbud music app database that you will use in the last exercise has tables such as listener, song, and play. The product team wants a new feature: "For each playlist, we will store its owner, its name, its creation date, and whether it is public." Follow the same path: separate the pieces of information, give each one a name and a type, and add the number.
Example 4 (outside the case): The playlist table
CREATE TABLE playlist ( id INTEGER, listener_id INTEGER, name VARCHAR(50), created_on DATE, is_public BOOLEAN ); SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = 'playlist' ORDER BY ordinal_position;
| column_name | data_type | character_maximum_length |
|---|---|---|
| id | integer | NULL |
| listener_id | integer | NULL |
| name | character varying | 50 |
| created_on | date | NULL |
| is_public | boolean | NULL |
(5 rows)
The owner of the list is stored in the listener_id column as a listener number. Why the number and not the name or nickname? Because, as you know from lesson 14, tables are connected to each other with key columns; the playlist should point to a row in the listener table.
What type should the playlist.listener_id column have? (In the listener table, id is INTEGER and nickname is VARCHAR(30).)
You will see how two tables are officially connected by such a column, that is, how the database checks this link, in lesson 30.
Your club table is ready, but it has no rules yet. Types check the form of a value; they do not check its meaning. All three rows below go into the club table without a problem:
OutputINSERT INTO club VALUES
(1, 'Chess', '2019-10-01', 12500, TRUE),
(2, NULL, '2021-03-15', -500, TRUE),
(1, 'Chess', '2019-10-01', 12500, TRUE);
SELECT * FROM club; -- 3 rowsA club with no name, a club with a negative budget, and two records of the same club. None of them breaks the type rules: NULL can be written to any type, -500 is a valid number, and nothing stops you from writing the same row twice. The second half of a design is to put rules like these on the table.
The check query shows not only your own tables but also the ready-made ones. Which columns does the course table have?
SELECT column_name, data_type, character_maximum_length FROM information_schema.columns WHERE table_name = 'course' ORDER BY ordinal_position;
| column_name | data_type | character_maximum_length |
|---|---|---|
| id | integer | NULL |
| code | character varying | 6 |
| name | character varying | 60 |
| credits | integer | NULL |
| ects | integer | NULL |
| department_id | integer | NULL |
Forgetting the comma between columns, or leaving a comma after the last column.
OutputCREATE TABLE event (title VARCHAR(100) event_date DATE);
ERROR: syntax error at or near "event_date"
CREATE TABLE event (title VARCHAR(100), event_date DATE,);
ERROR: syntax error at or near ")"In the first command a comma is missing: after VARCHAR(100), PostgreSQL expects a comma or a closing parenthesis, and it stops when it sees the word event_date. The message tells you exactly where the error was noticed; the missing comma is usually right before that word. In the second command there is an extra comma: after the comma a new column was expected, but a parenthesis came. A comma comes after every column definition, but not after the last one. Writing each column on a separate line makes both mistakes easier to see.
CREATE TABLE name (column type, ...) creates an empty table with defined columns but no rows; columns are separated by commas, and there is no comma after the last one. Names are written with lowercase letters, digits, and underscores; capital letters written without quotes are stored in lowercase.NUMERIC(p, s) for exactness, text for IDs and codes (a phone number must keep its leading 0), DATE for the calendar, BOOLEAN for yes or no. A type is a limit that rejects values that do not fit.information_schema.columns shows the columns, types, and limits of a table; the check query uses it. CREATE TABLE ... AS SELECT saves the result of a query as a new table but does not copy constraints.Next lesson: this table accepts everything; to block an empty name, a negative budget, and two records of the same club, you will put rules (constraints) on the table.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
TIMESTAMPenrollment_date, founded_on |
| Yes or no? | BOOLEAN | has_scholarship, is_active |
| prerequisite_id |
| integer |
| NULL |
(7 rows)
The course code (such as CPR101) is a text of 6 characters: letters and digits mixed, and no calculation is done with it. Credits and ECTS are whole numbers that are added up and averaged.
CREATE TABLE IF NOT EXISTS student (id INTEGER); SELECT COUNT(*) FROM student;
| count |
|---|
| 120 |
(1 row)
The command did not give an error, but it did not build a new table either: student already existed, and it stays as it was, with its 120 rows and 13 columns.