avatarJosep Ferrer

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

7022

Abstract

v><p id="a3ac">If <code>ASC</code> or <code>DESC</code> is not defined, the sorting order will be ascending by default.</p><div id="33e7"><pre><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> age <span class="hljs-keyword">DESC</span></pre></div><p id="6209">In this case, our output will be sorted from older to younger people.</p><figure id="80ac"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*lxrEqN-cqgtwZZKnBPMMJw.png"><figcaption></figcaption></figure><p id="c78c">You can order by multiple columns as well.</p><div id="0814"><pre><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> eyes_color, age <span class="hljs-keyword">DESC</span></pre></div><p id="a24c">In this second case, we obtain the table ordered by both eye_colors and age. <b>The hierarchy of order will follow the order in which each column appears after the ORDER BY command.</b></p><figure id="ce69"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*Paut0lqqLl6ssmg0WeB8-Q.png"><figcaption></figcaption></figure><h1 id="eb03">#5. Aggregate Functions</h1><p id="5514">Aggregate functions perform calculations on a range of values and return a single value. Some examples of aggregate functions are:</p><ul><li><code>COUNT()</code> returns the total number of rows. <i>Usually used with the </i><code>DISTINCT</code><i> command to count unique elements.</i></li><li><code>SUM()</code> returns the sum of all the values</li><li><code>MAX()</code> returns the maximum value</li><li><code>MIN()</code> returns the minimum value</li><li><code>AVG()</code> returns the average value</li></ul><p id="43e1">Suppose we want to know the number of people in our dataset. In this case, we are just counting all people, without using any group by command.</p><div id="5648"><pre><span class="hljs-keyword">SELECT</span> <span class="hljs-built_in">COUNT</span>() <span class="hljs-keyword">FROM</span> bbdd</pre></div><figure id="8fa1"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*3JjKG00dV02n1fiuVJ70sQ.png"><figcaption></figcaption></figure><p id="df17">Suppose now that we want to know all possible eye colors. In this case, we repeat the previous query only counting the eyes_color column and using the <code>DISTINCT</code> command.</p><div id="287b"><pre><span class="hljs-keyword">SELECT</span> <span class="hljs-built_in">COUNT</span>(<span class="hljs-keyword">DISTINCT</span> eyes_color) <span class="hljs-keyword">FROM</span> bbdd</pre></div><p id="e2cd">The corresponding output would be the following one.</p><figure id="f4f4"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*gUgurQNbLJKgO1MSrHjv8A.png"><figcaption></figcaption></figure><h1 id="f5ac">#6. GROUP BY</h1><p id="b77d"><code>GROUP BY</code> will group data by their identical values. <b>It is frequently used along with aggregate functions to summarise the attribute of a particular column or group of columns.</b></p><p id="7053">Let’s imagine now that we want to know how many people we have for each different eye color. We can repeat the previous logical query but group the result by the eyes_color column.</p><div id="a6a0"><pre><span class="hljs-keyword">SELECT</span> eyes_color, <span class="hljs-built_in">COUNT</span>()

<span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> eyes_color</pre></div><p id="5e42">As we can check, the corresponding output contains what we expected.</p><figure id="a143"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*F_PvGEKFfDOy4JMkERi0pA.png"><figcaption></figcaption></figure><h1 id="717c">#7. UNION</h1><p id="1dde"><code>UNION</code>is a great command, as it allows you to append rows to each other. <b>Unlike joins which append matching columns, </b><code>UNION</code><b> can append unrelated rows provided they have the same number and name of columns.</b></p><p id="6936"><b>You can think of </b><code>UNION</code> <b>as a way of combining the results of two queries. </b>A union will only return results where there is a unique row between the two queries.</p><div id="51c1"><pre><span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">WHERE</span> eyes_color = <span class="hljs-string">"Blue"</span>

<span class="hljs-keyword">UNION</span>

<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">WHERE</span> eyes_color = <span class="hljs-string">"Brown"</span>

<span class="hljs-keyword">UNION</span>

