markdown PSQL片段

Posted

tags:

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

## Using CASE Statements in PSQL
* Using a `CASE` statement in the `SELECT` clause **creates a column** which you can alias:

```SQL
SELECT a,
  (CASE WHEN column_name = some_value THEN "COLUMN VALUE"
     WHEN column_name = another_value THEN "ANOTHER COLUMN VALUE"
  END) AS 'PARM'
FROM ...
```

* MUST WRAP IN PARENTHESES!

---
## SubQueries
* You can create a column using a subquery **(A `SELECT` within a `SELECT`)**

```SQL
SELECT *,
  SELECT (name FROM ...) AS "PARM"
  ...
```

* You can also insert a `SELECT` inside a `FROM` clause!
  * Remember, a `SELECT` can return a table which is what you are passing to when using
  the `FROM` clause!

```SQL
 SELECT column_name1, column_name2
 FROM (SELECT col_n1, col_n2, column_name1
       FROM table
       GROUP BY column_name1) AS "..."
ORDER BY column_name2
```

## REPLACE
* Use the `REPLACE` function to **remove** part of the text entry in a record's column field
* Returns a column

```SQL
SELECT col_1,
  REPLACE(column_name, string_you_want_to_replace, string_replacing_the_removed_string) AS ''
  ...
```

---

### Obtaining all the column names in a table
```sql
SELECT * 
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'table_name'
```

* `information_schema` is an actual table in the postgresql database
* `table_schema = 'public'` is the name of the schema in your psql database

---
## Converting a list of items into a table
* This will return a table that contains table names not found in the `unnest(ARRAY)` list
from the `information_schema.tables`

```sql
SELECT * FROM unnest(ARRAY['services', 'order_logs', 'art_elements'])
WHERE unnest NOT IN (
	select table_name
	FROM information_schema.tables
	where table_schema = 'public'
)
```
---
### TIP
* **If, when you add a filter in the `WHERE` clause reduces the amountof records obtained, but you still need all the records
try moving that filter to the `ON` part of the `JOIN` table clause**

以上是关于markdown PSQL片段的主要内容,如果未能解决你的问题,请参考以下文章

markdown PSQL

markdown Mysql到Psql

markdown psql查询到文件 - OUTPUT QUERY,EXPORT QUERY

markdown psql如何使用SSH隧道远程服务器中的数据库?

VS Code配置markdown代码片段

VS Code配置markdown代码片段