What is SQL?
5 min read
SQL (Structured Query Language) is a domain-specific language designed for managing and querying relational databases. Created in the 1970s, SQL has become the standard language for database operations and is used by virtually every database system.
SQL allows you to create, read, update, and delete data in databases. It's essential for developers, data analysts, database administrators, and anyone who works with data. SQL is used across industries and is a fundamental skill for backend development, data science, business intelligence, and more.
🗄️ Why SQL is Essential
- ✓Universal: Works with MySQL, PostgreSQL, SQLite, SQL Server, Oracle, and more
- ✓High demand: #2 most in-demand skill, required for most tech roles
- ✓Data access: Essential for retrieving and analyzing data from databases
- ✓Career multiplier: Complements any programming language
- ✓Stable skill: SQL has been around for decades and isn't going away
-- Your first SQL query
SELECT 'Hello, World!' AS greeting;
-- Select from a table
SELECT name, email
FROM users
WHERE age > 18;SQL Syntax Basics
8 min read
SQL syntax is clean and readable. Understanding these fundamental rules will help you write SQL code effectively.
✓ SQL Features
- •Indentation-based blocks (no curly braces)
- •Dynamic typing (no type declarations)
- •Comments start with
# - •Case-sensitive (name ≠ Name)
- •Variables don't need declaration
- •Multiple assignment:
a, b = 1, 2
📝 Code Structure
- •Use 4 spaces for indentation (standard)
- •Colon
:starts code blocks - •No semicolons needed (optional)
- •Line continuation with
\or parentheses - •String quotes: single or double (both work)
✗ Wrong Indentation
if x > 0:
print("Positive") # IndentationError!
print("Still positive")✓ Correct Indentation
if x > 0:
print("Positive") # Correct!
print("Still positive")Try It Yourself
Edit the SQL code and see the results
Try these examples:
Variables & Data Types
10 min read
SQL is dynamically typed, meaning you don't need to declare variable types. SQL automatically determines the type based on the value assigned.
Basic Data Types
Integer
age = 30
count = -5
big_number = 1000000Whole numbers, positive or negative. No size limit in SQL 3.
Float
price = 19.99
pi = 3.14159
temperature = -5.5Decimal numbers. Use for calculations requiring precision.
String
name = "SQL"
message = 'Hello, World!'
multiline = """This is
a multiline
string"""Text data. Can use single, double, or triple quotes. Triple quotes for multiline strings.
Boolean
is_active = True
is_complete = False
has_permission = TrueTrue or False (capitalized). Used for conditional logic.
List
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]Ordered, mutable collection. Can contain any data type, including mixed types.
Dictionary
person = {
"name": "John",
"age": 30,
"city": "NYC"
}Key-value pairs. Keys must be immutable (strings, numbers, tuples).
Tuple
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # Note the commaOrdered, immutable collection. Faster than lists, used for fixed data.
None
result = None
value = NoneRepresents absence of value. Similar to null in other languages.
Operators & Expressions
8 min read
SQL supports various operators for performing operations on variables and values.
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
| + | Addition | 5 + 3 = 8 |
| - | Subtraction | 10 - 4 = 6 |
| * | Multiplication | 3 * 4 = 12 |
| / | Division (float) | 10 / 3 = 3.333... |
| // | Floor division | 10 // 3 = 3 |
| % | Modulus (remainder) | 10 % 3 = 1 |
| ** | Exponentiation | 2 ** 3 = 8 |
Comparison Operators
x = 5
y = 10
print(x == y) # False (equal)
print(x != y) # True (not equal)
print(x < y) # True (less than)
print(x > y) # False (greater than)
print(x <= y) # True (less than or equal)
print(x >= y) # False (greater than or equal)Logical Operators
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # FalseControl Flow
12 min read
Control flow statements allow you to control the execution order of your code. SQL supports if/else, loops, and more.
If/Else Statements
age = 20
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")For Loops
# Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Iterate with index
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# Range function
for i in range(5):
print(i) # 0, 1, 2, 3, 4While Loops
count = 0
while count < 5:
print(f"Count: {count}")
count += 1
# Break and continue
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == 'quit':
break
if user_input == 'skip':
continue
print(f"You entered: {user_input}")Functions
10 min read
Functions are reusable blocks of code that perform a specific task. They help organize code and avoid repetition.
Defining Functions
# Simple function
def greet(name):
return f"Hello, {name}!"
# Function with default parameters
def greet_with_title(name, title="Mr."):
return f"Hello, {title} {name}!"
# Function with multiple return values
def get_name_and_age():
return "John", 30
name, age = get_name_and_age()Lambda Functions
# Lambda (anonymous) function
square = lambda x: x ** 2
print(square(5)) # 25
# Used with map, filter, etc.
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]Lists & Dictionaries
12 min read
Lists and dictionaries are SQL's most commonly used data structures for storing collections of data.
Lists
# Create a list
fruits = ["apple", "banana", "orange"]
# Access elements
print(fruits[0]) # "apple"
print(fruits[-1]) # "orange" (last item)
# Modify list
fruits.append("grape") # Add item
fruits.remove("banana") # Remove item
fruits.insert(1, "mango") # Insert at index
# List methods
fruits.sort() # Sort alphabetically
fruits.reverse() # Reverse order
length = len(fruits) # Get lengthDictionaries
# Create a dictionary
person = {
"name": "John",
"age": 30,
"city": "NYC"
}
# Access values
print(person["name"]) # "John"
print(person.get("age")) # 30
print(person.get("email", "N/A")) # "N/A" (default)
# Modify dictionary
person["email"] = "john@example.com" # Add/update
person.pop("age") # Remove key
person.clear() # Clear all items
# Dictionary methods
keys = person.keys() # Get all keys
values = person.values() # Get all values
items = person.items() # Get key-value pairsObject-Oriented Programming
15 min read
SQL supports object-oriented programming (OOP) with classes and objects. OOP helps organize code into reusable, modular components.
Classes and Objects
# Define a class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"I'm {self.name}, {self.age} years old"
def have_birthday(self):
self.age += 1
# Create objects (instances)
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.introduce()) # "I'm Alice, 25 years old"
person1.have_birthday()
print(person1.age) # 26Inheritance
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# Derived class
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
dog = Dog("Buddy")
print(dog.speak()) # "Woof!"File Handling
10 min read
SQL makes it easy to read from and write to files. The with statement ensures files are properly closed.
Reading Files
# Read entire file
with open('data.txt', 'r') as file:
content = file.read()
print(content)
# Read line by line
with open('data.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() removes newline
# Read all lines into list
with open('data.txt', 'r') as file:
lines = file.readlines()Writing Files
# Write to file (overwrites)
with open('output.txt', 'w') as file:
file.write("Hello, World!")
# Append to file
with open('output.txt', 'a') as file:
file.write("\nNew line")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open('output.txt', 'w') as file:
file.writelines(lines)Error Handling
10 min read
SQL uses try-except blocks to handle errors gracefully. This prevents your program from crashing when something goes wrong.
Try-Except Blocks
# Basic error handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
number = int(input("Enter a number: "))
result = 100 / number
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An error occurred: {e}")Finally Block
# Finally always executes
try:
file = open('data.txt', 'r')
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close() # Always closes, even if error occurs
# Better: use 'with' statement (automatic cleanup)
try:
with open('data.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("File not found!")Modules & Packages
12 min read
Modules are SQL files containing functions, classes, and variables. Packages are collections of modules. They help organize and reuse code.
Importing Modules
# Import entire module
import math
print(math.pi) # 3.14159...
# Import specific function
from math import sqrt, pow
print(sqrt(16)) # 4.0
# Import with alias
import datetime as dt
now = dt.datetime.now()
# Import all (not recommended)
from math import *Common Built-in Modules
mathMathematical functions
import math; math.sqrt(16)datetimeDate and time operations
from datetime import datetime; datetime.now()osOperating system interface
import os; os.getcwd()jsonJSON encoding/decoding
import json; json.loads(data)randomRandom number generation
import random; random.randint(1, 10)reRegular expressions
import re; re.search(pattern, text)Common Mistakes
10 min read
Even experienced SQL developers make these mistakes. Learn to avoid them early.
Indentation Errors
SQL uses indentation to define code blocks. Use 4 spaces consistently (not tabs).
✗ Wrong
if x > 0:
print("Positive") # IndentationError!✓ Correct
if x > 0:
print("Positive") # Correct indentationMutable Default Arguments
Mutable default arguments are shared across function calls. Use None as default instead.
✗ Wrong
def add_item(item, my_list=[]):
my_list.append(item)
return my_list✓ Correct
def add_item(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_listModifying List While Iterating
Modifying a list while iterating can cause unexpected behavior. Use list comprehension or iterate over a copy.
✗ Wrong
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Dangerous!✓ Correct
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0] # List comprehensionUsing == for None
Use "is" or "is not" for None comparisons, not == or !=. This checks identity, not equality.
✗ Wrong
if value == None: # Not recommended
print("No value")✓ Correct
if value is None: # Correct
print("No value")Forgetting Return Statement
Functions without a return statement return None. Always use return for values you want to use.
✗ Wrong
def calculate_sum(a, b):
a + b # Missing return!✓ Correct
def calculate_sum(a, b):
return a + b # CorrectBest Practices
12 min read
Follow these SQL best practices to write clean, maintainable, and SQLic code.
📋Follow PEP 8 Style Guide
PEP 8 is SQL's official style guide. Following it makes your code more readable and professional.
✓ Good naming
user_name = "John"
def calculate_total():
pass✗ Bad naming
userName = "John"
def CalculateTotal():
pass⚡Use List Comprehensions
List comprehensions are more SQLic and often faster than loops.
✗ Loop approach
squares = []
for x in range(10):
squares.append(x ** 2)✓ List comprehension
squares = [x ** 2 for x in range(10)]💬Use f-strings for Formatting
f-strings (SQL 3.6+) are the most readable and efficient way to format strings.
✗ Old style
name = "John"
message = "Hello, %s" % name✓ f-string
name = "John"
message = f"Hello, {name}"🔒Use Context Managers (with statement)
Always use 'with' for file operations to ensure proper cleanup.
✗ Manual cleanup
file = open('data.txt')
content = file.read()
file.close() # Easy to forget!✓ Context manager
with open('data.txt') as file:
content = file.read()
# Automatically closed📚Write Docstrings
Document your functions and classes with docstrings for better code documentation.
def calculate_area(length, width):
"""
Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle
width (float): The width of the rectangle
Returns:
float: The area of the rectangle
"""
return length * widthPractice Coding
Interactive exercises to test your skills
Put your SQL knowledge to the test! Complete these exercises to reinforce what you've learned. Each exercise has a solution you can check when you're ready.
Exercise 1: Basic SELECT Query
BeginnerWrite a SQL query to select all columns from the users table.
Exercise 2: SELECT with WHERE Clause
BeginnerSelect the name and email columns from the users table where age is greater than 18.
Exercise 3: JOIN Two Tables
IntermediateWrite a query to join the users and orders tables. Select user name and order date where the user_id matches.
Exercise 4: Aggregate Functions
IntermediateWrite a query to calculate the total number of users, average age, and maximum age from the users table.
Exercise 5: GROUP BY with HAVING
AdvancedGroup orders by user_id and show only those users who have more than 5 orders. Display user_id and order count.