SQL Beginner's Tutorial: Sorting Groupies


Groupies Unite!


Preface: My SQL Server Management Studio took a nosedive, so I will not be including image-based examples from SSMS in the Tutorials until I resolve the issue... but alas, the show must go on.


Hey Everyone,

It's that time again!! I think Mabel (from Cartoon Network's Gravity Falls) has hit the nail on the head! There you see her sorting her fellow groupies and doing a FABULOUS job of it. Poor boys in the corner were segregated out of her group though... maybe next time.

So today's lessons are going to be about grouping and sorting results. This basically means that I'm going to teach you how to query for data that returns in such a way as to be grouped together based on one or more specific fields. Additionally, you're going to learn how to sort the data forwards and backwards by one or more fields. You'll become the Master of the Sorting Hat!!


The Sorting Hat from Harry Potter


Apples & Bananas

Grouping data is like bagging up apples and bananas, each segregated to its own fruit... yeah, it's a Fruitist Mentality that needs to be abolished! So I just ate them all anyway!!


What I Ate

In the great big world of Databases and Queries, one of the most useful tools is the GROUP BY clause. This SQL clause allows the returning dataset (this is another word for the query results that are returned to you after the query has completed) to be grouped by specific fields so that you can separate the data items accordingly and create more efficient analytical reports (and other things as well).

Above you can see the following 2 different queries:

SELECT * FROM BackPack
GROUP BY color, id, backpack_id,length, width, height, weight, strap_length

SELECT * FROM BackPack
GROUP BY backpack_id, color, id, length, width, height, weight, strap_length

If you look at the 2 Result Sets in the above image, you will see that they return rows in a different order. This is due to the GROUP BY clause that was included in the queries. The first query does a GROUP BY against the color field and then the id field before it looks at the backpack_id field. This means that the results are going to be lumped together in that order. The second query starts by using the GROUP BY against the backpack_id field right from the start.

To put this clause in simple terms, it lumps together same-value fields based on the order of the GROUP BY fields listed. So you see in the second Result Set, in the above image, that there are 2 rows with a backpack_id value of 10101 and so these 2 are lumped together. Since there are so few field-value pairs (values in the same field) that are equal, the GROUP BY clause does little more if other fields are selected first.

This clause is very important in programming, reporting, analytics, and just for aesthetic appeal since it makes like-like values rest next to one-another. The next thing you need to do is to sort them out. So if you had a Table (remember, this is where all the data rests, like a spreadsheet with rows and columns) called CartoonNetworkGroupies and you wanted to separate them by Gender (assuming these 5 fields in the Table: first_name, last_name, cartoon_name, character_gender, cartoon_mood) you could use the following query to do so:

SELECT first_name, last_name, cartoon_name, character_gender, character_mood
FROM CartoonNetworkGroupies
GROUP BY character_gender, first_name, last_name, cartoon_name, character_mood

... or if you wanted to lump them together by the cartoon that they're in:

SELECT first_name, last_name, cartoon_name, character_gender, character_mood
FROM CartoonNetworkGroupies
GROUP BY cartoon_name, first_name, last_name, character_gender, character_mood

...and if you wanted to lump them into groups contained by gender then by cartoon:

SELECT first_name, last_name, cartoon_name, character_gender, character_mood
FROM CartoonNetworkGroupies
GROUP BY character_gender, cartoon_name, first_name, last_name, character_mood

Note: In SQL Server you must use the entire list that you have in the SELECT clause in the GROUP BY clause, otherwise it throws errors... this does not apply to aggregates (SUM, COUNT, MAX, MIN, etc. which we will go over later in the series).


ORDER in the Court!

Now that you have all those characters lumped into groups, you might as well sort them out so you know which is most important to your needs. This is one of the clauses that will help in readability of your results more than anything else (my personal opinion). The ORDER BY clause allows you to identify which field to sort by, either using ASC for Ascending or DESC for Descending.

In the above image, you can see the 2 queries from above as well as a 3rd one that was added. This 3rd query adds on an ORDER BY clause that says this:

ORDER BY color desc

side-note: the desc should have been uppercase as a best-practice, but even I don't remember to do so all the time

The above basically tells us "Ok, now that we have those results, lets sort them in reverse order from biggest to smallest." In this case, since the field uses aphabetic characters, it returns values from Z-A... this is why the first color field value in the 3rd Result Set above shows "white".

You can leave off the ASC or DESC modifier without consequence. If you do leave it off, it will assume and Ascending sort order. This can, of course, get tricky if you need to group and sort by multiple columns in strange ways, so watch how your lists read.

As a last note, you will notice that I didn't include the full list of fields in the ORDER BY clause... you don't need to.



Our Fruit says Thank You!

So there you have it, a solid start to sorting things out in SQL. With this knowledge, you should now be able to make some pretty decent queries and practice up on how things show up and return. Going forward I plan on introducing the use of _DISTINCT, UNION, ISNULL(), TOP, LIKE, BETWEEN', aggregate functions, wildcards, and aliases.

Please feel free to return to prior Posts in this series (listed below) to refresh yourself on the fundamentals:

SQL Beginner's Tutorial: Relational Databases & SQL

SQL Beginner's Tutorial: Writing your First Queries

SQL Beginner's Tutorial: SELECT Data to Use in the Game

SQL Beginner's Tutorial: Manipulate Data for Use in the Game

SQL Beginner's Tutorial: JOIN Me and Together We Will Rule the Universe

SQL Beginner's Tutorial: What if the World IS NOT NULL? and IN the Galaxy?

Sort:  

Just wondering, is it hard to query data and information from 2 different tables and computers ???

