SQL
SQL
Alter
ALTER TABLE statement adds a new columns to a table.
ALTER TABLE celebs
ADD Columns twitter_handle TEXT; # is the data type for the
new column
SELECT * FROM celebs;
NULL # is a special value in SQL that represent missing or
unknown data. In this case column was added Have NULL (∅) values
for twitter_handle.
UPDATE statement edits a row in a table. You can use the UPDATE
statemenet when you want to change existing records.
UPDATE celebs
SET twitter-handle = ‘@taylorswift13’
WHERE id = 4;
SELECT * FROM celebs;
DELETE # statement deletes one or more rows from a table.
DELETE FROM celebs
WHERE twitter_handle IS NULL;
SELECT * FROM celebs;
# en este caso elimina todos en donde twitter_handle es NULL,
dejando solamente Taylor Swift que fue agregada anteriormente.
QUERIES
SELECT
SELECT columns1, column2, FROM table_name;
SELECT name, genre, year FROM movies;
# con esto se consulta en la consola el nombre, el genero y
el año de las movies.
REVIEW INITIAL
SELECT is the clause we use every time we want to query
information from a database.
AS renames a column or table.
DISTINCT return unique values.
WHERE is a popular command that lets you filter the result of
the query based on conditions that you specify.
LIKE and BETWEEN are special operators.
AND & OR combine multiple conditions.
ORDER BY sort the result.
LIMIT specifies the maximum number of rows that the query
will return.
CASE create different outputs.
Aggregate Functions
COUNT(): count the number of rows # SELECT COUNT(column_name)
FROM table_name;
SUM(): the sum of the values in a column # SELECT SUM
(column_name) FROM table_name;
MAX()/MIN(): the larges/smallest value # SELECT
MAX/MIN(column_name) FROM table_name;
AVG(): the average of the values in a columns # SELECT AVG
(column_name) FROM table_name;
ROUND(): round the values in a column # SELECT names,
ROUND(AVG(test_score), 2 ) AS semester_avg FROM grades GROUP BY
names; #ROUND (values, decimal_places)
COUNT
SELECT COUNT (*) FROM fake_apps; # count hoe many apps are in
the table.
SELECT COUNT (*) FROM fake_apps WHERE price = 0; # count how
many free apps are in the table where price is 0.
SUM
SELECT SUM (downloads) FROM fake_apps;
MIN
SELECT MIN (downloads) FROM fake_apps;
MAX
SELECT MAX (price) FROM fake_apps;
AVERAGE
SELECT AVG (downloads) FROM fake_apps;
ROUND
SELECT name, ROUND(price, 0) FROM fake_apps;
SELECT ROUND(AVG(price), 2) FROM fake_apps, # we were able to
get the average price of an app ($2.02365) using this query
#INSTRUCTIONS
1# Join orders table and subscriptions table and select
all columns. Make sure to join on the subscription_id column.
2# Don’t remove the previous query. Add a second query
after you first one that only select rows from the join where
description is equal to ‘Fashion Magazine’.
-First query
SELECT * FROM orders JOIN subscriptions ON
orders.subscription_id = subscriptions.subscription_id;
-Second query
SELECT * FROM orders JOIN subscriptions ON
orders.subscription_id = subscriptions.subscription_id
WHERE subscriptions.description = ‘Fashion Magazine’;
INNER JOINS # when we perform a simple JOIN (often called an inner
join – union interna) our result only includes rows that match our
ON condition.
INSTRUCTIONS
1# Suppose we are working for the Codeacademy Times, a
newspaper with two types of subscriptions: print newspaper, online
articles. Some users subscribe to just the newpaper, some
subscribe to just the online edition, and some subscribe to both.
There is a newspaper table that contains information about the
newspaper subscribers. Count the number of subscribers who get a
print newspaper using COUNT().
2# Don’t remove your previous query. There is also an online
table that contains information about the online subscribers.
Count the number of subscribers who get an online newspapers using
COUNT().
3# Joins newspaper table and online table on their id columns
(the unique ID of the subscriber). How many rows are in this
table?
SELECT COUNT(*) FROM newspaper;
SELECT COUNT(*) FROM online;
SELECT COUNT(*) FROM newspaper JOIN online ON
newspaper.id = online.id;
LEFT JOINS # A left join will keep all rows from the first table,
regardless of whether there is a matching row in the second table.
SELECT * FROM table1 LFT JOIN table2 ON table1.c2 =
table2.c2;
EXAMPLE
SELECT * FROM newspaper
LEFT JOIN online
ON newspaper.id = onlie.id;
SELECT * FROM newspaper
LEFT JOIN onlie
ON newspaper.id = online.id;
PRIMARY KEY vs FOREIGN KEY
SELECT * FROM classes
JOIN students
ON classes.id = students.class_id;
# las claves primarias 1. Ninguno de los valores puede ser
NULL. 2. Cada valor deber ser único (es decir, no puede
haber dos clientes con el mismo customers_id en la customers
tabla) 3. Una tabla no puede tener mas de una columns de
clave principal siendo customer_id (la clave principal para
customers).
# cuando la clave principal de una tabla aparece en una
tabla diferente, se denomina Foreing Key
Cross Join
SELECT shirt.shirt_color, pants.pants_color
FROM shirts
CROSS JOIN pants;
Suppose we wanted to know how many users were subscribed
during each month of the year. For each month of the year. For
each month (1, 2, 3) we would need to know if a user was
subscribed. Follow the step below to see how we can use a CROSS
JOIN to solve this problem.
1# Let’s start by counting the number of customers who were
subscribed to the newspaper during March.
User COUNT(*) to count the number of rows and a ‘WHERE’
clause to restrict to two conditions: start_month <= 3|end _ month
<= 3.
2# The previous query lets us investigate one month at a
time. In order to check across all month, we’re going to need to
use a cross join. Our database contains another table called month
which contains the numbers between 1 and 12. Select all columns
from the cross join of newspaper and months.
3# Create a third query where you add a WHERE statement to
your CROSS JOIN to restrict to two conditions: start_month <=
month | end_month >= month. This will select all month where a
user was subscribed.
4# Create a final query where you aggregate over each month
to count the number of subscribers.
-First Query
SELECT COUNT (*)
FROM newspaper
WHERE start_month <= 3
And end_month >= 3;
-Second Query
SELECT *
FROM newspaper
CROSS JOIN months;
-Third Query
SELECT *
FROM newspaper
CROSS JOIN months
WHERE start_month <= month
AND end_month >= month;
-Four Query
SELECT month,
COUNT (*)
FROM newspaper
CROSS JOIN months
WHERE start_month <= month
AND end_month >= month
GROUP BY month;
UNION
Sometimes we just want to stack one dataset on top of the other.
Well, the UNION operator allows us to do that. 1# Tables must have
the same number of columns. 2# The columns have the same data
types in the same orders as the first table.
Exercise
Let’s return to our newspaper and online subscriptions. We’d
like to create one big table with both sets of data. Use
UNION to stack the newspaper table on top of the online
table.
SELECT *
FROM newspaper
UNION
SELECT *
FROM online;
WITH
Essentially, we are putting a whole first query inside the
parentheses () and giving it a name. After that, we can use this
name as if it’s a table and write a new query using the first
query.
WHIT previous_query AS(SELECT customer_id,
SELECT customer_id,
COUNT(subscription_id) AS
‘subscriptions’
FROM orders
GROUP BY customer_id
)
SELECT customers.customer_name,
previous_query.subscriptions
FROM previous_query
JOIN customers
ON previous_query.customer_id = customers.customer_id;