0% found this document useful (0 votes)
34 views

Create Table: / Cria Ids Primary Keys Automaticamente, Sem Inserir Os Ids

The document provides an overview of common SQL commands used for data manipulation, including commands for creating and modifying database tables (CREATE TABLE, ALTER TABLE, DROP TABLE), inserting, updating, and deleting data (INSERT, UPDATE, DELETE), selecting data (SELECT), filtering and sorting query results (WHERE, ORDER BY, LIKE), aggregating data (SUM, AVG, COUNT), joining tables (INNER JOIN, OUTER JOIN, SELF JOIN), and explaining query plans (EXPLAIN). Examples are given for each command type to illustrate their syntax and usage.

Uploaded by

Felipe Sant'Anna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Create Table: / Cria Ids Primary Keys Automaticamente, Sem Inserir Os Ids

The document provides an overview of common SQL commands used for data manipulation, including commands for creating and modifying database tables (CREATE TABLE, ALTER TABLE, DROP TABLE), inserting, updating, and deleting data (INSERT, UPDATE, DELETE), selecting data (SELECT), filtering and sorting query results (WHERE, ORDER BY, LIKE), aggregating data (SUM, AVG, COUNT), joining tables (INNER JOIN, OUTER JOIN, SELF JOIN), and explaining query plans (EXPLAIN). Examples are given for each command type to illustrate their syntax and usage.

Uploaded by

Felipe Sant'Anna
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

https://www.codecademy.

com/articles/sql-commands

CREATE TABLE
CREATE TABLE table_name (column_1 datatype, column_2 datatype, column_3 datatype);
CREATE TABLE groceries (id INTEGER PRIMARY KEY, name TEXT, quantity INTEGER );

INSERT INTO
INSERT INTO table_name (column_1, column_2, column_3) VALUES (value_1, 'value_2',
value_3);
INSERT INTO groceries VALUES (1, "Bananas", 4);
INSERT INTO groceries VALUES (2, "Peanut Butter", 1);
INSERT INTO groceries VALUES (3, "Dark chocolate bars", 2);

AUTOINCREMENT
CREATE TABLE exercise_logs
(id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, minutes INTEGER, calories INTEGER,
heart_rate INTEGER);
INSERT INTO exercise_logs(type, minutes, calories, heart_rate) VALUES ("biking", 30, 100, 110);
/*Cria IDs primary keys automaticamente, sem inserir os IDs

SELECT
SELECT column_name FROM table_name;
SELECT * FROM groceries;

SELECT DISTINCT
/*somente valores não repetidos
SELECT DISTINCT column_name FROM table_name;

ORDER BY
SELECT column_name FROM table_name ORDER BY column_name ASC | DESC;
SELECT * FROM groceries ORDER BY aisle;

WHERE
SELECT column_name(s) FROM table_name WHERE column_name operator value;
SELECT * FROM groceries WHERE aisle > 5 ORDER BY aisle;

SUM
SELECT SUM(column_name) FROM table_name;
SELECT SUM(quantity) FROM groceries;

AVG
SELECT AVG(column_name) FROM table_name;
SELECT type, AVG(calories) AS avg_calories FROM exercise_logs GROUP BY type HAVING
avg_calories > 70

MÁX
SELECT MÁX(column_name) FROM table_name;
SELECT MÁX(quantity) FROM groceries;
COUNT()
SELECT COUNT(column_name) FROM table_name;
SELECT type FROM exercise_logs GROUP BY type HAVING COUNT(*) >= 2;

GROUP BY
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name;
SELECT SUM(quantity) FROM groceries GROUP BY aisle;
SELECT aisle, SUM(quantity) FROM groceries GROUP BY aisle;
/*Em tese colocar só uma column_name no SELECT e no GROUP BY para não dar “erro” de
informação

AND
SELECT column_name(s) FROM table_name WHERE column_1 = value_1 AND column_2 =
value_2;
SELECT * FROM exercise_logs WHERE calories > 50 AND minutes < 30;

OR
SELECT column_name FROM table_name WHERE column_name = value_1 OR column_name =
value_2;
SELECT * FROM exercise_logs WHERE calories > 50 OR heart_rate > 100;

IN
/* SEM IN */
SELECT * FROM exercise_logs WHERE type = "biking" OR type = "hiking" OR type = "tree
climbing" OR type = "rowing";
/* USANDO IN */
SELECT * FROM exercise_logs WHERE type IN ("biking", "hiking", "tree climbing", "rowing");