I believe you can do this with a linked server connection in SQL Server Management Studio.

I use a Linked server connection to pull from SteemSQL and insert a selection of data via a cursor into my local database.

Cheers :)

How'd yo do that Sir ?

Your question is a bit vague :)

google: Linkedserver, MSSQL

Ok Sir thank you :)

I'll discuss my findings when I discover it :)

That would be great. That's probably a bit advanced for my Tutorial series, but if I continue on to an Intermediate and/or Advanced Series for SQL, then I will try to fit it in.

Actually in the moment I have study linking two databases from two different computers, Ill just need to apply all I learn. I'am now finding an extra laptop to test it :)

I'll update you when I finish it :)

I am quite interested in this information. Thanks!

You can query from 2 different tables (and 2 different Databases at that) but I'm not sure the extent to that. I am not so sure about whether you could query data from 2 different computers at the same time. Now, I often query multiple tables, databases, and servers within my integration code; however, each different server has a different connection.

That's really the workaround is that, in your code, you could query the foundation table, store it as a DataSet, and then query the other server based on values within that DataSet. I've done that before, although it does tend to balloon the code by doing so.

Is that what you were wondering?

Yes, thank you for the response :)

its just that I'm planning to develop a system where client computers can store files into the server computer (2 or more computers connected to a single server). So i'm wondering about that

If it's a single server-based system, I believe you should be able to do so. If you're working direct with files as the data storage tool, then you could create a Network Share Folder that is accessible by the multiple computers involved and that should be enough to do so. You would just have to watch out, in that case, for File Locking.

Yes file security is my main problem with that, I want the system to give the server user the power or to enable and disable access whenever he/she wants. I want to make the system user-friendly to non-IT users.
image.png
I want it to be like a switch that give access or permission in just a single click.

Automation and ease-of-use is where it's at in regards to integration and development of solutions. It's actually something I try to highlight with the Clients I work with.

Yes, I want the software application to be fully automatic so that users will not lost inside the system. I have encountered using system that are not user-friendly and it really give me hard time using it

I completely agree. The harder the application is to use, the less I want to use it.

@dbzfan4awhile i had many doubts in sql and database and you have really cleared many of them. Wish you should have been my college sir and then i would have surely topped in dbms

Sometimes it just takes a certain type of person to be able to explain the nature of certain things in an understandable way. I have trouble understanding textbook stuff and I was just trying to explain it in an easier way. I'm glad it could help you with your own learning.

Yaa @dbzfan4awhile YouTube is the best platform to learn and clear the concept but after seeing your post i think steemit will surely overtake..... Bro how can i contact you personally on fb or any other social network??

I'm on the PAL/MSP Discord Server if you really need to contact me, or you can comment on my Posts and I will attempt to respond to as many as I am able to do so.

amazing post love to see some intelligent post on steemit.

Glad I could be of service. I also have art and writing and poetry as well Posted on Steemit.

i would love to see ur other post and it will be great like this post!

Feel free to go through all my older Posts if you want to do so. I hope you find enjoyment and fulfillment.

yes sir sure i have start following u the reason behind is ur awsome and mature nature the way u talk i s awsome and yes i have start watching ur post and i must stay bless stay happy!

as I love data analysis and I dont know sql, this is an awesome post. thank you for putting it together

So glad to see you enjoying my SQL Tutorials! I haven't read too many of your posts (mainly because reading lengthy posts tires my eyes), but I love the great content that you provide. If my Tutorial series helps you in your analyses, then it feels really good to provide this to you. You've done really good things on Steemit.

And if you need to learn the basics, I have a list of those earlier Tutorial Posts at the end.

yes I have bookmarked this post cos I seen the list at the end, you rock, keep it up

I plan to do so. Indeed, if you have interest in Programming, I also have a C# Programming Tutorial series as well. Not sure if that would be up your alley or not, unless you're considering making some sort of application for your analytics.

Really great And valuable information thank u for posting this valuable information with us. keep sharing buddy

I have no plans on stopping.

That's great i followed u to see ur more new stuff .

Thanks! I'll try to continue Posting quality content.

Funny. My SSMS took a nose dive the other day too. Perhaps they're all planning a revolt.

Mine then suddenly started working again this morning after my system did a reboot.

Lucky! Not so much for me. Ended up doing a reinstall. TYVM MSFT.

This has happened like 3 times for me. This time was the only time I didn't need a reinstall. I feel for you.

Besides a case of bad luck, do you have any idea what might causes this to happen? Definitely not my first time either.

I don’t, unfortunately. You might be able to see something in Event Viewer through the Control Panel.

i think this is amazing one of my friend told me about this he send me the link and he said this is an amaing post so i came to chack it up this is really so amazing i liked the ppost and followed you too couse i expect more good and quality contant ..

I certainly hope that I keep providing quality content. Please feel free to read my older Posts. And thank you so much!

yeah thanks for replying me back .. i really liked that and yeah i will read your older post after few minutes .. and i will post a review in the comment section for each post ... but i know i will not regret reading and watching this ....

Sounds like a plan.

hah yeah ... let me tell you something you are a nice erson with big heart be like that .. and what i have said i mean it

we missed you so much

Well, I Post 2 Tutorials per week. One Tutorial Post is this Tutorial Series and the other is my C# Programming Tutorial.

the lessons you gave before that were useful . will certainly be useful in this lesson

I am sure that you will be able to drag out some helpful tips and hints.

nice tutorial

Thank you very much.

Coin Marketplace

STEEM 0.30
TRX 0.11
JST 0.033
BTC 64320.07
ETH 3154.23
USDT 1.00
SBD 4.34