Cyan's Blog

Search

Search IconIcon to open search

Codecademy_SQL_Tutorial-Notes-Database

Last updated Sep 26, 2021 Edit Source

# SQL Tutorial

2021-09-26

Tags: #Database #SQL #SQLite

复习材料:

下面只叙述CheatSheet里面没有的内容

# Clauses

CREATE TABLE is a clause. Clauses perform specific tasks in SQL. By convention, clauses are written in capital letters. Clauses can also be referred to as commands. INSERT, SELECT etc. are also clauses. 中文: 子句?

# INSERT

1
2
3
4
5
 INSERT INTO celebs (id, name, age)
 VALUES (1, 'Justin Bieber', 22);

 INSERT INTO celebs (name, id, age)
 VALUES ('Jeremy Lin', 3, 26);
1
2
3
4
5
INSERT INTO table (col1, col2, col3)
VALUES
(row1_val1, row1_val2, row1_val3),
(row2_val1, row2_val2, row2_val3),
(row3_val1, row3_val2, row3_val3);

# ALTER

Order:

# Question

In the context of this exercise 89, can we add a column at a specific position to a table?

# Answer

No, unfortunately, you cannot specify what position to add a column to a table.

By default, a new column will always be added at the end of the table. For most intents and purposes, this should not affect much, since you can always select the columns in any order, for instance, like

1
SELECT col3, col1, col2

If column order is very important, then an alternative is to create a new table and add the columns in the specific order they should appear.

# DELETE

1
2
DELETE FROM celebs 
WHERE twitter_handle IS NULL;

# SQLite

# Part 2 Queries

# AS

1
2
SELECT name AS movie, imdb_rating AS IMDb
FROM movies;

# WHERE

# LIKE

# Question

Can we apply the LIKE operator to values other than TEXT?

# Answer

Yes, you can apply the LIKE operator to numerical values as well.

Whenever you use LIKE however, you must always wrap the pattern within a pair of quotations, whether for matching a number or a string.

# Example

1
2
3
4
5
6
7
/* 
This will select movies where the id number
starts with 2 and is followed by any two numbers.
*/
SELECT * 
FROM movies
WHERE id LIKE '2__';

# BETWEEN

1
2
3
SELECT *
FROM movies
WHERE year BETWEEN 1990 AND 1999;

这个范围是 [1990, 1999], 包括了1999,

但是如果是字符串的话, 就变得稍微有一点复杂: 看这个:

1
2
3
SELECT *
FROM movies
WHERE name BETWEEN 'A' AND 'J';

‘Jaw’ 会包括在里面吗? -> 不会 但是’J’会包括在里面

因为其实是这个顺序: ‘A’, ‘Aa’ …… ‘J’, ‘Ja’,……….. 到’J’那里就停下来了.

# CASE

1
2
3
4
5
6
7
SELECT name,
 CASE
  WHEN imdb_rating > 8 THEN 'Fantastic'
  WHEN imdb_rating > 6 THEN 'Poorly Received'
  ELSE 'Avoid at All Costs'
 END AS 'Review'
FROM movies;
1
2
3
4
5
6
7
8
9
SELECT *,
  CASE
    WHEN review > 4.5 THEN 'Extraordinary'
    WHEN review > 4   THEN 'Excellent'
    WHEN review > 3   THEN 'Good'
    WHEN review > 2   THEN 'Fair'
    ELSE 'Poor'
  END AS 'New Review'
FROM nomnom;

CASE是从上向下匹配的, 所以第二行的不用再说明要小于4.5:

# Multiple Tables

# Inner Join

# LEFT JOIN

# 学完了

有三个网站来回顾学习内容: