eolas/Databases/SQL/2_SELECT.md

83 lines
1.9 KiB
Markdown
Raw Normal View History

2022-08-05 20:00:04 +01:00
---
2022-08-16 11:58:34 +01:00
categories:
2022-08-05 20:00:04 +01:00
- Databases
2022-08-16 11:58:34 +01:00
- Programming_Languages
tags: [SQL]
2022-08-05 20:00:04 +01:00
---
# SQL: The SELECT query
## Print/retrieve/write an entire table, unfiltered
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:00:04 +01:00
SELECT * FROM [table_name]
SELECT * FROM model
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
## Retrieve all data from a specific field
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:00:04 +01:00
SELECT [field_name] FROM [table_name]
SELECT name FROM manufacturer
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
## Retrieve data and order it
2022-08-16 11:58:34 +01:00
This example orders alphabetically:
2022-08-05 20:00:04 +01:00
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:00:04 +01:00
SELECT [field_name] FROM [table_name] ORDER BY [property]
2022-08-16 11:58:34 +01:00
SELECT name FROM model ORDER BY name
```
> When `ORDER BY` is used the default method for strings is alphabetical and for integers it is ascending order.
2022-08-05 20:00:04 +01:00
Here's a more complex real-life request:
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:00:04 +01:00
SELECT name, cores, ram FROM model ORDER BY ram, name
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
It gives us:
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
name cores ram
---------------- ---------- ----------
Commodore VIC-20 1 0.005
Commodore 64 1 0.064
Amiga 500 1 0.5
Apple Lisa 1 1.0
Raspberry Pi 1 M 1 256.0
Raspberry Pi 1 M 1 256.0
Raspberry Pi 1 M 1 512.0
Raspberry Pi 1 M 1 512.0
Raspberry Pi 1 M 1 512.0
Raspberry Pi Zer 1 512.0
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
But we can obviously specify our own ordering method:
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:00:04 +01:00
SELECT name, cores, release_date FROM model ORDER BY cores DESC, name;
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
Returns:
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
name cores release_date
----------------- ---------- ------------
Apple MacBook Pro 6 2019-05-21
Apple iMac 4 2019-03-19
Raspberry Pi 2 Mo 4 2015-02-01
Raspberry Pi 3 Mo 4 2018-11-01
Raspberry Pi 3 Mo 4 2016-02-01
Raspberry Pi 3 Mo 4 2018-03-14
Raspberry Pi 4 Mo 4 2019-06-24
Raspberry Pi 4 Mo 4 2019-06-24
Raspberry Pi 4 Mo 4 2019-06-24
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:00:04 +01:00
2022-08-16 11:58:34 +01:00
> `ORDER BY` always comes last, after the selection and any filtering clauses but _before_ a `WHERE` clause