Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

SQL

2024-01-04

BASIC SELECTING

Selecting different columns of a table

SELECT column1, column2


FROM table;

Changing the name in the selection

SELECT column1 AS feature1, column2


FROM table;

Select only distinct records from column1

SELECT DISTINCT column1, column1


FROM table;

Creating a view (save a query result)

CREATE VIEW view_name AS


SELECT column1 column_2
FROM table;

Count number of observations

SELECT count(*) AS total_records


FROM people;

FILTERING

Numerical filtering

1
SELECT column_1
FROM table
WHERE numerical_column >= 1970;

Categorical filtering

SELECT column_1
FROM table
WHERE column_2 = 'categorical_value';

Multiple criteria filtering

–>

SELECT *
FROM table
WHERE column_1 = 'value1' OR column_2 = 'value2'

SELECT *
FROM table
WHERE column_1 IN ('value','vaue','value');

SELECT *
FROM table
WHERE column_1 = 'value_1' AND column_2 = 'value_2';

SELECT *
FROM table
WHERE column BETWEEN 1 AND 2;

Strings matching

SELECT name
FROM table
WHERE name LIKE 'je%';

SELECT name
FROM table
WHERE column_1 LIKE 'Ev_';

NULL TREATMENT

Identification

2
SELECT *
FROM table
WHERE column_1 IS NULL;

SELECT COUNT(*) AS nulls_count


FROM table
WHERE column_1 IS NULL;

AGGREGATE FUNCTIONS

Diferent Functions

SELECT MEAN(column_1)
FROM table;

SELECT ROUND(AVG(column_1),2)
FROM table
WHERE year BETWEEN 2010 AND 2020;

ORDERING AND GROUPING

Ordering

SELECT *
FROM table
ORDER BY column_1 ASC, column_2 ASC;

Grouping

SELECT column_1, COUNT(column_2) AS column_count


FROM table
GROUP BY column_1;

FILTERING GROUPS

SELECT column_1, COUNT(column_2)


FROM table
HAVING COUNT(column_2) > 3;

3
Example with all the verbs

SELECT column_1, COUNT(column_2) AS title_count


FROM table
WHERE column_1 IN ('A', 'B', 'C')
GROUP BY column_1
HAVING COUNT(column_2) > 10
ORDER BY title_count DESC;

INNER JOIN

Basic Sintax

SELECT table_1.column_1, table_2.column_2


FROM table_1
INNER JOIN table_2
ON table_1.column_x = table_2.column_2;

Simplified sintaxis

SELECT t1.column_1, t2.column_2


FROM table_1 AS t1
INNER JOIN table_2 AS t2
ON t1.column_x = t2.column_y;

SELECT t1.column_1, t2.column_2


FROM table_1 AS t1
INNER JOIN table_2 AS t2
USING(column_with_the_same_name_in_both_tables)

Multy Join

SELECT
t1.column_1,
t2.column_2,
t3.column_3
FROM table_1 AS t1
INNER JOIN table_2 AS t2
ON t1.column_x = t2.column_y
INNER JOIN table_3 AS t3
USING(column_with the same name);

4
Outer and Full Joins

ACROSS JOIN

Sintax

SELECT column_1, column_2


FROM table_1 AS c1
CROSS JOIN table_2 AS c2
WHERE c1.column_1 = 'A'
AND c2.column_2 = 'B';

SELF JOIN

SELECT
p1.column_1 AS A,
p2.column_1 AS B,
p1.column_2
FROM table_1 AS p1
INNER JOIN table_1 AS p2
ON p1.column_2 = p2.column_2
AND p1.column_1 <> p2.column_1;

You might also like