<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> bbdd <span class="hljs-keyword">WHERE</span> eyes_color = <span class="hljs-string">"Green"</span></pre></div><figure id="0168"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*gv20j7szkpYpFt6DFoLMQg.png"><figcaption></figcaption></figure><h1 id="fef9">#8. AS</h1><p id="cef9">The AS command is used to rename a specific column or a specific table during a query. It is a nickname that exists inside the query you are running.</p><ul><li><b>Renaming columns</b></li></ul><p id="9d34">It is as easy as selecting the column and writing the new desired name after the command <code>AS</code> .</p><div id="d43d"><pre><span class="hljs-keyword">SELECT</span> column_1 <span class="hljs-keyword">AS</span> new_name <span class="hljs-keyword">FROM</span> bbdd</pre></div><ul><li><b>Renaming tables</b></li></ul><p id="84bb">In this second case, the command <code>AS</code> is used to assign an alias to the table immediately after it is declared.</p><div id="54d7"><pre>SELECT <span class="hljs-selector-tag">A</span><span class="hljs-selector-class">.age</span> <span class="hljs-selector-tag">FROM</span> bbdd as <span class="hljs-selector-tag">A</span></pre></div><p id="2e9d">You can use any valid name you like, <b>but I strongly recommend to use letters of the alphabet. </b>Before each column name, the alias is prefixed. Rather than typing a long table name, you can type a simple and easy to remember letter.</p><h1 id="36e3">#9. CASE WHEN, ELSE and THEN</h1><p id="5488">If you have used any other programming languages before, this is very similar to an if-else statement.</p><p id="9d3d">Effectively, in plain English, the command sounds a little something like this:</p><ol><li><code>CASE WHEN</code>— If a condition is satisfied.</li><li><code>THEN</code> — Do this.</li><li><code>ELSE</code> — Otherwise do this other thing.</li></ol><p id="786a">Let’s look at an example to solidify this idea. Suppose we want to create a new column that tells us if the person is a teenager, a youngster o

Options

