Create table and copy data from csv file
Setup mysql database
brew install mysql
brew services start mysql
brew services stop mysql
brew services list
mysql_secure_installation
mysql --version
mysql -u root -p
Put this into a file sudo nano /etc/my.cnf
:
[client]
local_infile=1
[mysqld]
local_infile=1
brew services restart mysql
CREATE DATABASE database_name;
Setup postgres SQL database
Install Postgres via website or via brew:
brew install postgresql
brew services start postgresql
psql --version
Add psql to path to ~/.zshrc:
nano ~/.zshrc
export PATH="/Library/PostgreSQL/16/bin:$PATH"
Now login as postgres user:
psql -U postgres
Crate a new database:
CREATE DATABASE hello_world_db;
List all databases:
\l
Now one can use SQLTools
extension in VSCode, and connect to database.
Constraint in SQL
Foreign key (FK) constraint can be added to a table, for example below, Orders
table must have a CustomerID
that matches Customer(CustomerID)
. This ensures data integrity, so we don’t have nonsense Orders that have no matching Customer.
CREATE TABLE Customers (
INT PRIMARY KEY,
CustomerID VARCHAR(100)
CustomerName
);
CREATE TABLE Orders (
INT PRIMARY KEY,
OrderID DATE,
OrderDate INT,
CustomerID CONSTRAINT FK_CustomerOrder FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
Exercises
hint: avg(Survived)
is the same as (COUNT(CASE WHEN Survived = 1 THEN 1 END) * 1.0 / count(*))
since Survived is 0 or 1.
SELECT * FROM titanic LIMIT 10;
select (COUNT(CASE WHEN Survived = 1 THEN 1 END) * 1.0 / count(*)) as overall_rate FROM titanic;
select avg(Survived) as women_children_rate FROM titanic WHERE (Sex="female" OR Age<=12);
select avg(Survived) as others_rate FROM titanic WHERE NOT (Sex="female" OR Age<=12);
SELECT
Pclass, AVG(Survived) AS survival_rate
FROM
titanicGROUP BY
PclassORDER BY
Pclass;
select
Products.ProductName,
Suppliers.CompanyNamefrom
Productsleft join
Supplierson
= Suppliers.SupplierID
Products.SupplierID order by
Products.ProductName;