Skip to content

SQL SELECT Statement Syntax

Concept

SELECT retrieves data from one or more tables.

Syntax

SELECT column1, column2 FROM table_name;

SELECT first_name, salary FROM employees;

Removing Duplicate Values Using DISTINCT

Concept

DISTINCT removes duplicate rows from the result set.

Syntax

SELECT DISTINCT column_name FROM table_name;

SELECT DISTINCT department FROM employees;

SELECT DISTINCT department, city FROM employees; // (department + city) combination

SELECT DISTINCT * FROM employees; // Removes rows that are fully identical across every column.

Using a Column Alias

Concept

Rename columns in output using AS.

Syntax

SELECT column_name AS alias_name FROM table_name;

SELECT salary AS employee_salary FROM employees;

SQL WHERE Clause Syntax

Concept

Filters rows.

Syntax

SELECT columns
FROM table
WHERE condition;

Example

SELECT *
FROM employees
WHERE salary > 50000;

Filter Records Based on Single Criteria

Example

SELECT *
FROM students
WHERE age = 18;

Filtering Text vs Numeric Data

Concept

  • Text values use quotes.

  • Numbers do not.

Text Example

SELECT *
FROM employees
WHERE city = 'Mumbai';

Numeric Example

SELECT *
FROM employees
WHERE salary > 70000;

WHERE Clause Operators Cheat Sheet

Operator Meaning
= Equal
!= or <> Not Equal
> Greater Than
< Less Than
>= Greater or Equal
<= Less or Equal
BETWEEN Range
IN Match List
LIKE Pattern Match
IS NULL Null Check
SELECT *
FROM employees
WHERE salary BETWEEN 50000 AND 100000;
// WHERE salary NOT BETWEEN 50000 AND 100000;


SELECT *
FROM employees
WHERE department IN ('HR', 'IT', 'Finance'); // WHERE department NOT IN ('HR', 'IT');
is equivalent to 
WHERE department = 'HR'
OR department = 'IT'
OR department = 'Finance'


SELECT *
FROM employees
WHERE name LIKE 'A%'; // WHERE name NOT LIKE 'A%';

SELECT *
FROM employees
WHERE name LIKE '%a';

SELECT *
FROM employees
WHERE name LIKE '%mit%';


Wildcards in LIKE
Symbol  Meaning
%   Any number of characters
_   Exactly one character




SELECT *
FROM employees
WHERE manager_id IS NULL; // WHERE manager_id IS NOT NULL;

Filtering with AND

Concept

Both conditions must be true.

Example

SELECT *
FROM employees
WHERE department = 'IT'
AND salary > 60000;

SELECT *
FROM employees
WHERE NOT (department = 'HR' AND salary > 60000);

QUICK TIP --- MySQL Comments

Single Line

-- This is a comment
SELECT * FROM employees;
 OR 
# This is a comment

Multi-line

/*
This is
multi-line comment
*/

Filtering Dates with BETWEEN

Concept

Checks range inclusively.

Example

SELECT *
FROM orders
WHERE order_date BETWEEN '2025-01-01' AND '2025-12-31';

Filtering with OR

Concept

At least one condition must be true.

Example

SELECT *
FROM employees
WHERE department = 'HR'
OR department = 'Finance';

SQL ORDER BY Syntax

Concept

Sort results.

Syntax

SELECT columns
FROM table
ORDER BY column_name;

Sort Ascending (default order) / Descending

ASC Example

SELECT *
FROM products
ORDER BY price ASC;

DESC Example

SELECT *
FROM products
ORDER BY price DESC;

Sort by Multiple Columns

Example

SELECT *
FROM employees
ORDER BY department ASC, salary DESC;

SQL GROUP BY Syntax

Concept

Groups rows sharing same values. GROUP BY is commonly used with aggregate functions, but not strictly required.

However, using GROUP BY without aggregates is often pointless or a sign you don’t fully understand what it’s doing.

Critical SQL Rule

If you use GROUP BY, then every selected column must be:

Included in GROUP BY OR Wrapped inside aggregate function

Syntax

SELECT column, aggregate_function(column)
FROM table
GROUP BY column;

Grouping Data by Column

Example

SELECT department, COUNT(*)
FROM employees
GROUP BY department;

DISTINCT vs GROUP BY

DISTINCT

Removes duplicates.

SELECT DISTINCT department
FROM employees;

GROUP BY

Groups rows for calculations.

SELECT department, COUNT(*)
FROM employees
GROUP BY department;

Common mistake

Using GROUP BY when DISTINCT is enough. That's sloppy querying.


