SQL and MySQL course Β· Module 1: Introduction to databases

Your first spell: SELECT

2 min read Β·
In this lesson3

Time to give the Library its first order! The most important command in SQL is SELECT - "show me the data".

All columns: SELECT *

The asterisk * means "all columns":

SELECT * FROM ksiazki;

This means: "Show all fields of all books on the ksiazki shelf". The Library will return the entire contents of the shelf.

Selected columns

Usually we don't need everything. We can ask only for specific fields, listing them separated by commas:

SELECT tytul, autor_id FROM ksiazki;

This means: "Show only the title and the autor_id (the cross-reference to the author) of each book". The rest of the fields will be omitted. In the ksiazki shelf we store the author as the autor_id column - a cross-reference to the authors shelf.

What does a SELECT query consist of?

Let us take the query apart. A comment after -- describes each line - the Library skips it, and it tells you what that part does:

SELECT tytul, rok_wydania   -- WHICH columns you want to see
FROM ksiazki;               -- FROM WHICH shelf (table)
  • SELECT - the list of columns you want to receive (or * for all).
  • FROM - the name of the table you are reading from.

Remember: when you read data from a shelf, SELECT goes hand in hand with FROM. Without naming the shelf the Library does not know where to look!

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What will the query return: SELECT * FROM ksiazki;

  2. 2. What does the asterisk * mean in the query "SELECT * FROM ksiazki;"?

  3. 3. How do you retrieve only chosen columns instead of all of them?

  4. 4. What is the FROM keyword used for in a SELECT query?

Hands-on tasks in the game

  • Code editor

    Write a query that retrieves ALL columns and all rows from the ksiazki table. Remember the semicolon at the end.

  • Code editor

    Write a query that retrieves from the ksiazki table only two columns: tytul and autor_id.

  • Horizontal ordering

    Arrange on one line a query that retrieves all columns from the autorzy table:

  • Code editor

    Write a query that retrieves all columns and all rows from the autorzy table.

Useful articles