CREATE DATABASE record_company;
- Create a table with a column:
CREATE TABLE test (
test_column INT
);
- Add another column to a table:
ALTER TABLE test
ADD another_column VARCHAR(255);
- Full query for the
bands
and albums
tables:
CREATE DATABASE record_company;
USE record_company;
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 data into the
bands
table:
INSERT INTO bands (name)
VALUES ('Iron Maiden');
INSERT INTO bands (name)
VALUES ('Deuce'), ('Avenged Sevenfold'), ('Ankor');
- Query everuthing from the
bands
table:
- Query first two entries from the
bands
table:
SELECT * FROM bands LIMIT 2;
- Query the names of the columns from the
bands
table:
SELECT id AS 'ID', name AS 'Band name' FROM bands;
SELECT * FROM bands ORDER BY name DESC;
INSERT INTO albums (name, release_year, band_id)
VALUES
('The number of the beats', 1985, 1),
('Power slave', 1984, 1),
('Nightmare', 2018, 2),
('Test album', NULL, 3);
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 '%al%';
SELECT * FROM albums
WHERE name LIKE '%al%' 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 bands
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;
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
WHERE b.name = 'Deuce'
GROUP BY b.id
HAVING num_albums = 1;