My First SELECT Statement
Microsoft SQL Server makes it really easy for us to query tables. In SQL Server Management Studio (SSMS) for instance, we can right-click on any table we have access to and select the top 1000 rows from that table.
Please don’t query tables this way in a production environment. It’s a bad way to do it, and you should feel bad.
Let’s assume we want to get a list of the stores in our database that we created in the First Look at Normalization post.
The table had the following columns:
To get a list of all rows and all columns in a table, we write the following statement:
Remember from previous posts that the square brackets are a matter of style, and we could just as easily exclude them.
I leave them in because humans are terrible at naming things, and the square brackets make the code less likely to fail.
You’ll notice that there is a semi-colon at the end of the statement. We could have placed the entire statement on one line, like so:
SELECT [StoreID], [StoreCode], [StoreName], [Address], [ManagerName], [ManagerEmail] FROM [dbo].[Stores];
This is more difficult to read. SQL Server doesn’t really care about white space, including carriage returns, so feel free to format your code nicely so that it’s easy for you to read.
If you’re typing this in Management Studio, you can now press the Execute button in the menu, or the F5 key on the keyboard, to run the command.
Tip: in Management Studio, we can select just the text (T-SQL code) we want to run, using the mouse, and then press F5. This will guarantee that no other part of the script will run as well. It’s a useful way to run portions of code in a longer script.
Once we run the
SELECT statement, we see a result set.
Congratulations! We have asked SQL Server for data, and it has responded with the data we asked for.
Next time, we will be adding data to a table using the
INSERT command. Stay tuned.
Look me up on Twitter if you want to ask any questions about this series, on @bornsql.