By far the best way to learn the SQL language is to actually write SQL queries on your own. If you already have a SQL editor and a database that you’re using, then great – let’s move on. If you aren’t already using a SQL editor then I’d recommend trying out DBeaver for a free open source SQL editor/client. After installation, there’s an option to add a sample database. Click “yes” if you want to follow along and write your own queries as we’ll be using this database for various SQL examples throughout each section.
For a general overview of SQL check out these articles first:
The DBeaver sample database will appear in the database navigator section on the left side window with a list of tables that we can use as examples to write our own SQL queries.
Let’s Begin!
We commonly hear a SQL statement also referred to as a query or a SQL script – but in the end it’s all the same so you may see these terms used inter-changeably throughout the sections.
Note: If you’re using the sample database with DBeaver, make sure that you are connected and start a new script so that you can write your own queries.
A SQL SELECT clause is required in all queries that ask the database a question with an expected result. Some databases allow us to write only a SELECT statement without the requirement of a FROM clause. This is because databases can have their own built-in functions that can be used without specifically pulling data from a database object such as a view or table. This isn’t super important, but something worth noting.
See the following example:
And the result:
Minimum Requirements Of A Valid SQL Query
Although some databases may let us get away with not having a FROM clause – most won’t – and getting away without the clause requires using built in system functions.
The FROM clause is used to specify the table(s) that we’re trying to SELECT from. Remember, a SQL SELECT will tell us what we’re returning and FROM will tell us where the data comes from.
All SQL statements should end in a semi-colon, but this is not a requirement. For best practice and sanity, you should probably make it a habit to include the semi-colon at the end of your SQL statements. If you don’t and have multiple statements in an editor then you will need to highlight the exact text of your SQL query in order for it to run correctly. Some databases use alternate syntax, but we won’t get into that since we’re trying to follow the ANSI SQL standard.
Don’t Forget To ‘SELECT’ Everything!
Last, but not least in this section – the famous asterisk symbol * (aka “star” or “all”). This character is used to return ALL columns from a table. Whether we’re selecting from a single table or multiple tables, the star character will return all columns/fields from all tables included in a SQL statement.
Returns all fields and values (columns and rows):
That’s it! Now you know how to write a basic SQL SELECT query!