SQL basics
Practical SQL basics on a sample database – selecting and filtering data, sorting, changing data, joining tables, totals, data types and indexes. All examples are verified in MySQL and MariaDB.
The best way to learn SQL is to try it yourself. Create a small sample online shop database, which all articles in this series are based on, and write your first SELECT queries.
The WHERE clause selects only the rows that meet a condition. Comparing numbers and text, combining conditions with AND and OR, ranges, searching for part of a text and working with the missing value NULL – including the most common mistakes.
Without ORDER BY, the result of a query has no guaranteed order. How to sort by one or more columns, how accented text and missing values are sorted, how to select the first few rows and how to paginate a list in PHP.
The INSERT, UPDATE and DELETE statements change the data in tables. How to write them, how to find the number of a newly inserted row and above all how to protect yourself from the worst mistake – changing or deleting all rows at once.
Data is usually split into several tables – an order contains only the number of the customer, the name is in another table. How to join tables with JOIN, what the difference between INNER and LEFT JOIN is and how to find records without a match.
How many customers are there in each city, how much has each customer spent, which product sells best? The aggregate functions COUNT, SUM, AVG, MIN and MAX, grouping with GROUP BY and filtering groups with HAVING.
A well-chosen data type saves space, speeds up queries and protects the data from nonsense. Which types to use for numbers, prices, text and dates, why prices do not belong in FLOAT and why utf8mb4 is used.
An index is to a database what an index is to a book – instead of reading the whole table, the database finds the rows it needs straight away. When an index helps, how to create it, how to check its use with EXPLAIN and why it makes no sense to index everything.