r an adult. We can easily create this segmentation from scratch using a <code>CASE WHEN</code> command.</p><div id="0597"><pre><span class="hljs-keyword">SELECT</span> *, <span class="hljs-keyword">CASE</span> <span class="hljs-keyword">WHEN</span> age < <span class="hljs-number">20</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">"teen"</span> <span class="hljs-keyword">WHEN</span> age >= <span class="hljs-number">20</span> <span class="hljs-keyword">AND</span> age < <span class="hljs-number">30</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">"youngster"</span> <span class="hljs-keyword">ELSE</span> <span class="hljs-keyword">THEN</span> <span class="hljs-string">"adult"</span> <span class="hljs-keyword">END</span> <span class="hljs-keyword">AS</span> <span class="hljs-built_in">type</span> <span class="hljs-keyword">FROM</span> bbdd</pre></div><p id="3ce3">As you can observe, the previous query creates three different conditions:</p><ol><li>If age is smaller than 20, it is a Teen.</li><li>If age is ranged between 20 and 30, it is a Youngster.</li><li>In any other case, it is an adult.</li></ol><p id="0795">The corresponding output contains each person with their corresponding type label.</p><figure id="ec45"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*EEoD2XiUAMfvsITbvkJFDQ.png"><figcaption></figcaption></figure><h1 id="c77c">#10. JOIN</h1><p id="cc08">The <code>JOIN</code> command is the key command to manage data. It allows us to get data from different sources and tables and merge it all together. The three most common Joins are:</p><ul><li><code>INNER JOIN</code>— statement returns only those records or rows that have matching values and is used to retrieve data that appears in both tables.</li></ul><figure id="0826"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*srBHiflDyjR8ozI8z8MDFg.png"><figcaption>Self-made picture.</figcaption></figure><ul><li><code>LEFT JOIN</code> — gives the output of the matching rows between both tables following the structure of the left table. In case no records match from the left table, it shows those records with null values.</li></ul><figure id="ea5a"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*z9E1WOccGvTuMTLn0L7xxQ.png"><figcaption>Self-made picture.</figcaption></figure><ul><li><code>CROSS JOIN</code>— returns all combinations of rows from each table. <i>Note, that this join does not need any condition to join two tables.</i></li></ul><figure id="46c2"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*VtUMFo2dPzVufL2pVVthpg.png"><figcaption>Self-made picture.</figcaption></figure><p id="216d">Let’s imagine now we have an additional table containing the gender of each person. Thus, using a left join, we can merge both tables into a single one connecting by a common column, in this case, by name.</p><div id="30ec"><pre><span class="hljs-keyword">SELECT</span> </pre></div><div id="affc"><pre> <span class="hljs-built_in">T1</span>.name, <span class="hljs-built_in">T1</span>.age, <span class="hljs-built_in">T1</span>.eyes_color, <span class="hljs-built_in">T2</span>.gender</pre></div><div id="c71d"><pre>FROM <span class="hljs-keyword">bbdd </span>AS <span class="hljs-built_in">T1</span> LEFT <span class="hljs-keyword">JOIN </span><span class="hljs-keyword">bbdd_gender </span>AS <span class="hljs-built_in">T2</span> ON <span class="hljs-built_in">T1</span>.name = <span class="hljs-built_in">T2</span>.name</pre></div><p id="6f03">The corresponding output contains all info merged into a single table.</p><figure id="4b84"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*BXSlGFvEf9x1o3H573AA0Q.png"><figcaption></figcaption></figure><p id="f263">Hope you find this story useful to understand the basics of SQL and feel free to ask me any further question! :D</p><p id="7c5e"><b>Data always has a better idea — trust it.</b></p><p id="66db">Don’t forget to follow <a href="https://medium.com/forcodesake"><b>ForCode’Sake</b></a><b> to get more articles like this one! ✨</b></p><figure id="8fbb"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*1sss-BxGrJ2DDwUr1PzcEA.png"><figcaption></figcaption></figure><p id="50e1">Did you like this article? Then you can subscribe to my <a href="https://rfeers.substack.com/"><b>DataBites Newsletter</b></a><b> to stay tuned and receive my content right to your mail!</b></p><p id="6dd9"><i>I promise it will be unique!</i></p><figure id="e171"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/0*vQPtjamSdACqew-r.png"><figcaption></figcaption></figure><p id="2d41">You can also find me on <a href="https://twitter.com/intent/user?screen_name=rfeers"><b>X</b></a>, <a href="https://www.threads.net/@rfeers"><b>Threads</b></a> and <a href="https://www.linkedin.com/in/josep-ferrer-sanchez/"><b>LinkedIn</b></a>, where I post daily cheatsheets about ML, SQL, Python and DataViz.</p><p id="eb66">Some other nice medium related articles you should go check out! :D</p><div id="e532" class="link-block"> <a href="https://betterprogramming.pub/5-sql-tips-to-improve-your-queries-58c0e93ff4ef"> <div> <div> <h2>5 SQL Tips to Improve Your Queries</h2> <div><h3>Subtle changes in your code make all the difference</h3></div> <div><p>betterprogramming.pub</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*EaQRpAo20ZX7ftL0)"></div> </div> </div> </a> </div><div id="a83f" class="link-block"> <a href="https://betterprogramming.pub/how-to-structure-readable-and-reusable-sql-queries-623485ac4a36"> <div> <div> <h2>How To Structure Readable and Reusable SQL Queries</h2> <div><h3>The importance of modularity</h3></div> <div><p>betterprogramming.pub</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*w4VDBeWvtVNwdQ-77fMIBA.png)"></div> </div> </div> </a> </div><div id="5f44" class="link-block"> <a href="https://readmedium.com/from-basic-to-intermediate-sql-in-10-minutes-42b960ed6f9e"> <div> <div> <h2>From Basic to Intermediate SQL in 10 Minutes</h2> <div><h3>A guide for aspiring Data Scientists</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*o0JrsphlUW7yeutR)"></div> </div> </div> </a> </div></article></body>

10 Basic SQL Commands for Every Developer

And how to crush into SQL mastering them.

Self-made image. 10 Basic commands for every developer.

SQL is a very common, yet powerful tool, which can help extract, transform and load data from and into any database.

The very essence of data querying rests on SQL.

