0% found this document useful (0 votes)
18 views5 pages

Essential SQL Queries with Examples

This guide covers essential SQL statements including SELECT, INSERT INTO, UPDATE, CREATE TABLE IF NOT EXISTS, and DROP TABLE IF EXISTS, providing examples and explanations using a sample dataset. It also introduces advanced queries like JOIN, GROUP BY, and DELETE, along with best practices for safe execution. The document includes practice exercises to reinforce learning and ensure understanding of SQL operations.

Uploaded by

comof43008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Essential SQL Queries with Examples

This guide covers essential SQL statements including SELECT, INSERT INTO, UPDATE, CREATE TABLE IF NOT EXISTS, and DROP TABLE IF EXISTS, providing examples and explanations using a sample dataset. It also introduces advanced queries like JOIN, GROUP BY, and DELETE, along with best practices for safe execution. The document includes practice exercises to reinforce learning and ensure understanding of SQL operations.

Uploaded by

comof43008
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SQL Core Queries — Practical Guide with Examples

This short guide explains five essential SQL statements (SELECT, INSERT INTO, UPDATE,
CREATE TABLE IF NOT EXISTS, DROP TABLE IF EXISTS) with clear examples using a
sample dataset `customer_data.customer_address`. Each example shows the SQL, a short
explanation, and expected results or notes to practice safely.

Sample dataset: customer_data.customer_address


Assume we have a table with the following structure and rows:

customer_id name city address

1 Alice Johnson Chicago 789 Pine Street

2 Bob Smith Boston 22 Market Road

3 Jane Doe New York 123 Main Street

1. SELECT → extract data from tables


Purpose:
Use SELECT to retrieve columns (or * for all columns) from a table. Combine with WHERE,
ORDER BY, GROUP BY, LIMIT, etc., for filtering and aggregation.

Example SQL:

SELECT name, city


FROM customer_data.customer_address;

Explanation: Returns the name and city columns for every row in the table. Result (based on
sample data):

name city

Alice Johnson Chicago

Bob Smith Boston

Jane Doe New York

Practice tip: Try adding WHERE city = 'Boston' to filter results.

2. INSERT INTO → add new data


Purpose:
Use INSERT INTO to add one or more rows to a table. Specify the columns to avoid errors
and to keep insertions explicit.
Example SQL:

INSERT INTO customer_data.customer_address (customer_id, name, city, address)


VALUES (4, 'Sarah Lee', 'Miami', '55 Ocean Drive');

Explanation: This statement inserts a new row (customer_id=4) into the table. After running
it, the table will contain the new entry.

customer_id name city address

1 Alice Johnson Chicago 789 Pine Street

2 Bob Smith Boston 22 Market Road

3 Jane Doe New York 123 Main Street

4 Sarah Lee Miami 55 Ocean Drive

Best practice: When inserting many rows, consider a transaction or batch insert for safety.

3. UPDATE → change existing data


Purpose:
Use UPDATE to modify rows that already exist. Always include a WHERE clause to limit the
change to intended rows; otherwise every row will be updated.

UPDATE

your project [Link].car_info

SET

num_of_doors = "four"

WHERE

make = "dodge"

AND fuel_type = "gas"

AND body_style = "sedan";

Example SQL:

UPDATE customer_data.customer_address
SET address = '456 Oak Avenue'
WHERE customer_id = 3;
Explanation: This updates the row where customer_id = 3 (Jane Doe) changing her address.
Using the primary key (customer_id) is safer than matching on name.

Practice tip: Run a SELECT with the same WHERE first to confirm which rows will change:
SELECT * FROM customer_data.customer_address WHERE customer_id = 3;

4. CREATE TABLE IF NOT EXISTS → build a table safely


Purpose:
Creates a new table only if it does not already exist. Useful for scripts that may run multiple
times without failing when the table already exists.

Example SQL:

CREATE TABLE IF NOT EXISTS customer_data.weekend_promo (


promo_id INT PRIMARY KEY,
customer_id INT,
purchase_date DATE
);

Explanation: This creates a lightweight table to store promotional purchases. If the table
already exists, the statement does nothing (no error).

Note: After creating, you can INSERT INTO this table or populate it with results from a
SELECT: INSERT INTO customer_data.weekend_promo (promo_id, customer_id,
purchase_date)
SELECT 1, customer_id, purchase_date FROM some_source WHERE ...;

5. DROP TABLE IF EXISTS → clean up unused tables


Purpose:
Removes (drops) a table only if it exists. This is useful for cleaning temporary tables created
during analyses.

Example SQL:

DROP TABLE IF EXISTS customer_data.weekend_promo;

Explanation: This deletes the weekend_promo table if present. Be careful: DROP


permanently removes data. Avoid running on production tables without confirmation.

Best practices & safety tips


• Always backup or work on a copy of critical data before running INSERT/UPDATE/DROP.
• Use transactions when performing multiple related changes (BEGIN; ... COMMIT; or
ROLLBACK on error).
• Prefer using primary keys in WHERE clauses for UPDATE/DELETE to avoid accidental
mass updates.
• Test your WHERE clause with SELECT first to confirm affected rows.
• Use CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS in scripts to make them
idempotent and safe to rerun.

Practice exercises
1) Run a SELECT to list all customers in 'Boston'.
SELECT * FROM customer_data.customer_address WHERE city = 'Boston';

2) Insert two new customers and then SELECT to confirm they were added.

3) Update a customer's city using their customer_id and verify changes with SELECT.

4) Create a new summary table for daily customer counts using CREATE TABLE IF NOT
EXISTS, populate it, then drop it using DROP TABLE IF EXISTS.

Document created for you. Save and reuse this guide during practice.

Advanced SQL Queries


Now that you know the basics (SELECT, INSERT, UPDATE, CREATE, DROP), here are three
more advanced but commonly used SQL statements: JOIN, GROUP BY, and DELETE.

1. JOIN → combine data from multiple tables


Purpose:
JOIN lets you combine rows from two or more tables based on a related column.

Example SQL:

SELECT [Link], o.order_id, o.order_date


FROM customer_data.customer_address c
JOIN customer_data.orders o
ON c.customer_id = o.customer_id;

Explanation: This query combines the customer_address table with the orders table. It
matches rows where customer_id is the same, returning the customer's name alongside
their orders.

2. GROUP BY → aggregate data by categories


Purpose:
GROUP BY is used with aggregate functions (COUNT, SUM, AVG, etc.) to group rows that
share a column value.

Example SQL:

SELECT city, COUNT(*) AS customer_count


FROM customer_data.customer_address
GROUP BY city;

Explanation: This query counts how many customers are in each city. The result shows each
city alongside the number of customers living there.

3. DELETE → remove rows from a table


Purpose:
DELETE removes rows from a table. Always use WHERE to target specific rows.

Example SQL:

DELETE FROM customer_data.customer_address


WHERE customer_id = 4;

Explanation: This removes the row with customer_id = 4 from the table. Without WHERE,
all rows would be deleted — so use carefully!

Best practices for advanced queries


• Test JOINs with SELECT * and a LIMIT first to make sure results look right.
• Always double-check GROUP BY with COUNT before using SUM or AVG to avoid mis-
aggregation.
• For DELETE, confirm affected rows by first running SELECT with the same WHERE clause.

You might also like