-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_commands.sql
113 lines (78 loc) · 2.09 KB
/
basic_commands.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
CREATE DATABASE record_company;
USE record_company;
CREATE TABLE test (
test_column INT
);
ALTER TABLE test
ADD another_column VARCHAR(255);
DROP TABLE test;
DROP TABLE bands;
DROP TABLE albums;
CREATE TABLE bands(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE albums (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
release_year INT,
band_id INT NOT NULL,
PRIMARY KEY(id),
FOREIGN KEY (band_id) REFERENCES bands(id)
);
INSERT INTO bands(name)
VALUES ('Iron Maiden');
INSERT INTO bands (name)
VALUES ('Deuce'), ('Avenged Sevenfold'), ('Ankor');
SELECT * FROM bands;
SELECT * FROM bands LIMIT 2;
SELECT name FROM bands;
SELECT id AS 'ID', name AS 'Band Name'
FROM bands;
SELECT * FROM bands ORDER BY name;
INSERT INTO albums (name, release_year, band_id)
VALUES ('The Number of the Beasts', 1985, 1),
('Power Slave', 1984, 1),
('Nightmare', 2018, 2),
('Nightmare', 2010, 3),
('Test Album', NULL, 3);
SELECT * FROM albums;
SELECT name FROM albums;
SELECT DISTINCT name FROM albums;
UPDATE albums
SET release_year =1982
WHERE id = 1;
SELECT * FROM albums
WHERE release_year < 2000;
SELECT * FROM albums
WHERE name LIKE '%er%' OR band_id = 2;
SELECT * FROM albums
WHERE release_year = 1984 AND band_id = 1;
SELECT * FROM albums
WHERE release_year BETWEEN 2000 AND 2018;
SELECT * FROM albums
WHERE release_year IS NULL;
DELETE FROM albums WHERE id = 5;
SELECT * FROM albums;
SELECT * FROM bands
JOIN albums ON bands.id = albums.band_id;
SELECT * FROM bands
INNER JOIN albums ON bands.id = albums.band_id;
SELECT * FROM bands
LEFT JOIN albums ON bands.id = albums.band_id;
SELECT * FROM bands
RIGHT JOIN albums ON bands.id = albums.band_id;
SELECT * FROM albums
RIGHT JOIN bands ON bands.id = albums.band_id;
SELECT AVG(release_year) FROM albums;
SELECT band_id, COUNT(band_id) FROM albums
GROUP BY band_id;
SELECT b.name AS band_name, COUNT(a.id) AS num_albums
FROM bands AS b
LEFT JOIN albums AS a ON b.id = a.band_id
GROUP BY b.id
Having num_albums = 1;
/*
WHERE vs HAVING
*/