As companies and organizations find themselves dealing with rapidly increasing amounts of data, there’s a growing need for developers to effectively use databases to handle this data.

So if you want to crush into the data field, SQL is a must!

To master this language, you need to know how to work your way through some commands — and most of it is based on a few basic ones.

Let’s discover together the most important — and basic — SQL commands! 👇🏻

*For the whole article, I am using a self-created table containing 5 different people with their corresponding ages and eye colors.

#1. SELECT and FROM

TheSELECTcommand in SQL is the simplest, yet one of the most important ones. Every query begins with SELECTand this is how you grab data from your database.

We always need to indicate where to take the data from. And this is exactly where the FROMcommand plays its role, it indicates what is the table source of our query.

The simplest command that can be done in SQL is the following one:

SELECT 
    * 
FROM table

It would be the equivalent of printing “Hello World” to java or python ;)

Now you might be wondering… what’s that asterisk?

If you were so, congrats! That’s an important one. It indicates that you wish to select all the columns from the defined table.

The asterisk is a good way to figure out what data is in a table, but it’s not always recommended for production codes.

That’s why it is better to specify each column to be retrieved like follows.

SELECT 
    name, 
    age,
    eyes_color
FROM bbdd

The resulting table would be:

#2. DISTINCT

DISTINCT is used to view the unique values in a column. The command is used as follows:

SELECT DISTINCT 
    column_1
FROM table

For example, suppose we would like to see all possible eye colors. In this case, we would select all distinct values from the eyes_colors columns contained in our table.

SELECT DISTINCT 
    eyes_colors
FROM bbdd

The resulting output is:

#3. WHERE

Whenever you want to filter the results based on certain criteria, the WHERE command comes in. The use of this SQL command allows you to apply conditions to the SELECT statement.

SELECT 
    *
FROM table 
WHERE column_1 = "Given Condition"

Let’s imagine we only want to know the name of the people that have blue eyes. The required query would be:

SELECT DISTINCT 
    *
FROM bbdd
WHERE eyes_color = "Blue"

This query is now restricted to people who have blue eyes. The corresponding output is:

We can combine multiple conditions with both AND or OR operators.

  • AND works exactly like it does in the English language: it applies another condition to the statement.
SELECT 
    * 
FROM bbdd 
WHERE eyes_color = "Blue"
  AND age        < 20

The corresponding output contains all people with blue eyes and younger than 20.

  • OR works as a multiple condition tester. This means that any row that fulfills any of the conditions will be maintained.
SELECT 
    * 
FROM bbdd 
WHERE eyes_color = "Blue"
   OR eyes_color = "Green"

In this case, the corresponding output contains all people with either blue or green eyes.

#4. ORDER BY

The ORDER BY ommand is used to sort the results in a specific order. You need to specify the column and the order, which can be ASC for ascending or DESC for descending.

SELECT 
    * 
FROM table
ORDER BY column1 ASC/DESC

If ASC or DESC is not defined, the sorting order will be ascending by default.

SELECT 
    * 
FROM bbdd 
ORDER BY age DESC

In this case, our output will be sorted from older to younger people.

You can order by multiple columns as well.

SELECT 
    * 
FROM bbdd 
ORDER BY eyes_color, age DESC

In this second case, we obtain the table ordered by both eye_colors and age. The hierarchy of order will follow the order in which each column appears after the ORDER BY command.

#5. Aggregate Functions

Aggregate functions perform calculations on a range of values and return a single value. Some examples of aggregate functions are:

  • COUNT() returns the total number of rows. Usually used with the DISTINCT command to count unique elements.
  • SUM() returns the sum of all the values
  • MAX() returns the maximum value
  • MIN() returns the minimum value
  • AVG() returns the average value

Suppose we want to know the number of people in our dataset. In this case, we are just counting all people, without using any group by command.

SELECT 
    COUNT(*)
FROM bbdd

Suppose now that we want to know all possible eye colors. In this case, we repeat the previous query only counting the eyes_color column and using the DISTINCT command.

SELECT 
   COUNT(DISTINCT eyes_color)
FROM bbdd

The corresponding output would be the following one.

