What order are rows selected from a table?

Question

In the context of this exercise, what order are rows selected from a table?

Answer

In most SQL databases, by default, the rows will be selected in the order that they appear in the table, from top to bottom. For instance, if you have a statement like
SELECT * FROM table this will select all rows from the table from the first row that appears down to the bottom row.

Later on in the other SQL lessons, you will also learn about clauses such as ORDER BY, which allow you to set a certain order for how the rows will be returned in the result set.

20 Likes

In what order do they appear in the table? Is this something that needs to be defined? When new rows are added to the table, are they added to the bottom by default?

2 Likes

As far as I understand, most databases add them as they’re added, Therefore, if you want to add a bunch of rows, order them first.

5 Likes

You are right, I tested it to confirm.
If we would write this:

INSERT INTO celebs (id, name, age)
VALUES 
(1, 'Justin Bieber', 22),
(2, 'Beyonce Knowles', 33),
(3, 'Jeremy Lin', 26),
(4, 'Taylor Swift', 26),
(0, 'James Hetfield', 57),
(5, 'Donald Trump', 74);

SELECT *
FROM celebs;

Then, even though I entered a new entry with an id of 0 and then with an id of 5, the result comes out in the same order I wrote them.

I usually just use:

SELECT *
FROM celebs
ORDER BY id;

To get my results ordered in ascending order, but that is for another lesson.

30 Likes

That’s really useful thank you. I also did;
SELECT * FROM celebs
ORDER BY name;

And it put them in alphabetical order :slight_smile:

2 Likes

Hi @sebastienbaillargeon I tried the code written by you and when I ran it the result set had repeated entries making the total number of rows 10.
I am unable to understand why it would happen.
Could you please help with it?
Thanks

Hey Sebastien, I discovered you can also make the id a PRIMARY KEY and the column would be ordered in descending order 0, 1, 2… and 5.

@sailikulkarni4572335 Hi! It’s because the code uses INSERT INTO statement which adds new rows to the table. This means that if your celebs table was not new and already contained values (which is likely the case after you tried the exercise) it would add those rows in addition to the 4 already existing, making the total 10.

1 Like

great advice, thank you