0% found this document useful (0 votes)
17 views11 pages

SQL

Uploaded by

Matt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
17 views11 pages

SQL

Uploaded by

Matt
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

SQL

SELECT * FROM celebs; # presenta la table celebs.


CREATE TABLE table name (column_1 data_type, column_2 data_type,
column_3 data_type);
CREATE TABLE # es una clausula y cumplen funciones especificas,
por convención se escribe en mayúsculas table_name #refers to the
name of the table that the command is applied to (column_1
data_type, column_2 data_type, column_3 data_type) # is a
parameter. A parameter is a list of columns, data types, or values
that are passe to a clause as an argument.
CREATE TABLE celebs(id INTEGER, name TEXT, age INTEGER);
# id is the first columns in the table. It store values of
data type INTEGER
# name is the second column in the table. It store values of
data type TEXT
# age is the third column in the table. It store values of
data type INTEGER
INSERT INTO celebs (id, name, age)
VALUES (1, 'Justin Bieber', 22);
INSERT INTO celebs (id, name, age)
VALUES (2, 'Beyonce Knowles', 33);
INSERT INTO celebs (id, name, age)
VALUES (3, 'Jeremy Lin',26);
INSERT INTO celebs (id, name, age)
VALUES (4, 'Taylor Swift', 26);
SELECT name FROM celebs; # name is a column of the celebs table

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.

CONSTRAINS # that add Information about how a column can be used


are invoked after specifying the data type for a column. They can
be used to tell the database to reject inserted data that does not
adhere to a certain restriction
CREATE TABLE awards (id INTEGER PRYMARY KEY, recipient TEXT NOT
NULL, award_name TEXT DEFAULT ‘Grammy?);
PRIMAY KEY columns can be used to uniquely identify the row.
Attempts to insert a row with an identical values to a row already
in the table will result in a constraint violation which will not
allow you insert the row.
UNIQUE columns have a different value for every row. This is like
PRIMARY KEY except a table can have many different UNIQUE columns.
NOT NULL columns must have a value. Attempts to insert a row
whitout a values for a NOT NULL column will result in a constraint
violation and the new row will not be inserted.
DEFAULT columns take an additional argument that will be assumed
value for an insert row if the new row does not specify a value
for that column.
Review
CREATE TABLE creates a new table.
INSERT INTO add a new row to a table.
SELECT queries data from a table.
ALTER TABLE changes an existing table.
UPDATE edits a row in a table.
DELETE FROM delete rows from a table.

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.

AS # is a keyword in SQL that allows you to rename a column or


table using an alias.
SELECT imdb_rating AS ‘IMDb’ FROM movies;
DISTINCT # regresa el valor único de salida, filtra todos los
valores duplicados en una columna(s) especifica.
SELECT DISTINCT genre FROM movies; # retorna cada uno de los
géneros que se tiene como (acción, comedia, romance, etc.)
WHERE # clause in order to obtain only the information we want.
SELECT * FROM movies WHERE year < 2014, # con esto solo
mostramos las películas mayores al 2014, solo sigue la condición
si es verdadera y el operador solo puede ser evaluados con
verdadero o falso.
LIKE II # the percentage sign % is another wildcard character that
can be used with LIKE.
SELECT * FROM MOVIES WHERE name LIKE ‘%man%’; # cuantos
titulos de peliculas tienen la palabra ‘man’
%A matches all movies with names that begin with letter ‘A’ #
si quiere comprobar THE se usa un espacio ‘THE %’
%a matches all movies that end with a ‘a’
Is Null # los valores desconocidos son indicados por NULL
SELECT name FROM movies WHERE imdb_rating is NULL; # muestra
solo las movies que IMDb is NULL
BETWEEN # is used in a WHERE clause to filtr the result set within
a certain range. Example WHERE year BETWEEN 1990 AND 1999.
Inclusive filters the result set for within the alphabetical range
WHERE name BETWEEN ‘A’ AND ‘J’; that begin with the letter ‘A’ up
to, but not including ones that begin with ‘J’.
SELECT * FROM movies WHERE name BETWEEN ‘D’ AND ‘G’; # name
begins with the letter ‘D’, ’E’ and ‘F’
SELECT * FROM movies WHERE year BETWEEN 1970 AND 1979;
AND # used to combine multiple conditions in a WHERE clause to
make the result set more specific and useful.
SELECT * FROM movies WHERE year BETWEEN 1970 AND 1979 AND
imdb_rating > 8;
SELECT * FROM movies WHERE year <1985 AND genre = ‘ horror’;
OR # operator display a row if any condition is true
SELECT * FROM movies WHERE year > 2014 OR genre = ‘action’;
SELECT * FROM movies WHERE genre = ‘romance’ OR genre =
‘comedy’;
ORDER BY # ordenar por
SELECT name, year FROM movies ORDER BY name;
SELECT name, year, imdb_rating FROM movies ORDER BY
imbd_rating DESC # ASC = ascendente ; DESC = descendente

LIMIT # is a clause that lets you specify the maximum number of


rows the result set will have,
SELECT * FROM movies ORDER BY imdb_rating DESC LIMIT 3; # con
esto se limita a las mejores tres pelicualas calificadas,
seleccionando todas las columnas.

CASE # nos permite crear diferentes outputs (if, elif, else)


SELECT name,
CASE
WHEN genre = ‘romance’ THEN ‘chill’
WHEN genre = ‘comedy’ THEN ‘chill’
ELSE ‘Intense’
END AS ‘Mood’
FROM movies
# se muestra el nombre y el mood que tiene la película, el
THEN nombra la película en la nueva categoría Mood

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

GROUP BY # is a clause in SQL that is used with aggregate


functions. IT used in collaboration with the SELECT statement to
arrange identical data into groups. # GROUP BY statement comes
after any WHERE statements, but before ORDER BY or LIMIT.
SELECT price, COUNT(*) FROM fake_apps GROUP BY price;
MULTIPLE TABLES
SELECT * FROM orders LIMIT 5; #order would contain just the
information necessary to describe what was ordered: order_id,
customer_id, subscription_id, purchase_date
SELECT * FROM subscription LIMIT 5; # costumer_id,
customer_name, address.

COMBINING TABLES MANUALLY


Orders; subscriptions; customers
COMBINING TABLES WITH SQL
# If we want to combine orders and costumers
SELECT * FROM orders JOIN customers ON orders.customer_id =
customers.customer_id;

#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;

Review Multiple Tables


JOIN: will combine rows from different tables if the join
condition is true.
LEFT JOIN: will return every row in the left table, and if the
join condition is not met, NULL values are used to fill in the
columns from the right table.
PRIMARY KEY: is a column that serves a unique identifier for the
rows in the table.
FOREINZG KEY: is a column that contains the primary key to
another table.
CROSS JOIN: let’s us combine all rows of one table with all rows
of another table.
UNION: stacks one dataset on top of another.
WITH: allows us to define one or more temporary tables that can
be used in the final query.

You might also like