SUB-QUERYES
SELECT * FROM exercise_logs WHERE type IN (SELECT type FROM drs_favorites);
/* adicional de WHERE */
SELECT * FROM exercise_logs WHERE type IN (SELECT type FROM drs_favorites WHERE reason
= "Increases cardiovascular health");

LIKE e %%
Parte de Textos
SELECT column_name(s) FROM table_name WHERE column_name LIKE pattern;
SELECT * FROM exercise_logs WHERE type IN (SELECT type FROM drs_favorites WHERE reason
LIKE "%cardiovascular%");
where the value of the City column starts with letter "a" and ends with the letter "b".
SELECT * FROM Customers where city like "a%b"
second letter of the City is an "a".
SELECT * FROM Customers WHERE City LIKE '_a%';
AS
SELECT column_name AS 'Alias' FROM table_name;
SELECT type, SUM(calories) AS total_calories FROM exercise_logs GROUP BY type;

HAVING
Retorna uma condição do valor “agregado, não de cada linha individualmente
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name HAVING
COUNT(*) > value;
SELECT type, SUM(calories) AS total_calories FROM exercise_logs
GROUP BY type
HAVING total_calories > 150

CASE
SELECT column_name,
CASE
WHEN condition THEN 'Result_1'
WHEN condition THEN 'Result_2'
ELSE 'Result_3'
END
FROM table_name;
SELECT type, heart_rate,
CASE
WHEN heart_rate > 220-30 THEN "above max"
WHEN heart_rate > ROUND(0.90 * (220-30)) THEN "above target"
WHEN heart_rate > ROUND(0.50 * (220-30)) THEN "within target"
ELSE "below target"
END as "hr_zone"
FROM exercise_logs;

INNER JOIN
/* implicit inner join */
SELECT * FROM student_grades, students
WHERE student_grades.student_id = students.id;

/* explicit inner join - JOIN */


SELECT first_name, last_name, email, test, grade FROM students
JOIN student_grades
ON students.id = student_grades.student_id
SELECT students.first_name, students.last_name, student_projects.title
FROM students
JOIN student_projects
ON students.id = student_projects.student_id;

OUTER JOIN
/* outer join */ - quando não tem correspondente, coloca tabela da esquerda mesmo assim,
com variável NULL
SELECT students.first_name, students.last_name, student_projects.title
FROM students
LEFT OUTER JOIN student_projects
ON students.id = student_projects.student_id;

SELF JOIN
/* self join */
SELECT students.first_name, students.last_name, buddies.email as buddy_email
FROM students
JOIN students buddies
ON students.buddy_id = buddies.id;

COMBINANDO JOINS
/*2 JOINS*/
SELECT a.title, b.title FROM project_pairs
JOIN student_projects a
ON project_pairs.project1_id = a.id
JOIN student_projects b
ON project_pairs.project2_id = b.id;

EXPLAIN QUERY PLAN


/*Fala o plano de execução do código no SQLite

CÓDIGOS DE ESCRITA
UPDATE
UPDATE table_name SET some_column = some_value WHERE some_column = some_value;
UPDATE diary_logs SET content = "I had a horrible fight with OhNoesGuy" WHERE id = 1;

DELETE
DELETE FROM table_name WHERE some_column = some_value;
DELETE FROM diary_logs WHERE id = 1;

ALTER TABLE
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE diary_logs ADD emotion TEXT;
ALTER TABLE diary_logs ADD emotion TEXT default "unknown"; /* coloca o valor unknown
onde estiver vazio ap[os a criação

DROP TABLE
/* excluir banco de dados
DROP TABLE diary_logs;

You might also like