SQL (Structured Query Language) Basic Commands
In order to use SQL-based databases, one needs to become familiar with SQL clauses, keywords and queries. In this post we are going through some of the most basic SQL clauses and keywords using simple examples.
SQL Comments:
You can write comments in SQL files in two ways:
1. Single-Line comment:
You can create a single-line comment using two dashes:
2. Block comment:
You can create a block comment starting with /* and ending with */. This is especially helpful when you want to create a comment which has more than one line. for example, it is a good practice to write a block comment at the beginning of your SQL file and specify the file's creator, date of creation and description.
SELECT:
Use SELECT clause to columns you want to appear in the result table.
Alias:
To make your results more readable for yourself and others you can change the way columns' names are displayed in the result. For this purpose, you should use AS keyword, as shown in the following example:
As can be seen in the above example, for using an alias including more than one word we should put that multi-word alias between [ ] or ' '. However, we can bring a single-word alias immediately after AS without using any other special characters.
Sorting with ORDER BY:
We can sort results of our queries based on column contents. In order to do that, we use ORDER BY clause after FROM clause. Hint the following example which sorts the result table based on the contents of the LastName column.
The default mode of ORDER BY clause is ascending order. However, you can change it. You can use ASC for ascending or DESC for descending order. Use either of these two keywords after the column name stated in the ORDER BY clause. For example, to sort the result table based on LasrName descending order we should use the following query:
We can sort the results based on multiple columns. For example:
LIMIT:
You can limit the number of records shown in the result table using LIMIT Clause. In order to do that, you have to use "LIMIT number-of-rows" in your query. For example:
In the above example, number of rows in the result tables is limited to 10. Therefore, the result table will contain the information of the top 10 customers sorted with the specified order in the query.
P.S. The cover image is generated by DALL-E.
Subscribe to my newsletter
Read articles from Negar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by