How do you create a user named 'Mary' that is superuser with password 'myPassword'?
CREATE USER Mary WITH superuser PASSWORD 'mypassword';
How do you create a normal user named 'Mary' with password 'MyPassword'?
CREATE USER Mary WITH PASSWORD 'MyPassword';
How do you create a database named 'clues'?
CREATE DATABASE clues;
How do you create a database named clues with the owner 'Mary'?
If the user 'Mary' doesn't exist yet, create her.
CREATE USER Mary WITH PASSWORD 'MyPassword';
CREATE DATABASE clues WITH OWNER Mary;
Create a table called 'drinks' with the following fields:
CREATE TABLE drinks (
id serial,
name VARCHAR(50),
ounces INTEGER,
PRIMARY KEY (id)
);
How do you create a table called 'menu' with the following:
CREATE TABLE menu (
id serial,
name VARCHAR(50),
drink_id INTEGER,
PRIMARY KEY(id),
FOREIGN KEY (drink_id) REFERENCES drinks(id);
What is the command to show the people table (not the data, just the table)?
Use the describe people command:
\d people;
What is the command to show all the users in your RDBMS?
Use the describe users command:
\du;
What is the command to show the tables we have in our database (not the contents)?
Use the describe tables command
\dt; //describe tables
\d <<tableName>> //describe just this table
What is the command to show all of your databases?
Use the list database command:
\list;
How do you show the user in this session?
SELECT CURRENT_USER;
What are the commands to setup a database?
CREATE DATABASE <<databaseName>>;
REVOKE CONNECT ON DATABASE <<databaseName>> FROM PUBLIC;
GRANT CONNECT ON DATABASE <<databaseName>> TO <<UserName>>;
How do you delete a table?
If the table has any dependencies (i.e. another table references it) you MUST delete the table that references it first.
DROP TABLE <<tableName>>;
How do you delete a user?
If the user has any references, like "GRANT CONNECT ON DATABASE ...", you must REVOKE CONNECT ON DATABASE first.
DROP USER <<UserName>>;
How do you log a user in to a specific database?
psql -u -W <<userName>> <<databaseName>>;
If you have a string value set as NOT NULL, is "" a NULL value?
No! "" is not equivalent to NULL.
What are two ways of declaring a primary key?
Within the table, or using constraint syntax:
id serial PRIMARY KEY,
or constraint syntax, which is at the end of the CREATE TABLE, but still within the parens:
id serial,
PRIMARY KEY(id);
How do you write an insert statement where if any one of the statements fail, all of them fail?
INSERT INTO pets (name, age, owner_id) VALUES
('Fido', 4, 3),
('Rover', 2, 3),
('Spot', 1, 2);
Note: If this is a LONG insert you will literally lock the table until all of the inserts are completed, yielding it unavailable in a production environment for other access. Better to use individual insert statements if there are a lot of inserts.
How would you select all rows that do NOT have values in a certain field? For example: You do not want any rows where the states are New York, California, or Texas?
SELECT city, state, population_estimate_2018
FROM cities
WHERE state NOT IN ('New York', 'California', 'Texas');
How would you select a population when the population is listed like: 1000000, but print it like 1 Million?
SELECT city, (population_estimate_2018/1000000 || ' million') as population
FROM cities;
Note the || character is for string concatenation.
Also note, 'as population' will alias the output as a column named 'population'
How do you change your column name in a table?
ALTER TABLE <<table_name>> old_name TO new_name;
What is an inner join?
An inner join is the default join. It returns only those rows that have matching values in both tables.
How does a LEFT or LEFT OUTER join work?
It returns ALL rows from the LEFT table, whether there is a match on the RIGHT table. If there is no match on the RIGHT table, all the right table's columns will be NULL;
How does a RIGHT or RIGHT OUTER Join work?
Similar to the LEFT, or LEFT OUTER JOIN, it returns all records from the RIGHT table, and the matched records from the left table. If no records match on the left table, those columns will have NULL values.
How does a FULL or FULL OUTER JOIN work?
It returns ALL records. Only the records that match will have values in the columns. If the records did not match, that table will have NULL values in those columns.
Given the following tables, which JOIN will produce ALL of the rows from the left table, and only matched rows from the right table?
A LEFT JOIN:
Given the two tables below, which JOIN will produce ALL rows from BOTH tables?
FULL OUTER JOIN
Given the two tables below, which JOIN will produce ONLY the rows that match in both tables?
JOIN, or INNER JOIN
Given the two tables below, which JOIN will produce ALL rows from the RIGHT table, but only those rows that match from the LEFT table?
RIGHT JOIN
How would you write an index?
CREATE INDEX idx_addresses_city_post_code ON table_name (city_id, postal_code);
How would you write a partial index?
A partial index uses a subset of a table defined by a conditional expression:
CREATE INDEX index_name ON table_name WHERE (conditional_expression); OR
CREATE INDEX addresses_phone_index ON addresses (phone_number) WHERE (city_id = 2);
When would you want to use an index?
Indexes can help us optimize our queries for faster performance. Use them:
What is the default type of index?
B-tree
What is a downside to working with indexes?
For every update operation (DELETE/UPDATE/INSERTIONS) the index must be updated.
How do you analyze query performance?
What is a Self-Join?
A self join is when you join a table onto itself. Typically used to compare rows within the same table.
SELECT select_list
FROM table_name t1
INNER JOIN table_name t2 ON join_predicate;
What statements are required to use a database in your JavaScript code?
const { Pool } = require("pg");
const pool = new Pool({
database: "recipe_box",
password: "foo"
});
(async () => {
const results = await pool.query("INSERT INTO foo VALUES ($1, $2, $3, $4)",
[1, 'Hunter Valley', 't', 200.00]);
console.log(results);
pool.end();
})();
Define what a relational database management system is.
The RDBMS is a software application that you run that your programs can connect to so that they can store, modify, and retrieve data.
Describe what relational data is.
Relational Data is data that is related in some way. For instance user data in a photo sharing application might have a relationship with the photo data and photo data and user data might both have a relationship with comment data.
How many types of relationships can you have in relational data?
There are three types of relationships you can have:
Define what a database is.
A database is a collection of structured data stored in a Database "System" or "Server"
Define what a database table is.
A database can have many tables, a table is made up of several Columns . Each Column is of a certain type.A table Schema describes the columns in a table. Tables also contain Rows which hold the actual data for the table.
Describe the purpose of a primary key.
A primary key is a single unique column in a database table.
Describe the purpose of a foreign key.
A foreign key is an integer column in a table which holds the value of a matching primary key from another table. A foreign key constraint ensures that the id stored in the foreign key column is a valid primary key in the related table.
What is the command line used to connect to an instance of PostgreSQL with the command line tool psql.
psql -U <database username;> -h <hostname> <database name>
-U
specifies psql user (defaults to the same as your unix username)-h
does not have a default value. If you leave it out, psql connects through a unix socket instead of connecting to a hostname through the network<database name>
defaults to the same as whatever <database username> isYou can set these two environment variables (PGHOST
and PGUSER
in your shell to override the default behavior -U
and -h
How do you set your environment variables so that you don't have to enter your host, user or password?
In your .bash_profile or .zshrc file export your localhost and username as follows:
export PGHOST=localhost
export PGUSER=<userName>
To set your password, in your unix home directory, create a .pgpass
file and set your password for psql, so you don't have to type it in everytime.
How do you identify the user type in psql?
\du
: describe user
postgres-# \du
List of roles
Role name | Attributes | Member of
------------------------+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
my_user | | {}
How do you create a user for the RDBMS?
CREATE USER <database username> WITH PASSWORD <password> <attributes>
Attributes can be things like SUPERUSER
or permissions like CREATEDB
or any of the other attributes listed in the documentation
How do you configure a database so that only the owner (and superusers) can connect to it?
CREATE DATABASE <database name> WITH OWNER <database username>
How do you list all of the databases in your PostgreSQL installation?
\l
: list command
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------------+------------------------+----------+------------+------------+-----------------------
aa_times | aa_times | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
project_manager | project_management_app | UTF8 | en_US.utf8 | en_US.utf8 |
recipe_box | recipe_box_app | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgress +
| | | | | postgress=CTC/postgres
template1 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgress +
| | | | | postgress=CTC/postgres
(6 rows)
How do you create a table in a database?
CREATE TABLE <table name> (
<column name> <data type>,
<column name> <data type>,
...
<column name> <data type>
);
How do you list all of your tables in your database?
\dt
: describe tables
aa_times=# \dt
public | people | table | aa_times
public | sections | table | aa_times
public | stories | table | aa_times
Identify and describe the 7 most common data types used in PostgreSQL.
What is the purpose of a UNIQUE constraint and how do you use it?
Unique constraints ensure that the data contained in a column is unique among all the rows in the table.
CREATE TABLE products (
id integer UNIQUE,
name text,
price NUMERIC
);
Describe the purpose of the NOT NULL constraint and how do you use it?
A not-null constraint simply specifies that a column must not assume the null value.
CREATE TABLE products (
id integer NOT NULL,
name text NOT NULL,
price NUMERIC
);
How do you create a primary key for a table?
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name text,
price numeric
);
OR ...
CREATE TABLE products (
id SERIAL,
name text,
price numeric,
PRIMARY KEY(id)
);
What is a foreign key?
A foreign key constraint specifies that the values in a column (or a group of columns) must match the values appearing in some row of another table.
How do you create a foreign key constraint?
Use the REFERENCES
keyword:
To reference the products table from the orders table:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name text,
price numeric
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
product_id integer REFERENCES products (product_id),
quantity integer
);
CREATE TABLE ORDERS (
id SERIAL,
product_id integer,
quantity integer,
PRIMARY KEY (id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
Which of the two are valid SQL?
SELECT name, quantity FROM orders;
OR select name, quantity from orders;
Both! Although, SELECT name, quantity FROM orders;
is the convention to use uppercase SQL keywords
Which of the following will work when you have a table named Orders, with column names of Name and Quantity?
SELECT Name, Quantity FROM Orders;
SELECT "Name", "Quantity" FROM "Orders";
If your tables and/or rows are using capital letters, you MUST quote them in your query. Otherwise PostgresSQL will first transform the table name/table columns to lower case, then perform the query.
Write a select statement that will select the population (column named population) in France (column called name) from the table "countries"
SELECT population
FROM countries
WHERE name = 'France';
Write a query to update the countries table's population column to 1000 for only the country name of 'Vatican City'
UPDATE countries
SET population = 1000
WHERE name = "Vatican City";
What could potentially be wrong with this query?
UPDATE countries
SET population = 1000
If you only wanted to update one country with that population, you would have actually updated ALL countries with that population. Remember to use the WHERE clause to select the country you want to update.
Write a SQL query that will delete the planet named Pluto from your planets table
DELETE FROM planets
WHERE name = 'Pluto';
How would you write a query to select all of the team players on the 'Lakers' from the following tables:
CREATE TABLE players (
player_id SERIAL,
player_name VARCHAR(50),
team_id INTEGER,
PRIMARY KEY(player_id),
FOREIGN KEY (team_id) REFERENCES team(id)
);
CREATE TABLE teams (
id SERIAL,
team_name VARCHAR(50),
PRIMARY KEY(id),
);
SELECT player_name
FROM players
JOIN teams ON teams.id = players.team_id
WHERE team_name = 'Lakers'
How would you write an INSERT statement to insert data into a table?
INSERT INTO nfl_players
VALUES(DEFAULT, 'Joe Burrow', 'Bengals');
or ...
INSERT INTO nfl_players (playerName, team)
VALUES('Joe Burrow', 'Bengals');
or ...
INSERT INTO nfl_players (playerName, team)
VALUES
('Joe Burrow', 'Bengals'),
('Tom Brady', 'Buccaneers'),
('Drew Brees', 'Saints');
How do you use a seed file to populate data in a database?
CREATE TABLE IF NOT EXISTS bands (
id SERIAL,
name VARCHAR(50) NOT NULL,
vocalist VARCHAR(50),
PRIMARY KEY (id)
);
INSERT INTO bands
VALUES (DEFAULT, 'The Beatles', 'John Lennon');
INSERT INTO bands
VALUES (DEFAULT, 'Queen', 'Freddie Mercury');
INSERT INTO bands
VALUES (DEFAULT, 'U2', 'Bono');
Define Normalization
A process of minimizing redundancy from a relation or set of relations.
Define First Normal Form
If a relation contains composite, or multi-valued attributes, it violates first normal form. A relation is in first normal form if every attribute in that relation is a single valued attribute.
What are the 3 steps to designing a database?
You have a database where you want to transfer money from one account to another. That requires two database queries. However, if one query fails you do NOT want the other query to execute. What would you use to prevent this?
A transaction. If any query within the transaction fails, the entire transaction may be rolled back.
Using SQL in Javascript, how would you create a transaction?
By using pool.query("Begin")
, then a try-catch block. If a query fails, throw an error. If all queries succeed, then commit. In the catch block, rollback.
async function transferFunds(pool, account1, account2, amount) {
const balanceQ = 'select balance from "AccountBalances" where account_id = $1';
const updateBalanceQ = 'update "AccountBalances" set balance=$1 where account_id = $2';
await pool.query("BEGIN");
try {
const balance1 = await pool.query(balanceQ, [account1]);
if (balance1 < amount) {
throw ("Not enough funds");
}
const balance2 = await pool.query(balanceQ, [account2]);
await pool.query(updateBalanceQ, [balance2 + amount, account2]);
await pool.query(updateBalanceQ, [balance1 - amount, account1]);
await pool.query("COMMIT;");
} catch (e) {
await pool.query("ROLLBACK;");
}
}
What are indexes used for?
To improve performance.
Why would we NOT want to use an index?
If our table is running many inserts, deletes, and updates, they would have to wait for the Index to update after each update. Updating indexes locks the table, and the queries may be stalled momentarily.
How would you evaluate a poorly performing query?
Use EXPLAIN
and EXPLAIN ANALYZE
to determine your query performance. EXPLAIN
will give you baseline numbers you can use to compare query to query, for trying to optimize your queries. You can use EXPLAIN ANALYZE
for details on how the query is executing, and to obtain a measure in milleseconds for the query.
What are the steps you need to install and use the node-postgres library and its Pool object to query a PostgreSQL-managed database.
From the command line, install node-postgres:
$npm install node-postgres
Then import your postgres library and define your database connection:
const { Pool } = require('pg');
const pool = new Pool({
database: <dbName>,
hostname: <hostName>
username: <userName>
password: <password>
});
const result = await pool.query("SELECT 1;");
Write a javaScript function using placeholders for parameters of the form $1 and $2, to select from the users table all columns that contain the username and password specified.
//first, create the query
const loginQuery = 'SELECT * FROM users WHERE username = $1 AND password = $2;';
//now write a function using your parameterized query, passing in the values to your query
async function loginUser(username, password) {
const results = await pool.query(loginQuery, [username, password]);
}
What is the security benefit of using parameterized queries?
node-postgres library exists primarily to protect our applications from SQL-injection attacks. One of the most common type of hacking attacks that we see on the web.
What are the steps to set your project up to use your postgreSQL RDBMS with Sequelize?
There are four steps to setup your project:
CREATE USER <databaseUser> WITH SUPERUSER PASSWORD '<password>';
CREATE DATABASE <databaseName> WITH OWNER '<databaseUser>';
REVOKE CONNECT ON DATABASE <databaseName> FROM PUBLIC;
GRANT CONNECT ON DATABASE <databaseName> TO <databaseUser>
npm install sequelize@^5 sequelize-cli@^5 pg;
npx sequelize-cli init;
"development": {
"username": "sequilize_recipe_box_app",
"password": "HfKfK79k",
"database": "recipe_box_development",
"host": "127.0.0.1",
"dialect": "postgres",
"seederStorage": "sequelize"
},
Now that you have your database created and project setup, what are the steps you would take to install the tables, and make the associations in your database using sequilize?
npx sequelize-cli model:generate --name <ModelName> --attributes <ModelName>:<type>,<ModelName>:<type>, ...
npx sequelize-cli db:migrate;
npx sequelize-cli seed:generate --name <descriptiveName>
npx sequelize-cli db:seed:all
How do you rollback your seed files, and your migrations?
npx sequelize-cli db:migrate:undo
npx sequelize-cli db:migrate:undo:all
npx sequelize-cli db:seed:undo
npx sequelize-cli db:seed:undo:all
How do you perform data validations with Sequelize?
Because you want the validation to occur BEFORE you touch the database, you will want to put your validation in your Model:
const Cat = sequelize.define('Cat', {
firstName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: {
msg: "firstName must not be null",
},
notEmpty: {
msg: "firstName must not be empty",
}
},
}
}
How would you use transactions with Sequelize?
Using a try, catch block, you use sequelize.transaction passing in an async callback function
async function main() {
try {
await sequelize.transaction(async (tx) => {
const markovAccount = await BankAccount.findByPk(1, { transaction: tx } );
const curieAccount = await BankAccount.findByPk(2, {transaction: tx} );
curieAccount.balance += 5000;
await curieAccount.save( { transaction: tx} );
markovAccount.balance -= 5000;
await markovAccount.save ({ transaction: tx} );
});
} catch (err) {
console.log("Unable to complete transaction. Rolled back.");
}
await sequelize.close();
}
main();
How do you create a new table row with sequelize?
<Model>.create()
OR <Model>.build()
with <instance>.save()
How do you perform a Read with a sequelize method?
<Model>.findOne()
, <Model>.findAll()
, or <Model>.findByPk()
How do you update a column in a table row?
First you would get the instance by using one of the <Model>.find*()
methods, and now you can simply set the property on the instance and call .save()
or use the .update()
method.
How do you delete a table row from a table?
First you find the instance by using one of the <Model>.find*()
methods, and now you can use <instance>.destroy()
, OR use the <Model>.destroy()
with a where clause to destroy multiple rows.