Software & Web Engineering

What Is SQL? How to Ask a Database a Question

Phòng lưu trữ với dãy ngăn kéo gỗ có nhãn dưới ánh đèn bàn vàng ấm
In this article

    Suppose you sell coffee online. At the end of the month, you want to know which product sold best, which customer bought the most, and how much money came in. The data is already in your website’s orders table. The problem is getting it out without scrolling through thousands of rows by hand.

    The answer is one SQL statement. SQL is the language for asking a database questions, and the question “which product sold best” written in SQL is a single line. This article explains what SQL is, how a query runs from start to finish, and a common security mistake when using SQL.

    Learning SQL is not about memorizing dozens of commands. The skill is asking the right question: which columns, from which table, filtered to which rows, in what order. Once you can do that, the rest is looking things up.

    Quick summary

    • SQL (Structured Query Language) is the language for asking and managing data in a relational database. Data lives in tables made of rows and columns.
    • The first query to learn is SELECT: it says which columns, from which table, filtered to which rows, in what order. SQL says what data to get, not how to get it, because the query processor picks the fastest way itself.
    • SQL is a language under an international standard, while MySQL and PostgreSQL are database programs that use SQL. Each program has its own dialect, so code rarely moves between systems untouched.
    • A dangerous mistake with SQL is SQL injection: building a query by joining user input straight into the statement. The fix is parameterized queries, never string concatenation.
    Quiet archive room with rows of labelled wooden drawers under a warm desk lamp
    Quiet archive room with rows of labelled wooden drawers under a warm desk lamp

    What is SQL?

    SQL, short for Structured Query Language, is a language for querying structured data. According to Amazon Web Services, SQL is a programming language for storing and processing information in a relational database, and you can use SQL statements to store, update, remove, search for, and retrieve information from the database.

    A relational database stores data as tables. Each table has rows and columns: one row is one record, such as one order, and one column is one attribute of that record, such as the customer name or the unit price. Tables relate to each other through shared columns, such as a customer ID appearing in both the customers table and the orders table.

    SQL was born in the 1970s. Two IBM researchers, Donald D. Chamberlin and Raymond F. Boyce, developed it for IBM’s System R database, first under the name SEQUEL. That name ran into a registered trademark, so they shortened it to SQL. The American National Standards Institute (ANSI) standardized SQL in 1986, the International Organization for Standardization (ISO) adopted it in 1987, and the latest version of the standard is SQL:2023.

    On a website, SQL usually sits behind an API. When you open a product list page, the browser calls the API, the API asks the database with SQL, and the result comes back to the page. What an API is and how it works explained the first half of that chain; this article explains the second half.

    How data sits in a table

    Take a small coffee shop as the running example for this article. Its orders table holds 5 orders, shown below. This is made-up data for illustration, not real orders.

    Order IDCustomerProductQuantityUnit priceOrder date
    1LanArabica coffee 250g2120,00028 Nov 2026
    2MinhRobusta coffee 500g1150,00029 Nov 2026
    3LanAluminium phin filter185,00030 Nov 2026
    4HoaArabica coffee 250g3120,0001 Dec 2026
    5MinhArabica coffee 250g1120,0002 Dec 2026

    Reading this table tells you a few things at once. The order ID never repeats: each order has its own ID, and a column like that is called a primary key. Customer names can repeat, because one customer buys more than once. Prices are numbers, dates are dates, and each column holds one kind of data.

    One table holds one kind of information. Orders live in the orders table, customer details in the customers table, products in the products table. Splitting it up like this means changing the price of one product takes one edit, instead of one edit in every order ever sold.

    Your first SQL query

    The shop owner’s first question is: which product sold best? In SQL, that question looks like this:

    SELECT product, SUM(quantity) AS total_sold FROM orders GROUP BY product ORDER BY total_sold DESC;

    Reading the statement left to right, each clause answers one part:

    • SELECT product, SUM(quantity) says which columns to get: the product name and the total quantity sold, shown under the name total_sold.
    • FROM orders says which table to get them from: the orders table.
    • GROUP BY product says to bunch rows with the same product together before adding.
    • ORDER BY total_sold DESC says to sort the result by total sold, highest first.

    Running this query on the example data above gives exactly the table below. I ran it with sqlite3, a database tool that ships with many computers, and the result matches adding the numbers by hand.

    producttotal_sold
    Arabica coffee 250g6
    Robusta coffee 500g1
    Aluminium phin filter1

    Second and third questions

    The second question: how much money came in this month? Revenue is the sum of quantity times unit price across every order:

    SELECT SUM(quantity * unit_price) AS revenue FROM orders;

    The result is 955,000 VND. Checking by hand: Lan bought 2 packs of Arabica for 240,000, Minh bought Robusta for 150,000, Lan bought a phin filter for 85,000, Hoa bought 3 packs of Arabica for 360,000, and Minh bought 1 pack of Arabica for 120,000. Added up, that is exactly 955,000 VND.

    The third question: which orders were over 100,000 VND? Add a WHERE clause to filter rows before returning them:

    SELECT customer, product, unit_price FROM orders WHERE unit_price > 100000 ORDER BY unit_price DESC;

    The result has 4 rows: Minh’s Robusta at 150,000 VND, then three Arabica orders at 120,000 VND from Lan, Hoa, and Minh. The phin filter order at 85,000 VND is filtered out because it does not meet the condition.

    These three queries show one way SQL differs from a general-purpose programming language: SQL is a declarative language. The statement says what data to get, and the database’s query processor works out how to get it. According to Amazon Web Services, the query processor builds a plan to retrieve data in the most efficient way, reusing an old approach or creating a new one. The writer does not need to know where the data sits on disk or which index exists, only how to ask correctly.

    Diagram from a question to a SQL statement, then to the database and a result table
    Diagram from a question to a SQL statement, then to the database and a result table

    The five groups of SQL commands

    SELECT is the command you will use most often, but SQL has four other groups. The table below puts all five in one place, following Amazon Web Services’ classification.

    GroupWhat it doesCommon commands
    DQL, data query languageReads data outSELECT
    DDL, data definition languageCreates and changes table structureCREATE TABLE, ALTER TABLE, DROP TABLE
    DML, data manipulation languageAdds, changes, and deletes recordsINSERT, UPDATE, DELETE
    DCL, data control languageGrants and revokes accessGRANT, REVOKE
    TCL, transaction control languageConfirms or rolls back a batch of changesCOMMIT, ROLLBACK

    A beginner only needs to master SELECT first. Reading data is the daily job: checking orders, totaling revenue, finding customers. Writing data with INSERT and UPDATE needs more care, because an UPDATE without a WHERE clause can change the whole table by mistake. GRANT permissions and COMMIT and ROLLBACK transactions are usually the database administrator’s job, not a beginner’s.

    How is SQL different from MySQL and PostgreSQL?

    This is a pair of ideas that often gets mixed up when learning. SQL is a language under the international standard ISO/IEC 9075. MySQL, PostgreSQL, SQL Server, and Oracle Database are relational database programs: real software running on a server that understands SQL statements.

    MySQL is an open-source relational database management system provided by Oracle, widely used for web applications. PostgreSQL is another open-source choice, known for sticking closely to the standard. Each program has its own dialect: date and time syntax, how empty NULL values are handled, and case sensitivity all differ a little, so SQL code rarely moves from one system to another without any changes.

    That is why “learning MySQL” in practice usually means learning SQL on MySQL. Once you know it, you can carry SELECT, WHERE, and GROUP BY over to PostgreSQL almost unchanged, looking up only a few details of syntax that belong to each system.

    When to use SQL, and when not to

    SQL fits data with a clear structure and clear relationships between tables: orders tied to customers, products tied to categories, articles tied to authors. A relational database keeps things consistent: with a foreign key constraint, an order cannot point to a customer who does not exist.

    NoSQL, or non-relational, databases fit data that does not fit in tables: documents, graphs, key-value pairs. According to Amazon Web Services, NoSQL is popular with modern applications because it scales horizontally, meaning it gains capacity by adding more machines running NoSQL software.

    Picking the wrong model is not a disaster, and many systems today support both kinds of storage, but changing data models halfway through costs far more than picking the right one at the start. For a shop website, a blog, or an ordinary management application, relational tables and SQL are still the sensible default.

    SQL injection: one wrong join can open the database

    This is a security mistake that working programmers run into in real life, and understanding it shows why how you write a query matters.

    SQL injection happens when an application joins user input straight into a SQL statement. According to OWASP, an attacker inserts a SQL query through input data from the client, and a successful exploit can read sensitive data, modify or delete data, and even take over as database administrator.

    Take a product search box that joins the keyword straight into the statement, as below. This is code that shows the mistake; do not use it in a real product:

    SELECT * FROM products WHERE name = 'keyword';

    If an attacker types ' OR 'a'='a into the search box, the statement becomes WHERE name = '' OR 'a'='a', and the condition 'a'='a' is always true, so the database returns the whole table. With a nastier string, an attacker can delete data or read the users and passwords table.

    The fix, according to OWASP, is parameterized queries (also called prepared statements). The statement and the data travel separately: the statement goes first with a placeholder, the data fills in after, and it is never run as a command. Never build a SQL statement by joining strings from user input.

    The fault sits with the application code, not with SQL. The database only runs the exact statement it receives. Telling a command apart from data is the programmer’s job.

    Where to start learning SQL

    Three steps are enough to start in one afternoon.

    1. Open a database to practice in. sqlite3 ships with many Mac and Linux machines and runs with no server to install. On Windows, DB Browser for SQLite is a similar option.
    2. Create the orders table above and run the three queries in this article: the best-selling product, the revenue, and orders over 100,000 VND. Change the WHERE condition yourself and watch the result change.
    3. When you want a real database running with a website, run MySQL with Docker Compose, following how to write Docker Compose for a web app with a database. The database in that guide runs on your own server, so you can create tables and try commands without risking real data. What web hosting is and the types of hosting explains where that server lives when the website runs for real.

    Good follow-up exercises after the first three queries: count orders per customer, find the customer who spent the most, and total revenue by day. All three use the same clauses you already learned, only changing the grouping column and the filter.

    Frequently asked questions

    Is SQL a programming language?

    SQL is a specialized language for managing data, not a general-purpose programming language. You cannot write a complete application in SQL alone. SQL works together with a general-purpose language such as JavaScript or Python: the application is written in that language, and the data is asked for in SQL.

    How long does it take to learn SQL?

    SELECT, WHERE, and ORDER BY are enough for one practice session. JOIN for combining tables and GROUP BY for statistics take a few more sessions. The rest comes from daily use: every time you need a number from the database is one more round of practice.

    How is SQL different from Excel?

    Excel is a spreadsheet for one person working with one file. SQL asks a database that many people and many applications share, with far more data, access permissions, and transactions so that several changes either all succeed or all fail together.

    With AI writing code, do I still need to learn SQL?

    AI can write a query, but the reader still has to know whether the query is right or wrong. A SELECT with the wrong WHERE condition returns a number that looks reasonable and is completely wrong, and a decision based on that number is wrong too. Learning SQL means being able to check what the AI gives you.

    A good SQL query answers the question correctly, reads clearly the first time, and returns a result you can check. Open sqlite3, create the orders table above, run the three queries in this article, and then ask one more question of your own data.

    Assistant Gnurt

    Full-stack developer

    Discuss your project

    Comments

    No comments yet. Be the first!