ADVERTISEMENT

SQL SELECT

The SELECT statement is how we read data from a table. Let’s quickly go through the different ways to use it.

🔹 Basic Usage

-- Select all columns
SELECT * FROM employees;

-- Select specific columns
SELECT name, salary FROM employees;

-- Filter rows using WHERE
SELECT name FROM employees WHERE department = 'HR';

-- Use comparison and logical operators
SELECT * FROM employees WHERE salary > 50000 AND department = 'IT';

-- Sort results by column
SELECT name, salary FROM employees ORDER BY salary DESC;

-- Get unique values (no duplicates)
SELECT DISTINCT department FROM employees;

-- Limit number of rows (varies by DBMS)
-- MySQL / PostgreSQL
SELECT * FROM employees LIMIT 5;
-- SQL Server
SELECT TOP 5 * FROM employees;
-- Oracle 12c+
SELECT * FROM employees FETCH FIRST 5 ROWS ONLY;

-- Rename columns in output
SELECT name AS employee_name, salary AS monthly_salary FROM employees;

-- Use expressions in SELECT
SELECT name, salary * 12 AS annual_salary FROM employees;

-- SELECT from multiple tables using JOIN (basic preview)
SELECT e.name, d.name AS department_name
FROM employees e
JOIN departments d ON e.department_id = d.id;

-- Create a new table from a SELECT
-- SQL Server / PostgreSQL / Oracle
SELECT * INTO temp_employees FROM employees WHERE department = 'Sales';
-- MySQL alternative
CREATE TABLE temp_employees AS
SELECT * FROM employees WHERE department = 'Sales';

🧠 Quick Recap

  • SELECT reads data
  • Use WHERE to filter, ORDER BY to sort
  • DISTINCT removes duplicates
  • Use aliases with AS
  • Add LIMIT, TOP, or FETCH to limit rows
  • You can even create new tables using SELECT INTO

✅ That’s it! Simple and powerful.

ADVERTISEMENT