CodeWithSQL.com
HomeSQL Beginner CourseSQL Fundamentals

SQL Fundamentals

Master SQL basics including syntax rules, data types (INT, VARCHAR, DATE, etc.) and operators (arithmetic, comparison, logical) with practical examples.

3 Topics Chapter 3 of 8 Beginner

1 SQL Syntax

Top

SQL has a clean, English-like syntax. Every SQL statement tells the database what to do — and the database figures out how to do it. Let's build a mini-project from scratch to see how the syntax works in practice.

Step 1: Create a Database

SQLCREATE DATABASE bookstore;

Step 2: Create a Table

SQLCREATE TABLE books ( id INT PRIMARY KEY, title VARCHAR(200), author VARCHAR(100), price DECIMAL(8,2), published DATE );

Step 3: Insert Data

SQLINSERT INTO books (id, title, author, price, published) VALUES (1, 'SQL in 10 Minutes', 'Ben Forta', 24.99, '2021-11-01'), (2, 'Learning SQL', 'Alan Beaulieu', 39.99, '2020-04-15'), (3, 'SQL Pocket Guide', 'Alice Zhao', 19.99, '2021-08-10');

Step 4: Query the Data

SQLSELECT title, author, price FROM books WHERE price < 30 ORDER BY price;
Result
title              | author      | price
-------------------|-------------|------
SQL Pocket Guide   | Alice Zhao  | 19.99
SQL in 10 Minutes  | Ben Forta   | 24.99

Syntax Rules to Remember

RuleExampleNotes
Statements end with ;SELECT * FROM books;Tells the DBMS the statement is complete
Keywords are case-insensitiveSELECT = select = SelectConvention: UPPERCASE for keywords
Strings use single quotesWHERE name = 'Alice'Double quotes are for identifiers in some DBs
Single-line comments-- This is a commentEverything after -- is ignored
Multi-line comments/* ... */For longer explanations
Whitespace doesn't matterYou can split queries across linesUse line breaks for readability

Best practice: Write SQL keywords in UPPERCASE and table/column names in lowercase. This makes queries much easier to read: SELECT name FROM customers WHERE country = 'UAE'

Key Takeaways

  • Every SQL statement ends with a semicolon (;)
  • SQL keywords are case-insensitive, but use UPPERCASE by convention
  • Strings go in single quotes; comments use -- or /* */
  • The basic flow: CREATE a table, INSERT data, SELECT to query

2 Data Types

Top

Every column in a SQL table has a data type that controls what kind of values it can hold. Choosing the right type matters — it affects storage, performance, and what operations you can perform.

Numeric Types

TypeWhat It StoresExample ValuesWhen to Use
INTWhole numbers1, -42, 1000000IDs, counts, quantities
BIGINTVery large whole numbersUp to 9.2 quintillionSocial media post IDs, large counters
DECIMAL(p,s)Exact fixed-point numbersDECIMAL(10,2)12345678.99Money, financial data (always!)
FLOATApproximate decimals3.14159Scientific calculations, measurements

String / Character Types

TypeWhat It StoresMax SizeWhen to Use
CHAR(n)Fixed-length textCHAR(2) always stores 2 charsCountry codes ('US'), status flags
VARCHAR(n)Variable-length textUp to n charactersNames, emails, descriptions
TEXTLarge text blocksUp to 65,535+ charsBlog posts, comments, long descriptions

Date and Time Types

TypeFormatExampleWhen to Use
DATEYYYY-MM-DD'2026-04-04'Birthdays, order dates
TIMEHH:MM:SS'14:30:00'Schedules, durations
DATETIMEYYYY-MM-DD HH:MM:SS'2026-04-04 14:30:00'Timestamps, created_at fields

Other Types

TypeWhat It StoresNotes
BOOLEANTRUE or FALSEMySQL uses TINYINT(1) internally
NULLAbsence of a valueNot zero, not empty string — literally "unknown"

Practical Example

SQLCREATE TABLE employees ( id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(150) UNIQUE, department VARCHAR(50), salary DECIMAL(10,2), hire_date DATE, is_active BOOLEAN DEFAULT TRUE ); INSERT INTO employees VALUES (1, 'Sara Ahmed', 'sara@company.com', 'Engineering', 85000.00, '2023-01-15', TRUE), (2, 'James Lee', 'james@company.com', 'Marketing', 62000.00, '2023-06-01', TRUE), (3, 'Priya Patel', 'priya@company.com', 'Engineering', 92000.50, '2022-09-10', TRUE);