#6. GROUP BY

GROUP BY will group data by their identical values. It is frequently used along with aggregate functions to summarise the attribute of a particular column or group of columns.

Let’s imagine now that we want to know how many people we have for each different eye color. We can repeat the previous logical query but group the result by the eyes_color column.

SELECT 
            eyes_color,
            COUNT(*)
               
FROM bbdd
GROUP BY eyes_color

As we can check, the corresponding output contains what we expected.

#7. UNION

UNIONis a great command, as it allows you to append rows to each other. Unlike joins which append matching columns, UNION can append unrelated rows provided they have the same number and name of columns.

You can think of UNION as a way of combining the results of two queries. A union will only return results where there is a unique row between the two queries.

SELECT 
    *
FROM bbdd
WHERE eyes_color = "Blue"
        
UNION
        
SELECT 
    *
FROM bbdd
WHERE eyes_color = "Brown"
        
UNION
        
SELECT 
    *
FROM bbdd
WHERE eyes_color = "Green"

#8. AS

The AS command is used to rename a specific column or a specific table during a query. It is a nickname that exists inside the query you are running.

  • Renaming columns

It is as easy as selecting the column and writing the new desired name after the command AS .

SELECT 
     column_1 AS new_name
FROM bbdd
  • Renaming tables

In this second case, the command AS is used to assign an alias to the table immediately after it is declared.

SELECT 
     A.age 
FROM bbdd as A

You can use any valid name you like, but I strongly recommend to use letters of the alphabet. Before each column name, the alias is prefixed. Rather than typing a long table name, you can type a simple and easy to remember letter.

#9. CASE WHEN, ELSE and THEN

If you have used any other programming languages before, this is very similar to an if-else statement.

Effectively, in plain English, the command sounds a little something like this:

  1. CASE WHEN— If a condition is satisfied.
  2. THEN — Do this.
  3. ELSE — Otherwise do this other thing.

Let’s look at an example to solidify this idea. Suppose we want to create a new column that tells us if the person is a teenager, a youngster or an adult. We can easily create this segmentation from scratch using a CASE WHEN command.

SELECT 
    *,
    CASE WHEN age <  20               THEN "teen"
         WHEN age >= 20 AND  age < 30 THEN "youngster"
         ELSE                         THEN "adult"
    END AS type
FROM bbdd

As you can observe, the previous query creates three different conditions:

  1. If age is smaller than 20, it is a Teen.
  2. If age is ranged between 20 and 30, it is a Youngster.
  3. In any other case, it is an adult.

The corresponding output contains each person with their corresponding type label.

#10. JOIN

The JOIN command is the key command to manage data. It allows us to get data from different sources and tables and merge it all together. The three most common Joins are:

  • INNER JOIN— statement returns only those records or rows that have matching values and is used to retrieve data that appears in both tables.
Self-made picture.
  • LEFT JOIN — gives the output of the matching rows between both tables following the structure of the left table. In case no records match from the left table, it shows those records with null values.
Self-made picture.
  • CROSS JOIN— returns all combinations of rows from each table. Note, that this join does not need any condition to join two tables.
Self-made picture.

Let’s imagine now we have an additional table containing the gender of each person. Thus, using a left join, we can merge both tables into a single one connecting by a common column, in this case, by name.

SELECT 
    T1.name,
    T1.age,
    T1.eyes_color,
    T2.gender
FROM bbdd AS T1
LEFT JOIN bbdd_gender AS T2
  ON T1.name = T2.name

The corresponding output contains all info merged into a single table.

Hope you find this story useful to understand the basics of SQL and feel free to ask me any further question! :D

Data always has a better idea — trust it.

Don’t forget to follow ForCode’Sake to get more articles like this one! ✨

Did you like this article? Then you can subscribe to my DataBites Newsletter to stay tuned and receive my content right to your mail!

I promise it will be unique!

You can also find me on X, Threads and LinkedIn, where I post daily cheatsheets about ML, SQL, Python and DataViz.

Some other nice medium related articles you should go check out! :D

Programming
Data Science
Sql
Python
Software Development
Recommended from ReadMedium