Day 2/100: Getting started with T-SQL
In this blog post, I will show you some more queries that you can use with the SELECT statement to filter, sort, group, and limit your data.
Before we start, make sure you have installed SQL Server and Azure Data Studio as explained on day 1. Also, make sure you have created a database and a table with some sample data as shown below:
-- Create a database named TSQLTutoria
CREATE DATABASE TSQLTutorial;
GO
-- Use the database
USE TSQLTutorial;
GO
-- Create a table named Products with four columns: Id,
-- Name, Price and Category
CREATE TABLE Products (
Id INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Price DECIMAL(18,2) NOT NULL,
Category VARCHAR(20) NOT NULL
);
GO
-- Insert some sample data into the table
INSERT INTO Products (Id, Name, Price, Category)
VALUES
(1, 'Laptop', 999.99, 'Electronics'),
(2, 'Mouse', 19.99, 'Electronics'),
(3, 'Keyboard', 29.99 , 'Electronics'),
(4 , 'Book', 9.99 , 'Books'),
(5 , 'Pen', 0.99 , 'Stationery'),
(6 , 'Notebook', 4.99 , 'Stationery');
GO
Now that we have some data to work with, let’s see how we can use different clauses and keywords with the SELECT statement to query our data.
WHERE clause
The WHERE clause allows you to filter the rows that match a certain condition. For example, if you want to see only the products that belong to the category of Electronics, you can use this query:
-- Select all columns from Products where Category is Electronics
SELECT *
FROM Products
WHERE Category = 'Electronics';
The result will be:
You can use various operators and logical expressions in the WHERE clause to create more complex conditions. For example:
-- Select all columns from Products where Price is less than
-- or equal to $10 or Category is Stationery
SELECT *
FROM Products
WHERE Price <=10 OR Category = 'Stationery';
The result will be:
ORDER BY clause
The ORDER BY clause allows you to sort the rows by one or more columns in ascending or descending order. For example,
-- Select all columns from Products ordered by Price in
-- ascending order
SELECT * FROM Products ORDER BY Price ASC;
The result will be:
Conclusion
In this blog post, we learned how to use some more queries with the SELECT statement to filter, sort, group, and limit our data in T-SQL. We saw how to use the WHERE clause to apply conditions on the rows, and the ORDER BY clause to sort the rows by one or more columns.
I hope you found this blog post useful and informative. If you have any questions or feedback, please leave a comment below. In the next blog post, we will learn how to join two or more tables in T-SQL using different types of joins. Stay tuned!