Structured query language (SQL)

Computer Science · Databases. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science topics

The idea

SQL is the language used to ask a database for data. A request is called a query. The basic query has three parts: SELECT lists the fields to show, FROM names the table, and WHERE gives the condition a record must meet to be included.

Conditions can be joined with AND or OR. The results can be sorted with ORDER BY. SUM and COUNT give one number instead of a list of records.

To find the output of a query, work in this order: test every record against the WHERE condition, keep the ones that pass, sort them if asked, then show only the fields named after SELECT.

In simpler words

SQL is a language to ask a database for data. SELECT lists the fields to show. FROM names the table. WHERE gives the condition a record must meet. AND and OR join conditions. ORDER BY sorts the results. SUM adds up values. COUNT tells you how many records match.

An everyday comparison

An SQL query is like ordering from a menu at a restaurant. FROM is choosing the restaurant, WHERE is saying only vegetarian dishes, and SELECT is asking to see just the names and prices. The comparison stops working because SQL follows a strict order and syntax, and text values must be written in quotes.

Rules to remember

Common mistake

Students mix up COUNT and SUM: COUNT says how many records match, SUM adds their values. Another common error is showing a field from the WHERE clause instead of the field named after SELECT.

In the exam

Write the clauses in the correct order: SELECT fields, FROM table, WHERE condition, ORDER BY field, ending with a semicolon. Put text in quotes and leave numbers without. To find output, test each record against WHERE, keep the matches, sort if asked, then show only the SELECT fields. Use COUNT for how many and SUM for a total.

Worked example

Table BOOK holds these records (BookID, Genre, Price, Copies): B1, Crime, 8.00, 3; B2, Poetry, 5.50, 0; B3, Crime, 6.25, 7; B4, Travel, 9.00, 2. What is output by SELECT SUM(Copies) FROM BOOK WHERE Genre = 'Crime' OR Price > 8.50;

  1. Genre = 'Crime' is true for B1 and B3.
  2. Price > 8.50 is true for B4 only (9.00). B1 at 8.00 does not pass this test, but it is already included.
  3. OR keeps records that pass at least one test: B1, B3 and B4.
  4. SUM adds their Copies: 3 + 7 + 2 = 12.

Answer: 12

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Single-table databases and primary keysLogic gates →Take a Computer Science test