What is a Query?
Query
: A question we’re asking a database, aiming to get a response back.
psql -U postgres
-U
stands for ‘user’.\q
is used to quit postgres at any time.create table puppies (
name VARCHAR(100),
age_yrs NUMERIC(2,1),
breed VARCHAR(100),
weight_lbs INT,
microchipped BOOLEAN
);
insert into puppies
values
('Cooper', 1, 'Miniature Schnauzer', 18, 'yes');
insert into puppies
values
('Indie', 0.5, 'Yorkshire Terrier', 13, 'yes'),
('Kota', 0.7, 'Australian Shepherd', 26, 'no'),
('Zoe', 0.8, 'Korean Jindo', 32, 'yes'),
('Charley', 1.5, 'Basset Hound', 25, 'no'),
('Ladybird', 0.6, 'Labradoodle', 20, 'yes'),
('Callie', 0.9, 'Corgi', 16, 'no'),
('Jaxson', 0.4, 'Beagle', 19, 'yes'),
('Leinni', 1, 'Miniature Schnauzer', 25, 'yes' ),
('Max', 1.6, 'German Shepherd', 65, 'no');
varchar(n)
: variable length char, n represents the limit.numeric(p, s)
: floating point number, with p digits and s number of places after the decimal point.int
: 4 byte integer.boolean
: regular boolean value.SELECT Query
: Query used to get results back from a table.
SELECT [columns] FROM [table]
.SELECT *
to get all rows back in a given table.To select multiple columns you could use:
Also if you format it like this you can easily comment out certain columns with double dash.
Using SELECT and WHERE
WHERE clause for a single value
WHERE clause for a list of values
WHERE clause for a range of values
ORDER BY
Order By
to get back your data in a specified way.LIMIT and OFFSET
SQL operators
SELECT name, breed FROM puppies
WHERE breed NOT IN ('Miniature Schnauzer', 'Basset Hound', 'Labradoodle')
AND breed NOT LIKE '%Shepherd';
INSERT INTO table_name
VALUES
(column1_value, colum2_value, column3_value);
INSERT INTO friends (first_name, last_name)
VALUES
('Rose', 'Tyler'),
('Martha', 'Jones'),
('Donna', 'Noble'),
('River', 'Song');
Writing And Running A Seed File In PSQL
Creating a seed file
.sql
file type.CREATE TABLE pies (
flavor VARCHAR(255) PRIMARY KEY,
price FLOAT
);
INSERT INTO pies VALUES('Apple', 19.95);
INSERT INTO pies VALUES('Caramel Apple Crumble', 20.53);
INSERT INTO pies VALUES('Blueberry', 19.31);
INSERT INTO pies VALUES('Blackberry', 22.86);
INSERT INTO pies VALUES('Cherry', 22.32);
INSERT INTO pies VALUES('Peach', 20.45);
INSERT INTO pies VALUES('Raspberry', 20.99);
INSERT INTO pies VALUES('Mixed Berry', 21.45);
Populating a database via < (“left caret”)
psql -d [database] < [path_to_file/file.sql]
psql -d bakery < path_to_my_file/seed-data.sql
Populating the database via | (“pipe”)
cat [path_to_file/file.sql] | psql -d [database]
cat path_to_my_file/seed-data.sql | psql -d postgres