Useful Notes and Links

Reynier Cruz-Torres, PhD

Fundamentals

SELECT column_1, column_2 FROM table;
SELECT * FROM table;

Select distinct (unique) values in a column:

SELECT DISTINCT column FROM table;
SELECT DISTINCT(column) FROM table;

Count function

SELECT COUNT(column_1) FROM table;
SELECT COUNT(column_2) FROM table;
SELECT COUNT(*) FROM table;

returns number of rows in the table. All the calls above return the same value.

Combining distinct and count:

SELECT COUNT(DISTINCT column_1) FROM table;

Conditional selection

SELECT column_1, column_2 FROM table WHERE condition;
SELECT name, choice FROM table WHERE name = 'David';
SELECT name, choice FROM table WHERE name = 'David' AND rate > 4;

Ordering (ORDER BY)

SELECT col1, col2 FROM table ORDER BY col1 ASC
SELECT col1, col2 FROM table ORDER BY col1 ASC, col2 DESC

Limiting number of rows return in a query

SELECT * FROM table ORDER BY payment_date DESC LIMIT 5;
SELECT * FROM table LIMIT 5;

BETWEEN

SELECT * FROM payment WHERE amount BETWEEN 8 AND 9;
SELECT * FROM payment WHERE amount NOT BETWEEN 8 AND 9;

IN

Check if a value is included in a list of options.

SELECT color FROM table WHERE color IN ('red','blue');
SELECT color FROM table WHERE color NOT IN ('red','blue');

LIKE and ILIKE

SELECT * FROM table WHERE first_name LIKE 'J%' AND last_name NOT LIKE 'S%';

Aggregate functions

SELECT MIN(replacement_cost) FROM film;
SELECT ROUND(AVG(replacement_cost),2) FROM film;