SQL Syntax
Intro
- This is the first in a series of tutorials on how to use a relational database.
- We are using Postgres, and it is assumed you have a Postgres database server installed on your computer, with the PG Admin graphical interface.
- In this tutorial we will:
- Plan the database structure and create the schema.
- Create the database.
- Review SQL Syntax.
- Use the PG Admin tool to add tables and rows to the database.
Read it, watch it, do it, review it:
- There is both a written and accompanying video version of this tutorial. There are timestamps under the headings that align with the video version of the topic.
- Read it: For each topic heading, First read the topic.
- Watch it: Then watch the associated section of the video.
- Do it: Then follow the instructions to replicate the steps in your own version of the bookstore database.
- The Database CheatSheet has a major category that aligns with this tutorial.
- Review it: When you are done with the whole tutorial, open the CheatSheet and review the SQL category from this tutorial. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future.
Plan your database
[0:00 and 0:29 Video timestamps]
We'll start by planning our database and creating the schema.
Schema is essentially a "blueprint" of the database. It defines how the data is organized. It includes logical constraints such as table names, fields, data types, and the relationships between them.
We will create a database for a book store.
It will have two tables, one for authors and one for books.
Table: A table is a set of related data that is structured in rows and columns.
A table is sometimes called a relation, althought, they don't exactly mean the same thing.
Columns: Across the top of the table are the columns. Columns are named and have an assigned data type.
Rows: Data items are stored in rows. The values they can contain are constrained by the columns. While there is a fixed number of columns, there is not a fixed number of rows.
Associations: Two or more tables may be related. Associations describe how they are related.
Let's write out the schema listing the table names, the columns, and the associations.
Database Name: bookstoreWe'll start by planning our database and creating the schema.
Schema is essentially a "blueprint" of the database. It defines how the data is organized. It includes logical constraints such as table names, fields, data types, and the relationships between them.
We will create a database for a book store.
It will have two tables, one for authors and one for books.
Table: A table is a set of related data that is structured in rows and columns.
A table is sometimes called a relation, althought, they don't exactly mean the same thing.
Columns: Across the top of the table are the columns. Columns are named and have an assigned data type.
Rows: Data items are stored in rows. The values they can contain are constrained by the columns. While there is a fixed number of columns, there is not a fixed number of rows.
Associations: Two or more tables may be related. Associations describe how they are related.
Let's write out the schema listing the table names, the columns, and the associations.
Schema
Schema (blueprint of tables, columns, associations):
- authors: name, bio, date of birth
- books: International Standard Book Number (isbn), title, author, description, quantity in stock, price, is it on sale?, published date.
- Associations: one-to-many relationship. Authors is the parent table and books is the Child table in the association. Each book has exactly one author. Each author can have zero, one, or many books.
Create the bookstore database
To create the database in Postgres we can use PG Admin.
- Open PG Admin > In the left panel drill into databases > Right-click: Create database > Enter: bookstore
SQL Syntax
Below are the SQL statements we will use to create the two tables and populate them with some rows.-- Create an "authors" table:
CREATE TABLE authors (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(255),
bio TEXT,
date_of_birth DATE
);
-- Insert some rows:
INSERT INTO authors(name, bio, date_of_birth)
VALUES('Joey R.', 'Lorem ipsum.', '1990-05-19'),
('Sheena R.', 'Lorem ipsum.', '1993-06-28');
-- Create a "books" table:
CREATE TABLE books (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
isbn CHAR(13),
title VARCHAR(255),
author VARCHAR(100),
description TEXT,
quantity INTEGER,
price NUMERIC(5,2),
on_sale BOOLEAN,
published_date DATE,
created_at TIMESTAMP
);
-- Insert a row:
INSERT INTO books(
isbn, title, author, description,
quantity, price, on_sale, published_date
)
VALUES(
'1234567891011', 'Learn Databases', 'Joey R.', 'Lorem ipsum.',
47, 19.99, false, '2022-07-01'
);
For now we will just focus on the SQL syntax.
[3:14 Video timestamp]
- SQL statement: A SQL statement is a unit of SQL code that defines the action to be carried out. In the examples above we have two statements to create tables, and two statements to add rows to the tables.
- Semicolons: End each statement with a semicolon.
- Quotes:
- Use single quotes: Some of the values we insert into the database will be text, like the author name and bio and the book title and description. Put text in single quotes:
'Learn Databases'
. - Postgres is case insensitive so a column named
CreatedAt
can be referenced ascreatedat
. If you need to distinguish identifiers with capital letters, put the identifier in double quotes: "CreatedAt" - Use two single quotes to escape a single quote in the text:
''
- Example: Change
'Joe's Diner'
to'Joe''s Diner'
[4:09 Video timestamp]
- Capitalization: SQL is case insensitive.
- Keywords uppercase: Keywords are reserved words that have special meaning in the SQL language.
- It is convention to put keywords in all uppercase since it makes them easier to read, but it is not a requirement.
- Identifiers lowercase: Identifiers are names you supply for variables such as table and column names. They must be unique and cannot be keywords.
- Put identifiers in lower case.
- Example with uppercase keywords and lowercase identifiers:
SELECT title, author, publisher FROM books;
- There is no consensus on capitalization of data types (e.g., text vs TEXT). Either can be used.
[5:07 Video timestamp]
- Naming Conventions: For table and column names, it is common practice to use snake_case for names with multiple words. For pluralization, there is no consensus for table names so either singular or plural names are fine, just be consistent. For column names, singular names are commonly used.
- Table name example:
library_book
orlibrary_books
- Column name examples:
title
,postal_code
[5:43 Video timestamp]
- Comments:
- To ignore text in SQL code, use comments.
- For a single line comment, preface it with two dashes:
-- This is a comment
- In the SQL code above we put comments explaining what it does before each statement. Those will be ignored when the statements are executed.
- For multi-line comments, use the below syntax:
/*
This is a
multi-line comment.
*/
We will explain more about these statements in the next tutorials.
Add tables to the database
We have our schema, and an SQL statement to add tables to the database.Three ways we can add the tables are:
- Use PG Admin's Query Tool to execute the SQL statements.
- Use PG Admin's GUI directly.
- Use the PSQL Shell to enter the SQL statements.
1. Create table using the PG Admin Query Tool
[2:52 Video timestamp]
Going forward we will be using the PG Admin Query Tool, which allows us to execute SQL statements.To open the Query Tool:
- With PG Admin open, in the Browser side panel drill down to the bookstore database: Servers > PostgreSQL > Databases > bookstore. Then either:
- Right click on bookstore > Query Tool.
- Or click the Tools menu > Query Tool
- Or click the Query Tool toolbar:
- Copy and Paste the SQL statements from the SQL Syntax section above, into the Query Tool's editor window.
- Then click the
▶
Execute toolbar. - You can then view the new tables: bookstore > Schemas > public > Right click Tables > Refresh: You should then see the authors and books tables.
- To see the columns either:
- Click the table name > Columns
- Or right click the table name > Properties > Columns tab.
- To see the rows we added either:
- Right click the table name > View/Edit Data > All Rows. This will query the database and return all rows for that table.
- Or click the table name > then click the View Data toolbar:
2. Create table using the PG Admin GUI
Instead of using the Query Tool, we could create the table using PG Admin's GUI directly:- With PG Admin open, in the Browser column click: Servers > PostgreSQL > Databases > bookstore > Schemas > public > Right click on Tables > Create Table > Enter the table name and click the save button.
- Then add the first column: Click the table name > Right click Columns > Create Column > Enter column name > Definitions tab: Select data type > Constraints tab: optionally add a default value or Not NULL constraint > SQL tab: view the generated SQL statement. If satisfied click the Save button.
- Repeat above for each column.
3. Create table using the PSQL Tool
The PSQL tool is a shell program you execute from the command line. PG Admin has a window for entering PSQL commands. It is not the best choice for pasting blocks of code, but it is useful to be familiar with for quick entries.
- With PG Admin open, in the Browser side panel drill down to the bookstore database: Servers > PostgreSQL > Databases > bookstore. Then either:
- Right click on bookstore > PSQL Tool.
- Or click the Tools menu > PSQL Tool
- Or click the PSQL Tool toolbar:
Then after the prompt, type in the SQL statements from the SQL Syntax section above.
You need to enter the statements line by line and you will get a new prompt after every line.