Adding Custom Row and Cell Names in SQL
This guide explains how to integrate custom row and cell names in a SQL query to explicitly label data.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So far in the section, we've spoken quite a bit about functions in SQL. We've been able to cover things such as being able to summarize data, use calculated fields, and to randomize data to populate a database.

One thing that we haven't talked about is how to present the data in a report format. So for example, if I were to run a select statement on the user database here and run this query.

SELECT *
FROM users;

picture

You can see that it brings up all 2000 plus users and if you scroll all the way down. You can see that right here there's not really a lot of hints on which each one of these fields represents. MySQL Workbench does a very nice job where it keeps your column names up here, but other services such as Excel don't do that by default.

Many times you want to customize your data to be outputted into a format that you can hand straight off to whoever you're generating the report for. That is where you can use name rows, and that's what we're going to walk through in this guide.

Right now we have select, but I'm going to change this up a little bit because I want to customize our report. Now if you put quotation marks just like this you can create fields that don't perform any type of database query. What this is going to do is it's actually going to represent itself inside of the database query result.

I can say "Email:" users_email and then "Name:" then users_name from users, so nothing else has to change.

SELECT 'Email:', users_email, 'Name:', users_name
FROM users;

picture

Now if I run this query you can see we have a very different resultset now.

picture

Now we have a column called "email;" and then the e-mail, then a name, and then each one of the "users_names." This is something where if you simply exported this and dropped it into Excel or a CSV file. You now would have the column names right next to the value.

That can be incredibly helpful whenever you're building reports. Since functions are closely aligned with being able to summarize and build reports to that, you would give to a CEO, CFO, or someone like that. That is something that SQL developers are called on to do quite often.

If you don't have to do some things such as run a script to put the word email in the word name right in front of a column in like Excel it just saves you time. It also shows that you're very proficient in using the tool. So that is how you can add named rows inside of sequel.

Code

USE devcamp_sql_course_schema;

SELECT 'Email:', users_email, 'Name:', users_name
FROM users;