SQL Select Statement
The select statement is used to grab data from a table.
Select all values from a table
SELECT * FROM tbl; — Select all columns and rows in the tbl table.
Select specific columns from a table:
SELECT c1,c2 FROM tbl; - Select column c1 and c2 from tbl table.
Select distinct values in a column from a table:
SELECT DISTINCT c1 FROM tbl; — Select only distinct values from c1, ie values that are different from each other.
There is also the option to select counts:
SELECT COUNT(*) FROM tbl; — Count number of rows from tbl, using * may not be best practice if a specific column is being counted.
SELECT COUNT(DISTINCT column) FROM table; — Count number of distinct types in a column.
You can also limit the number of results:
SELECT * FROM tbl LIMIT 5; — Select every row from tbl, but limit it to 5 entries (defaults to first five)
Results can be ordered asc or descending:
SELECT c1, c2
FROM tbl
ORDER BY c1 asc/desc; — Order by c1, choose either asc/desc
Conditional Selections
The ‘where statement’ can be used to conditionally select as follows:
SELECT c1,c2 — Select column 1 and column 2
FROM tbl — from tbl table
WHERE conditions — Where specific conditions are met
ORDER BY c1 ASC, c2 DESC — Order by …….
Values can be selected in a range as follows:
SELECT c1,c2
FROM tbl
WHERE c2 BETWEEN 8 AND 9; — Where the c2 column has values equal or greater than 8 and equal or lesser than 9.
SELECT c1,c2
FROM tbl
WHERE c2 NOT BETWEEN 8 AND 9; — Where the c2 column DOES NOT HAVE values equal or greater than 8 and equal or lesser than 9.
SELECT COUNT(*) FROM tbl; — Count number of rows from tbl, using * may not be best practice if a specific column is being counted.
SELECT COUNT(DISTINCT column) FROM table; — Count number of distinct types in a column.
SELECT * FROM tbl LIMIT 5; — Select every row from tbl, but limit it to 5 entries (defaults to first five)