SQL Basics
UNION – Combine Query Results
Get seyma akın’s stories in your inbox
Join Medium for free to get updates from this writer.
Combines the results of two or more SELECT queries into one result set.
SELECT name FROM Patients
UNION
SELECT name FROM Doctors;Notes:
- Number and type of columns must match.
- Returns only unique values.
- Use
UNION ALLif you want to keep duplicates.
EXISTS – Check If Data Exists
Returns TRUE if the subquery returns any result.
SELECT * FROM Patients
WHERE EXISTS (
SELECT * FROM Appointments
WHERE Patients.PatientID = Appointments.PatientID
);Notes:
- It checks if data exists, not what the data is.
- If the subquery returns something, the row is selected.
ANY – Compare with Any Value
Returns TRUE if the condition is true for at least one value in the subquery.
SELECT * FROM Doctors
WHERE Salary > ANY (
SELECT Salary FROM Doctors WHERE Department = 'Cardiology'
);Notes:
- If one or more values match the condition, the row is selected.
- Similar to using
INfor equality:= ANY (...).
ALL – Compare with All Values
Returns TRUE if the condition is true for all values in the subquery.
SELECT * FROM Doctors
WHERE Salary > ALL (
SELECT Salary FROM Doctors WHERE Department = 'Cardiology'
);Notes:
- The condition must be true for every value in the subquery.
- If even one value does not match, the row is not selected.
SELECT INTO – Copy Data to a New Table
Creates a new table and copies data from a query into it.
SELECT * INTO NewDoctors
FROM Doctors
WHERE Department = 'Neurology';Notes:
- The new table should not already exist.
- To add data to an existing table, use
INSERT INTO.
INSERT INTO SELECT
It copies data from one existing table into another existing table. It does not create a new table.
INSERT INTO OldPatients (Name, BirthDate)
SELECT Name, BirthDate
FROM Patients
WHERE YEAR(BirthDate) < 1990;ISNULL
Checks if a value is NULL.
If it is, replaces it with another value.
SELECT ISNULL(column, replacement_value) AS result
FROM table;Often used to avoid nulls in calculations or display defaults like 0, '', or 'N/A'.
CASE
Works like an if-else in SQL.
Returns different values based on conditions.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;Useful for custom labels, categories, or conditional logic in queries.