Common mistake: Never use FLOAT for money. FLOAT has rounding errors — 0.1 + 0.2 might equal 0.30000000000000004. Always use DECIMAL for financial data. Also, prefer VARCHAR over CHAR unless the length is truly fixed (like country codes).

Key Takeaways

  • Use INT for whole numbers, DECIMAL for money, FLOAT for science
  • Use VARCHAR(n) for most text; CHAR(n) only for fixed-length values
  • Use DATE for dates, DATETIME for timestamps
  • NULL means "unknown" — it's not zero or empty string
  • Choosing the right data type affects storage, performance, and data integrity

3 SQL Operators

Top

Operators are the tools you use inside SQL queries to filter, compare, calculate, and combine data. Let's look at each category with practical examples using the employees table we created above.

Arithmetic Operators

Perform calculations directly in your queries:

SQL-- Calculate annual bonus (10% of salary) SELECT name, salary, salary * 0.10 AS bonus FROM employees;
Result
name        | salary   | bonus
------------|----------|--------
Sara Ahmed  | 85000.00 | 8500.00
James Lee   | 62000.00 | 6200.00
Priya Patel | 92000.50 | 9200.05
OperatorMeaningExample
+Additionsalary + 5000
-Subtractionprice - discount
*Multiplicationquantity * price
/Divisiontotal / 12
%Modulus (remainder)id % 2 (odd/even check)

Comparison Operators

Used in WHERE clauses to filter rows:

SQL-- Employees earning more than 80K SELECT name, salary FROM employees WHERE salary > 80000;
Result
name        | salary
------------|----------
Sara Ahmed  | 85000.00
Priya Patel | 92000.50
OperatorMeaningExample
=Equal toWHERE department = 'Engineering'
!= or <>Not equal toWHERE status != 'inactive'
>Greater thanWHERE salary > 80000
<Less thanWHERE age < 30
>=Greater than or equalWHERE rating >= 4
<=Less than or equalWHERE price <= 99.99

Logical Operators (AND, OR, NOT)

Combine multiple conditions:

SQL-- Engineers earning over 90K SELECT name, department, salary FROM employees WHERE department = 'Engineering' AND salary > 90000; -- Engineers OR anyone earning over 90K SELECT name, department, salary FROM employees WHERE department = 'Engineering' OR salary > 90000; -- Everyone except Marketing SELECT name, department FROM employees WHERE NOT department = 'Marketing';

Watch out: AND is evaluated before OR. The query WHERE a = 1 OR b = 2 AND c = 3 means WHERE a = 1 OR (b = 2 AND c = 3). Use parentheses to be explicit: WHERE (a = 1 OR b = 2) AND c = 3.

BETWEEN, IN, LIKE, IS NULL

These are the operators you'll use most often for filtering:

SQL-- BETWEEN: salary range SELECT name, salary FROM employees WHERE salary BETWEEN 60000 AND 90000; -- IN: match any value in a list SELECT name, department FROM employees WHERE department IN ('Engineering', 'Design', 'Product'); -- LIKE: pattern matching with wildcards SELECT name FROM employees WHERE name LIKE 'S%'; -- starts with S SELECT email FROM employees WHERE email LIKE '%@company.com'; -- ends with @company.com -- IS NULL: check for missing values SELECT name FROM employees WHERE department IS NULL; -- no department assigned
OperatorWhat It DoesExample
BETWEEN x AND yValue within a range (inclusive)WHERE price BETWEEN 10 AND 50
IN (list)Matches any value in the listWHERE country IN ('USA', 'UK')
LIKE patternPattern match (% = any chars, _ = one char)WHERE name LIKE 'J_hn%'
IS NULLChecks for null (missing) valuesWHERE phone IS NULL
IS NOT NULLChecks value existsWHERE email IS NOT NULL

Why IS NULL instead of = NULL? In SQL, NULL isn't a value — it's the absence of a value. You can't compare something to nothing with =. The expression NULL = NULL returns NULL (unknown), not TRUE. Always use IS NULL or IS NOT NULL.

Key Takeaways

  • Arithmetic operators (+ - * / %) let you calculate values in queries
  • Comparison operators (= != > < >= <=) filter rows in WHERE clauses
  • AND narrows results; OR broadens them; NOT inverts conditions
  • BETWEEN, IN, LIKE, and IS NULL are your everyday filtering tools
  • Use parentheses with AND/OR to avoid operator precedence surprises

What's next? Now that you understand SQL syntax, data types, and operators, you're ready to start creating database objects. The next chapter covers DDL Commands — CREATE, ALTER, DROP, TRUNCATE, and RENAME.