{"id":18299922,"url":"https://github.com/shuvoprogram/postgres_cheatsheet","last_synced_at":"2025-07-05T15:03:36.367Z","repository":{"id":190554444,"uuid":"682622779","full_name":"ShuvoProgram/Postgres_CheatSheet","owner":"ShuvoProgram","description":"Master PostgreSQL with this concise cheatsheet! Discover essential commands for database creation, querying, data manipulation, and user management. Level up your SQL skills and manage databases efficiently. Your one-stop reference for PostgreSQL success. #PostgreSQL #DatabaseManagement","archived":false,"fork":false,"pushed_at":"2023-08-26T17:41:00.000Z","size":7,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-15T03:29:33.960Z","etag":null,"topics":["postgresql"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ShuvoProgram.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-08-24T15:07:18.000Z","updated_at":"2023-08-25T05:24:41.000Z","dependencies_parsed_at":"2024-11-05T15:10:51.130Z","dependency_job_id":null,"html_url":"https://github.com/ShuvoProgram/Postgres_CheatSheet","commit_stats":null,"previous_names":["shuvoprogram/postgres_cheatsheet"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShuvoProgram%2FPostgres_CheatSheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShuvoProgram%2FPostgres_CheatSheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShuvoProgram%2FPostgres_CheatSheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShuvoProgram%2FPostgres_CheatSheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ShuvoProgram","download_url":"https://codeload.github.com/ShuvoProgram/Postgres_CheatSheet/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248010125,"owners_count":21032851,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["postgresql"],"created_at":"2024-11-05T15:10:44.595Z","updated_at":"2025-04-09T09:25:12.850Z","avatar_url":"https://github.com/ShuvoProgram.png","language":null,"readme":"# PostgreSQL Database Management Commands\n\nThis repository contains a collection of PostgreSQL commands for various database management tasks.\n\n## Introduction\n\nThis repository provides a set of PostgreSQL commands and examples for managing databases, tables, and data. Each section covers a specific aspect of database management, and the commands are presented with explanations for better understanding.\n\n## Grant Permissions\n\nGrant the necessary permissions to users for performing specific actions within the database.\n\n- **Grant the \"CONNECT\" permission to the \"test\" database for the \"postgres\" user:**\n  ```sql\n  GRANT CONNECT ON DATABASE test TO postgres;\n\n- **Grant the permission to create databases to the \"postgres\" user:**\n  ```sql\n  ALTER USER postgres CREATEDB;\n\n## Database Operations\n\n- **Create a new database named \"test2\":**\n  ```sql\n  CREATE DATABASE test2;\n\n- **Rename the database \"test2\" to \"test3\":**\n  ```sql\n  ALTER DATABASE test2 RENAME TO test3;\n\n- **Delete the \"test3\" database:**\n  ```sql\n  DROP DATABASE test3;\n\n## Table Operations\n\n- **Create a \"student\" table with columns for student information:**\n  ```sql\n  CREATE TABLE student (\n    student_id INT,\n    first_name VARCHAR(15),\n    last_name VARCHAR(15),\n    cgpa NUMERIC(1, 2) );\n\n- **Rename the \"student\" table to \"learner\":**\n  ```sql\n  ALTER TABLE student RENAME TO learner;\n\n- **Delete the \"learner\" table:**\n  ```sql\n  DROP TABLE learner;\n\n## Table Operations\n\n- **Create a \"users\" table with columns for user information and constraints:**\n  ```sql\n  CREATE TABLE users (\n    user_id SERIAL PRIMARY KEY,\n    username VARCHAR(50) NOT NULL,\n    email VARCHAR(50) NOT NULL,\n    age INT DEFAULT 18,\n    UNIQUE(username, email));\n\n- **Remove all data from the \"users\" table while keeping its structure:**\n  ```sql\n  TRUNCATE TABLE users;\n\n- **Insert user data into the \"users\" table using various methods:**\n\n- **Method 1:**\n  ```sql\n  INSERT INTO users(user_id, username, email, age)\n  VALUES ('sam', 'sam@gmail.com', 21);\n\n- **Method 2:**\n  ```sql\n  INSERT INTO users(username, email, age)\n  VALUES ('clark', 'clark@gmail.com', 35),\n       ('clark2', 'clark2@gmail.com', 35);\n\n- **Method 3:**\n  ```sql\n  INSERT INTO users\n  VALUES (1, 'persian', 'persian@gmail.com'),\n       (2, 'persian2', 'persian2@gmail.com');\n\n- **Add a \"password\" column to the \"users\" table with a default value:**\n  ```sql\n  ALTER TABLE users\n  ADD COLUMN password VARCHAR(255) DEFAULT 'admin123' NOT NULL;\n\n- **Delete the \"age\" column from the \"users\" table:**\n  ```sql\n  ALTER TABLE users DROP COLUMN age;\n\n- **Add and modify columns in the \"users\" table:**\n  ```sql\n  ALTER TABLE users ADD COLUMN demo INT;\n  ALTER TABLE users ALTER COLUMN demo TYPE TEXT;\n  ALTER TABLE users ALTER COLUMN country SET DEFAULT 'bangladesh';\n  ALTER TABLE users ALTER COLUMN demo DROP DEFAULT;\n\n- **Insert a user with specific values into the \"users\" table:**\n  ```sql\n  INSERT INTO users VALUES(4, 'john1', 'john1@gmail.com');\n\n- **Rename the \"demo\" column to \"country\" in the \"users\" table:**\n  ```sql\n  ALTER TABLE users RENAME COLUMN demo TO country;\n  ALTER TABLE users ALTER COLUMN country SET NOT NULL;\n\n- **Drop the \"NOT NULL\" constraint from the \"country\" column:**\n  ```sql\n  ALTER TABLE users ALTER COLUMN country DROP NOT NULL;\n\n- **Add a unique constraint to the \"email\" column in the \"users\" table:**\n  ```sql\n  ALTER TABLE users ADD CONSTRAINT unique_email UNIQUE(email);\n\n- **Delete the unique constraint from the \"email\" column in the \"users\" table:**\n  ```sql\n  ALTER TABLE users DROP CONSTRAINT unique_email;\n\n## Retrieving Data\n\n- **Retrieve all data from the \"users\" table:**\n  ```sql\n  SELECT * FROM users;\n\n\n## Foreign Keys Constraint And Data Integrity\n\n- **Create a table named \"Employees\" to store employee information.:**\n  ```sql\n  CREATE TABLE Employees (\n      empID SERIAL PRIMARY KEY,\n      empName VARCHAR(50) NOT NULL,\n      departmentID INT,\n      CONSTRAINT fk_constraint_dept FOREIGN KEY (departmentID) REFERENCES Department(deptID)\n  );\n\nExplanation: Create a table to store employee details with a foreign key constraint.\n\n- **Retrieve Specific table column:**\n  ```sql\n  SELECT empid, name, email, joining_date, salary, from employees;\n\n  SELECT *\n  FROM employees\n  WHERE\n      name \u003c\u003e 'Eve'\n      AND salary \u003e 9000\n      OR name = 'Greta'\n\n- **Update Course Data:**\n  ```sql\n  UPDATE courses\n  SET\n      course_name = 'laravel',\n      description = 'super'\n      WHERE course_id = 1;\n\nExplanation: Update course data where course_id is 1.\n\n- **Update Multiple Course Data:**\n  ```sql\n  UPDATE courses\n  SET\n      course_name = 'laravel',\n      description = 'super'\n      WHERE course_id \u003e 1;\n\nExplanation: Update course data for courses with course_id greater than 1.\n\n- **Delete Course Data:**\n  ```sql\n  DELETE FROM courses WHERE course_id = 1;\n\nExplanation: Delete course data where course_id is 1.\n\n## Employees Table (Continued)\n\n- **Create Employees Table (Conditional):**\n  ```sql\n  CREATE TABLE IF NOT EXISTS employees (\n    empID SERIAL PRIMARY KEY,\n    name text NOT NULL,\n    email TEXT NOT NULL,\n    salary INT not NULL,\n    joining_data DATE NOT NULL,\n    deptID INT NOT NULL,\n    CONSTRAINT fk_deptID FOREIGN KEY (deptID) REFERENCES department(deptID));\n\nExplanation: Create employees table if it doesn't exist.\n\n- **Select Specific Columns from Employees Table:**\n  ```sql\n  SELECT empid, name, email, joining_date, salary FROM employees;\n\nExplanation: Retrieve specific columns from the employees table.\n\n- **Filtering Rows with Conditions:**\n  ```sql\n  SELECT * FROM employees WHERE name LIKE '_r%';\n\n  SELECT * FROM employees WHERE name LIKE '__r__';\n\n  SELECT * FROM employees WHERE name LIKE 'G%a';\n\n  SELECT * FROM employees WHERE deptid IS NULL;\n\nExplanation: Retrieve rows based on specified conditions.\n\n- **Sorting and Limiting Results:**\n  ```sql\n  SELECT * FROM employees ORDER BY name ASC LIMIT 10 OFFSET 2;\n\nExplanation: Retrieve sorted and limited rows from employees table.\n\n- **Retrieving Maximum Salary:**\n  ```sql\n  SELECT * FROM employees ORDER BY salary DESC LIMIT 1;\n\nExplanation: Retrieve employee with the highest salary.\n\n- **IN, NOT IN, BETWEEN, and LIKE Operators:**\n  ```sql\n  SELECT * FROM employees WHERE empid NOT IN (2, 3, 5);\n  SELECT * FROM employees WHERE salary BETWEEN 10000 AND 15000;\n  SELECT * FROM employees WHERE name LIKE 'A%';\n\nExplanation: Retrieve rows based on various filtering conditions.\n\n## Joining Tables \n\n- **Inner Join with Explanation:**\n  ```sql\n  SELECT *\n  FROM employees\n    INNER JOIN department ON employees.deptid = department.deptid;\n\nExplanation: Retrieve all columns from both tables where the department ID matches in both tables.\n\n- **Left Join:**\n  ```sql\n  SELECT *\n  FROM employees\n  LEFT JOIN department ON department.department_id = employees.department_id;\n\nExplanation: Retrieve all rows from the left table and matching rows from the right table.\n\n- **Right Join:**\n  ```sql\n  SELECT *\n  FROM employees\n  RIGHT JOIN department ON department.department_id = employees.department_id;\n\nExplanation: Retrieve all rows from the right table and matching rows from the left table.\n\n\n- **Full Outer Join:**\n  ```sql\n  SELECT *\n  FROM employees\n  FULL JOIN department ON department.department_id = employees.department_id;\n\nExplanation: Retrieve all rows when there is a match in either the left or right table.\n\n- **Cross Join:**\n  ```sql\n  SELECT * FROM employees CROSS JOIN department;\n\nExplanation: Generate all possible combinations of rows between two tables.\n\n## Aggregate Functions\n\nPerform calculations on groups of rows and summarize data\n\n- **Aggregate Functions with Explanation:**\n  ```sql\n  SELECT\n    d.name,\n    AVG(e.salary),\n    SUM(e.salary),\n    MAX(e.salary)\n  FROM employees e\n    FULL JOIN department d ON e.dept = d.dept\n  GROUP BY d.name\n  HAVING AVG(e.salary) \u003e 60000;\n\nExplanation: Calculate average, sum, and maximum salary for each department, filtering results using the HAVING clause.\n\n- **Aggregate Functions with GROUP BY:**\n  ```sql\n  SELECT\n    d.name,\n    SUM(salary),\n    AVG(salary),\n    MIN(salary),\n    COUNT(*)\n  FROM department d\n    FULL JOIN employees e ON e.dept = d.deptid\n  GROUP BY d.deptid;\n\nExplanation: Group and aggregate salary data by department, calculating sum, average, minimum, and count.\n\n## Subqueries\n\nUse subqueries to perform complex queries within other queries\n\n- **Aggregate Functions with GROUP BY:**\n  ```sql\n  SELECT\n    film_id,\n    title,\n    rental_rate\n  FROM film\n  WHERE rental_rate \u003e 2.98;\n\nExplanation: Retrieve film details where the rental rate is greater than 2.98.","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshuvoprogram%2Fpostgres_cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshuvoprogram%2Fpostgres_cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshuvoprogram%2Fpostgres_cheatsheet/lists"}