Site logo

postgresql Cheat sheet

CLI
Connect to Postgresql
Connect: psql -U username -d database_name -h localhost -p port_number
Quit
Quit: \q
Check version
psql --version
Clauses
Clauses
FROM > WHERE > GROUP BY > HAVING > SELECT > DISTINCT > ORDER BY > LIMIT
Data Types
TINYINT: 1 byte -128 to +127 (unsigned: from 0 to 255)
TINYINT
SMALLINT: 2 bytes -32 768 to +32 767 (unsigned: from 0 to 65 535)
SMALLINT
MEDIUMINT: 3 bytes (3o: +-16 000 000)
MEDIUMINT
INT: 4 bytes (4o: +- 2 000 000 000)
INT
BIGINT: 8 bytes (8o: +-9.10^18)
BIGINT
FLOAT(M,D): Floating-Point
FLOAT
DOUBLE(M,D): Floating-Point
DOUBLE
DECIMAL(M,D): (Fixed-Point),
DECIMAL(M,D)
Fixed-Length String, max size=255
CHAR(M)
Variable-Length String, max size=255
VARCHAR(M)
Text: max size=65535
TEXT(M)
Binary Large Object: binary; max size=65535
BLOB
Date: YYYY-MM-DD
DATE
Time: (HH:MM:SS)
TIME
Date and Time: YYYY-MM-DD HH:MM:SS
DATETIME
(YYYY)
YEAR
Timestamp: TIMESTAMP (like DATETIME, but 1970->2038, compatible with Unix
TIMESTAMP
Boolean
BOOLEAN
Enumeration
ENUM('value1', 'value2', ...)
Set of Values
SET('option1', 'option2', ...)
TEXT []
Array: datatype []
UUID
UUID
M: total number of digits
"M" refers to the total number of digits you want to store
N: decimal point
"N" is the number of digits to be stored after the decimal point
Database Operations
Create a Database
CREATE DATABASE database_name [CHARACTER SET utf8];
Show databases
\l
Select database
\c database_name
Delete a database
DROP DATABASE database_name;
Alter a database
ALTER DATABASE database_name CHARACTER SET utf8;
Table Operations
Create a Table
CREATE TABLE [IF NOT EXISTS] table_name (column1 datatype COMMENT 'string', ...);
Create a Table
CREATE TEMPORARY TABLE table;
Show tables
\dt
Describe table
\d table_name
Delete a table
DROP TABLE [IF EXISTS] table_name;
Rename table
ALTER TABLE table RENAME TO new_table_name
Rename column
ALTER TABLE table RENAME col1 TO col2
Add a Column
ALTER TABLE table ADD column_name datatype;
Add a Column
ALTER TABLE table ADD column_name datatype FIRST;
Add a Column
ALTER TABLE table ADD column_name datatype AFTER another_field;
DROP colum
ALTER TABLE table DROP column_name;
Alter table
ALTER TABLE table CHANGE field1 new_field_name datatype FIRST
Alter table
ALTER TABLE table CHANGE field1 new_field_name datatype NOT NULL ..
Alter table
ALTER TABLE table ALTER field1 SET DEFAULT ...
Alter table
ALTER TABLE table ALTER field1 DROP DEFAULT;
change the data type of a column
ALTER TABLE table MODIFY field1 datatype NOT NULL ...
Alter table
ALTER TABLE table MODIFY field1 type1 FIRST;
Alter table
ALTER TABLE table MODIFY field1 type1 AFTER another_field;
Constraints Operations
Constraint
CREATE TABLE table_name ( column1 datatype constraint, ...);
Full Constraint
CREATE TABLE table_name ( column_name datatype [ UNSIGNED ] [ NULL | NOT NULL ] [DEFAULT default_value] [SERIAL], ...);
Auto-Increment and Primary Key Constraint
CREATE TABLE table_name ( column_name INT SERIAL, ..., PRIMARY KEY (column_name) );
Foreign Key Constraint
CREATE TABLE table_name ( column_name INT, FOREIGN KEY (column_name) REFERENCES other_table(other_column) );
Unique Constraint: Ensures that all values in a column are different
CREATE TABLE table_name ( column1 INT, column2 INT, UNIQUE KEY `key_name` (column1, column2) );
Check Constraint
CREATE TABLE table_name ( column_name INT, CHECK (column_name > 10) );
Check Constraint: DEFAULT CURRENT_DATE()
CREATE TABLE table_name ( City varchar(255) DEFAULT 'Danang' );
UNSIGNED Constraint
CREATE TABLE table_name ( column_name datatype UNSIGNED, );
Insert Operations
Insert Data into a Table
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);
Insert Multiple Rows into a Table
INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...), (value1, value2, ...);
Update Operations
Update Data in a Table
UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition;
Delete Operations
Delete all data from a Table
DELETE FROM table_name;
Delete Data from a Table
DELETE FROM table_name WHERE condition;
Delete Data from a Table
DELETE FROM table1, table2 WHERE table1.id1 = table2.id2 AND condition
Delete table records and reset increment
TRUNCATE table_name;
Select Operations
Select Data from a Table
SELECT * FROM table_name;
Select Alias Column
SELECT column_name AS alias_name FROM table_name;
Select Alias Table
SELECT c.OrderID FROM Customers AS c;
Select Data from a Table
SELECT * FROM table1, table2;
Select Data from a Table
SELECT column1, column2, ... FROM table_name;
Select Data from a Table
SELECT column1, column2, ... FROM table_name WHERE condition;
Select Data from a Table
SELECT ... FROM ... WHERE condition ORDER BY column1, column2;
Select Data from a Table
SELECT ... FROM ... WHERE condition ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Select Data from a Table
SELECT ... FROM ... WHERE condition LIMIT 10;
Select Data from a Table
SELECT ... FROM ... WHERE condition LIMIT row_count OFFSET offset
Join Operations
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
Inner Join multiple conditions
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column AND table1.column2 = table2.column2;
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
Right Join
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
Union Operations
Inner Join
SELECT c1, c2 FROM table1 UNION[ALL] SELECT c1, c2 FROM t2;
Condition Operations
Simple Equality Condition
WHERE column_name = value;
Simple Not Equality Condition
WHERE column_name <> value;
Simple Not Equality Condition
WHERE column_name != value;
Greater Than Condition
WHERE column_name > value;
Less Than Condition
WHERE column_name < value;
Greater Than Condition
WHERE column_name >= value;
Greater Than Condition
WHERE column_name <= value;
Between Condition
WHERE column_name BETWEEN value1 AND value2;
IN Condition
WHERE column_name IN (value1, value2, ...);
IN Condition
WHERE column_name NOT IN (value1, value2, ...);
NULL Condition
WHERE column_name IS NULL;
NULL Condition
WHERE column_name IS NOT NULL;
Simple Equality Condition
WHERE column_name LIKE 'd%';
Simple Equality Condition
WHERE column_name LIKE '%d%';
Simple Equality Condition
WHERE column_name NOT LIKE 'd%';
AND Condition
WHERE column_name1 = value AND column_name2 = value;
AND Condition
WHERE column_name1 = value OR column_name2 = value;
Aggregate Function Operations
Aggregate Function Operations
SELECT COUNT(id) FROM table_name;
Aggregate Function Operations
SELECT MAX(age) FROM table_name;
Aggregate Function Operations
SELECT MIN(age) FROM table_name;
Aggregate Function Operations
SELECT SUM(age) FROM table_name;
Aggregate Function Operations
SELECT AVG(age) FROM table_name;
Aggregate Function Operations
SELECT UCASE(first_name), LCASE(first_name) FROM table_name;
Select Data from a Table
SELECT DISTINCT field1 FROM ...;
Select Data from a Table
SELECT DISTINCT field1, field2 FROM;
Function Operations
Simple Equality Condition
SELECT CONCAT(first_name, ' ', last_name) AS 'Name', dept FROM users;
DISTINCT
SELECT DISTINCT location FROM users;
NOW
SELECT NOW();
CURDATE
SELECT CURDATE();
CURTIME
SELECT CURTIME();
YEAR(NOW()),
SELECT YEAR(NOW());
TIMESTAMPDIFF
SELECT TIMESTAMPDIFF(MINUTE, '2023-01-01 12:00:00', NOW());
DATE_FORMAT
SELECT DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%s');
List Functions
\df
Group By
Group By
SELECT age, COUNT(age) FROM users GROUP BY age;
Group By
SELECT age, COUNT(age) FROM users WHERE age > 20 GROUP BY age;
Group By
SELECT age, COUNT(age) FROM users GROUP BY age HAVING count(age) >=2;
Subquery Operations
Subquery in WHERE Clause
SELECT * FROM table1 WHERE column_name IN (SELECT column_name FROM table2 WHERE condition);
Group By with Aggregate Function
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
Index Operations
Create Index
CREATE INDEX index_name ON table_name (column_name);
Create Index
CREATE TABLE t1 (col1 VARCHAR(10), col2 VARCHAR(20), INDEX index_name (col1, col2)
Create Index
CREATE TABLE t1 (col1 VARCHAR(10), col2 VARCHAR(20), INDEX index_name (col1, col2(10))
Create Index on Multiple Columns
CREATE INDEX index_name ON table_name (column1, column2, ...);
Create Unique Index
CREATE UNIQUE INDEX index_name ON table_name (column_name);
Create Unique Index on Multiple Columns
CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);
Drop Index
DROP INDEX index_name ON table_name;
List Indexes
\di
Lock Operations
FOR UPDATE
select * from Email where id > 10 and id < 15 FOR UPDATE;
FOR SHARE
select * from Email where id > 10 and id < 15 FOR SHARE;
Lock Tables for READ
LOCK TABLES table_name IN SHARE MODE;
Lock Tables for Write
LOCK TABLES table_name IN SHARE UPDATE EXCLUSIVE MODE;
Lock Tables for Write
LOCK TABLES table_name IN SHARE ROW EXCLUSIVEMODE;
Lock Tables for Write
LOCK TABLES table_name IN EXCLUSIVE MODE;
Lock Tables for Write
LOCK TABLES table_name IN ACCESS EXCLUSIVE MODE;
Lock Tables for Write
LOCK TABLES table_name IN SHARE ROW EXCLUSIVEMODE;
Lock Tables for READ
LOCK TABLES table_name IN ACCESS SHARE MODE;
Lock Tables for Write
LOCK TABLES table_name IN ROW SHARE MODE;
Lock Tables for Write
LOCK TABLES table_name IN ROW EXCLUSIVE MODE;
Transaction Operations
Start Transaction
Start Transaction: BEGIN
Start Transaction
Start Transaction: BEGIN TRANSACTION
Commit Transaction
Commit Transaction: COMMIT;
Commit Transaction
Commit Transaction: END TRANSACTION;
Rollback Transaction
ROLLBACK;
Auto commit
SET AUTOCOMMIT = ON|OFF;
Backup Database Operations
Backup
pg_dump -U username -h localhost -p port_number -d database_name -F c -f backup_file.dump
Import Database Operations
Import
pg_restore -U username -h localhost -p port_number -d database_name -F c -c backup_file.dump
Users and Privileges
Create User
CREATE USER new_user WITH PASSWORD 'your_password';
List Users
List Users: \du
Change User password
ALTER USER your_user WITH PASSWORD 'new_password';
Delete user
DROP USER user_name;
GRANT user privileges
GRANT permission_type ON DATABASE db_name to new_user;