Aggregate Functions

Function Purpose
COUNT() Count rows
SUM() Total
AVG() Average
MAX() Highest
MIN() Lowest

Calculations within GROUP BY

Example

SELECT department,
       AVG(salary) AS avg_salary,
       SUM(salary) AS total_salary
FROM employees
GROUP BY department;

HAVING Clause

Concept

Filters grouped data.

Example

SELECT department, COUNT(*) AS total
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;

Critical distinction

  • WHERE filters rows BEFORE grouping.

  • HAVING filters groups AFTER grouping.

Confusing these means you do not yet understand SQL execution flow.


Create Database

Syntax

CREATE DATABASE company_db;

Drop Database

Syntax

DROP DATABASE company_db;

Warning

Permanent deletion.


CREATE TABLE Statement

Syntax

CREATE TABLE employees (
    id INT,
    name VARCHAR(100),
    salary DECIMAL(10,2)
);

DROP TABLE

Syntax

DROP TABLE employees;

NOT NULL Constraint

Concept

Prevents empty values.

Example

CREATE TABLE users (
    id INT,
    name VARCHAR(100) NOT NULL
);

AUTO_INCREMENT Column

Concept

Automatically generates numeric IDs.

Example

CREATE TABLE users (
    id INT AUTO_INCREMENT,
    name VARCHAR(100),
    PRIMARY KEY(id)
);

PRIMARY KEY Constraint

Concept

Uniquely identifies each row.

Example

CREATE TABLE employees (
    emp_id INT PRIMARY KEY,
    name VARCHAR(100)
);

FOREIGN KEY Constraint

Concept

Creates relationship between tables.

Example

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id)
    REFERENCES customers(customer_id)
);

Creating a SQL Database --- Full Example

CREATE DATABASE school_db;

USE school_db;

CREATE TABLE students (
    student_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    age INT,
    city VARCHAR(50)
);

Insert Data into Specific Columns

Syntax

INSERT INTO table_name(column1, column2)
VALUES(value1, value2);

Example

INSERT INTO students(name, age)
VALUES('Rahul', 20);

Insert Data into Every Column

Syntax

INSERT INTO table_name
VALUES(value1, value2, value3);

Example

INSERT INTO students
VALUES(1, 'Amit', 22, 'Mumbai');

One Practical Mini Example

CREATE DATABASE company_db;

USE company_db;

CREATE TABLE employees (
    emp_id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    department VARCHAR(50),
    salary DECIMAL(10,2),
    joining_date DATE
);

INSERT INTO employees(name, department, salary, joining_date)
VALUES
('Rahul', 'IT', 70000, '2024-01-10'),
('Amit', 'HR', 50000, '2023-06-15'),
('Sneha', 'IT', 90000, '2022-11-01');

SELECT * FROM employees;

SELECT DISTINCT department
FROM employees;

SELECT *
FROM employees
WHERE salary > 60000;

SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000;

SELECT *
FROM employees
ORDER BY salary DESC;

The fastest way to actually learn SQL is not reading syntax. It is:

  1. Create tables.

  2. Break queries.

  3. Debug errors.

  4. Predict outputs before running queries.

Most beginners stay stuck because they passively watch tutorials instead of writing 200+ queries themselves.


Window functions in SQL

Window functions in SQL are powerful tools used to perform calculations across a specific "window" of rows related to the current row. Unlike aggregate functions (like SUM(), AVG(), COUNT()), which collapse multiple rows into a single result, window functions retain individual rows while adding calculated values.

  • FUNCTION() OVER (PARTITION BY column1 ORDER BY column2)

    • FUNCTION(): What do you want to calculate? (e.g., SUM, AVG, ROW_NUMBER, RANK).
    • OVER: The magic keyword that tells SQL, "Treat this as a window function, not a regular aggregation." - OVER clause defines the "window" of rows that the function will evaluate for each given row.
    • PARTITION BY: How do you want to slice the data? - GROUP BY returns one row per group, whereas PARTITION BY retains all rows and calculates values for each row within its partition.
    • ORDER BY: Inside that slice, how should the data be sorted to calculate the function? [1]
  • The Big Three: Ranking Functions

The best way to start practicing window functions is by numbering your rows. There are three functions that do this, and they handle ties differently:

  1. ROW_NUMBER(): Numbers rows sequentially (1, 2, 3, 4). No ties allowed.
  2. RANK(): Numbers rows but leaves gaps if there is a tie (1, 2, 2, 4).
  3. DENSE_RANK(): Numbers rows and leaves no gaps for ties (1, 2, 2, 3).