2
0
mirror of https://github.com/chubin/cheat.sheets synced 2024-11-09 07:10:36 +00:00
cheat.sheets/sheets/_psql/select

75 lines
1.9 KiB
Plaintext
Raw Normal View History

2018-01-17 16:13:38 +00:00
-- Query all data from a table
2018-01-07 11:42:08 +00:00
SELECT * FROM table_name;
Query data from specified columns of all rows in a table
SELECT column, column2... FROM table;
2018-01-17 16:13:38 +00:00
-- Query data and select only unique rows
2018-01-07 11:42:08 +00:00
SELECT DISTINCT (column) FROM table;
2018-01-17 16:13:38 +00:00
-- Query data from a table with a filter
2018-01-07 11:42:08 +00:00
SELECT * FROM table WHERE condition;
2018-01-17 16:13:38 +00:00
-- Set an alias for a column in the result set
2018-01-07 11:42:08 +00:00
SELECT column_1 AS new_column_1, ...
FROM table;
2018-01-17 16:13:38 +00:00
-- Query data using the LIKE operator
2018-01-07 11:42:08 +00:00
SELECT * FROM table_name
WHERE column LIKE '%value%'
2018-01-17 16:13:38 +00:00
-- Query data using the BETWEEN operator
2018-01-07 11:42:08 +00:00
SELECT * FROM table_name
WHERE column BETWEEN low AND high;
2018-01-17 16:13:38 +00:00
-- Query data using the IN operator
2018-01-07 11:42:08 +00:00
SELECT * FROM table_name
WHERE column IN (value1, value2,...);
2018-01-17 16:13:38 +00:00
-- Constrain the returned rows with LIMIT clause
2018-01-07 11:42:08 +00:00
SELECT * FROM table_name
LIMIT limit OFFSET offset
ORDER BY column_name;
2018-01-17 16:13:38 +00:00
-- Query data from multiple using the inner join, left join, full outer join, cross join and natural join:
2018-01-07 11:42:08 +00:00
SELECT * FROM table1 INNER JOIN table2 ON conditions
SELECT * FROM table1 LEFT JOIN table2 ON conditions
SELECT * FROM table1 FULL OUTER JOIN table2 ON conditions
SELECT * FROM table1 CROSS JOIN table2;
SELECT * FROM table1 NATURAL JOIN table2;
2018-01-17 16:13:38 +00:00
-- Return the number of rows of a table.
2018-01-07 11:42:08 +00:00
SELECT COUNT (*)
FROM table_name;
2018-01-17 16:13:38 +00:00
-- Sort rows in ascending or descending order
2018-01-07 11:42:08 +00:00
SELECT column, column2, ...
FROM table
ORDER BY column ASC [DESC], column2 ASC [DESC],...;
2018-01-17 16:13:38 +00:00
-- Group rows using GROUP BY clause.
2018-01-07 11:42:08 +00:00
SELECT *
FROM table
GROUP BY column_1, column_2, ...;
2018-01-17 16:13:38 +00:00
-- Filter groups using the HAVING clause.
2018-01-07 11:42:08 +00:00
SELECT *
FROM table
GROUP BY column_1
HAVING condition;
2018-01-17 16:13:38 +00:00
-- Combine the result set of two or more queries with UNION operator:
2018-01-07 11:42:08 +00:00
SELECT * FROM table1
UNION
SELECT * FROM table2;
2018-01-17 16:13:38 +00:00
-- Minus a result set using EXCEPT operator:
2018-01-07 11:42:08 +00:00
SELECT * FROM table1
EXCEPT
SELECT * FROM table2;
2018-01-17 16:13:38 +00:00
-- Get intersection of the result sets of two queries:
2018-01-07 11:42:08 +00:00
SELECT * FROM table1
INTERSECT
SELECT * FROM table2;