Создание таблицы и удаление
СОЗДАНИЕ
CREATE TABLE имя-таблицы
(
имя-поля тип-данных [ограничение целостности],
…
[ограничение целостности],
[первичный ключ],
[внешний ключ]
);
Пример:
CREATE TABLE aircrafts
(aircraft_code char(3) NOT NULL,
model text NOT NULL,
range integer NOT NULL,
CHECK (range > 0),
PRIMARY KEY (aircraft_code)
CREATE TABLE seats
aircraft_code char(3) NOT NULL,
seat_no varchar(4) NOT NULL,
fare_conditions varchar(10) NOT NULL,
CHECK (fare_conditions IN (‘Economy’, ‘Comfort’, ‘Business’)),
PRIMARY KEY (aircraft_code, seat_no);
FOREIGN KEY (aircraft_code)
REFERENCES aircrafts (aircraft_code)
ON DELETE CASCADE
УДАЛЕНИЕ
DROP TABLE имя-таблицы;
DROP TABLE aircrafts;
Ввод данных в таблицу, обновление данных в таблице
ВВОД В ТАБЛИЦУ
INSERT INTO имя-таблицы [(имя-атрибута, имя-атрибута, …)]
VALUES (значение-атрибута, значение-атрибута, …);
INSERT INTO aircrafts (aircraft_code, model, range)
VALUES (‘SU9’, ‘Sukhoi SuperJet-100‘, 3000);
ИЛИ НЕСКОЛЬКО ВСТАВОК СРАЗУ
VALUES (‘773’, ‘Boieng 777-300‘, 11100),
VALUES (‘763’, ‘Boieng 767-300‘, 7900),
VALUES (‘733’, ‘Boieng 737-300‘, 4200),
VALUES (‘320’, ‘Airbus A320-200‘, 5700),
VALUES (‘321’, ‘Airbus A321-200‘, 5600),
VALUES (‘319’, ‘Airbus A319-100‘, 6700),
VALUES (‘CN1’, ‘Cessna 208 Caravan‘, 1200),
VALUES (‘CR2’, ‘Bombardier’, 2700);
ОБНОВЛЕНИЕ В ТАБЛИЦЕ
UPDATE имя-таблицы
SET имя-атрибута1 = значение-атрибута1,
имя-атрибута2 = значение-атрибута2, …
WHERE условие;
ПРИМЕР
UPDATE aircrafts
SET range = 3500
WHERE aircrafts_code = ‘SU9‘;
УДАЛЕНИЕ В ТАБЛИЦЕ
DELETE FROM имя-таблицы WHERE условие;
либо без WHERE чтобы почистить вообще всё
DELETE FROM aircrafts WHERE aircraft_code = ‘SU9’;
DELETE FROM aircrafts;
Выбор атрибутов с упорядочением по атрибуту и с условием. Подсчет кол-ва кортежей с группировкой
С УПОРЯДОЧЕНИЕМ ПО АТРИБУТУ
SELECT model, aircraft_code, range
FROM aircrafts
ORDER BY model ASC;
ASC возрастание, DESC убывание
С УСЛОВИЕМ
WHERE range >= 4000 AND range <= 6000;
ПОДСЧЕТ КОЛ-ВА КОРТЕЖЕЙ С ГРУППИРОВКОЙ (То есть где одинаковые aircraft_code будет свой count)
SELECT aircraft_code, count(*) FROM seats
GROUP BY aircraft_code
ORDER BY count;
ГРУППИРОВКА С ДВУМЯ АТРИБУТАМИ
SELECT aircraft_code, fare_conditions, count(*)
FROM seats
GROUP BY aircraft_code, fare_conditions
ORDER BY aircraft_code, fare_conditions;
Создание таблицы с проверкой на ограничения и заданием значения по умолчанию(DEFAULT, CHECK). Уникальность значений в столбце (UNIQUE)
mark numeric(1) DEFAULT 5,
record_book numeric(4) UNIQUE,
range integer,
CONSTRAINT valid_range CHECK (range > 0)
Связь первичного и внешнего ключа. Чтобы удалить связанные таблицы, нужно наложить каскадное удаление(связных таблиц)
CREATE TABLE students
record_book numeric(5) PRIMARY KEY
CREATE TABLE progress
record_book numeric(5) REFERENCES students
ИЛИ
record_book numeric(5)
FOREIGN KEY (record_book)
REFERENCES students (record_book)
DROP TABLE IF EXISTS students CASCADE;
Модификация таблиц
ALTER TABLE airports
ADD COLUMN speed integer NOT NULL
CHECK (speed >= 30)
ALTER COLUMN latitude
SET DATA TYPE numeric(5,2);
Представления [VIEW[
CREATE VIEW имя-представления [(имя-столбца [, …])] AS запрос;
CREATE VIEW seats_by_fare_cond AS
SELECT * FROM seats_by_fare_cond;
изменение имя столбца
DROP VIEW seats_by_fare_cond;
CREATE OR REPLACE VIEW seats_by_fare_cond AS
SELECT aircraft_code, fare_conditions, count(*) AS num_seats
Материализованные представления
CREATE MATERIALIZED VIEW [IF NOT EXISTS] имя-мат-представления [ (имя-столбца[,…])]
AS запрос
[WITH [NO] DATA];
обновление
REFRESH MATERIALIZED VIEW название;
удалени
DROP MATERIALIZED VIEW название;
Last changed8 months ago