Sub topic 1
Your first query: SELECT and FROM
Prerequisites
This chapter assumes you know what tables, rows, and columns are, and that you can connect to a SQL database such as PostgreSQL, MySQL, or SQLite. The examples use an employees table with the columns first_name, last_name, department, salary, and hire_date.
Your first query: SELECT and FROM
A SELECT statement asks the database to return data. The FROM clause names the table to read. The following query returns two columns from every row of employees.
SELECT first_name, last_name
FROM employees;Choosing columns instead of using *
SELECT * returns every column in the table. It is quick for exploring unfamiliar data. In application code, however, it is fragile. If someone adds a column later, the shape of your result changes. Listing the columns you need avoids that problem.
SELECT *
FROM employees;Computing values and naming them with aliases
A select list item can be an expression, not only a column name. The AS keyword gives the result column a readable name. Most databases accept the query without AS, but writing it makes the intent clear.
SELECT first_name, salary * 12 AS annual_salary
FROM employees;Removing duplicate rows with DISTINCT
DISTINCT keeps one copy of each distinct row in the result. The following query returns each department once, even when many employees share it.
SELECT DISTINCT department
FROM employees;DISTINCT compares the entire row of selected columns. If you add first_name, each name and department pair appears once, so duplicates of a department can return.
Keeping only matching rows with WHERE
The WHERE clause filters rows before they reach the result. Text values go in single quotes. Comparison operators such as =, <>, <, <=, >, and >= build the condition.
SELECT first_name, last_name, department, salary
FROM employees
WHERE department = 'Sales'
AND salary >= 50000;Exercise
Write a query that returns each distinct department of employees whose salary is at least 50000.
Show answer
SELECT DISTINCT department FROM employees WHERE salary >= 50000;