markdown Postgres SQL命令备忘单

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Postgres SQL命令备忘单相关的知识,希望对你有一定的参考价值。

# Postgres Cheat Sheet

## Create Database
```
create database sample_db;
```
## Psequel command to show databases 
>\l
## Psequel command to show all relation
>\d
## Quit from command line
>\q
## Create Sample Table  
> Example 1
```
CREATE TABLE people(
        id INTEGER,
        name VARCHAR(255)

)
```
> Example 2
```
CREATE TABLE flights(
         id SERIAL PRIMARY KEY,
         origin VARCHAR NOT NULL,
         destination VARCHAR NOT NULL,
         duration INTEGER NOT NULL
);
```
## Drop Table
```
DROP TABLE people;
```
## Insert
>Type 1
```
INSERT INTO people VALUES (1,'Corey')
INSERT INTO people VALUES (2,'Travis')
```

> Type 2
```
INSERT INTO people (id,name) VALUES (3,'John')
INSERT INTO people (name,id) VALUES ('Harry',4)
```
## Select Satement
>All Select
```
SELECT * FROM people;
```
>Specific Field
```
SELECT first_name,last_name FROM people;
```
>Filter with "WHERE"(1)
```
SELECT * FROM people
WHERE last_name='joe';
```
>Filter with "WHERE" and "OR"
```
SELECT * FROM people
WHERE last_name='joe'
OR last_name='Chanda';
```
> Filter with "WHERE" and "AND"
```
SELECT * FROM people
WHERE last_name='joe'
AND age<33;
```
> Conditonals
```
SELECT * FROM people
WHERE age>20;
```
>Ordering(ascending)(Default)
```
SELECT * FROM people
WHERE age >20
ORDER BY age ASC; 
```
>Ordering(descending)
```
SELECT * FROM people
ORDER BY age DESC; 
```
>Ordering(Mutiple fields)
```
SELECT * FROM people
ORDER BY first_name,last_name ; 
```
> Use  AVG Function
```
SELECT AVG(duration) FROM flights;
```
> Use SUM Function
```
SELECT SUM(duration) FROM flights;
```
>Use COUNT Function
>Example 1
```
SELECT COUNT(*) FROM flights;
```
>Example 2

```
SELECT COUNT(*) FROM flights WHERE origin='California';
```
> Use MIN Function
```
SELECT MIN(duration) FROM flights
```
>Use MAX Function
```
SELECT MAX(duration) FROM flights
```
> String Matching
```
SELECT * FROM flights WHERE origin LIKE '%a%';
```
>LIMIT keyword
```
SELECT * FROM flights LIMIT 2
```
> LIMIT + ORDERING
```
SELECT *  FROM flights ORDER BY duration ASC LIMIT 3
```
## Update Statement
>Update all entry of specific field
```
UPDATE test_table 
SET location ='unknown';
```
> Update Specific field with Condition and Filter

```
UPDATE people
SET occupation ='Garbage'
WHERE first_name='Dibaloke'
AND last_name='Chanda'
```
## Delete Statement
> Delete Everything from a table
```
DELETE FROM test_table
```
> Delete Specific field by filtering
```
  DELETE FROM flights WHERE destination='London'
```
## Complex Queries
>GROUP BY 
```
SELECT origin,COUNT(*) FROM flights GROUP BY origin
````

以上是关于markdown Postgres SQL命令备忘单的主要内容,如果未能解决你的问题,请参考以下文章

markdown Postgres - 将表导出为SQL

markdown Git命令备忘单

markdown MacOS命令备忘单

markdown PostgreSQL命令行备忘单

markdown nginx命令备忘录

markdown Django命令备忘单