SELECT column1, column2, ...
FROM table_name;
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
The COUNT(DISTINCT column_name) is not supported in Microsoft Access databases.
workaround for MS Access:
SELECT Count(*) AS DistinctCountries
FROM (SELECT DISTINCT Country FROM Customers);
SELECT COUNT(*) AS [Number of records], CategoryID
FROM Products
GROUP BY CategoryID;
COLUMNS = ATTRIBUTE
The MOD() function returns the remainder of a number divided by another number.
MOD(x, y) x MOD y x %y
The LENGTH() function returns the length of a string (in bytes).
LENGTH(string)
SQL Server / MS Access Syntax:
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;
MySQL Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Oracle 12 Syntax:
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY; -- FETCH FIRST ROW ONLY;
Older Oracle Syntax:
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
The percent sign % represents zero, one, or multiple characters
The underscore sign _ represents one, single character
Wildcard Characters
Symbol Description
% Represents zero or more characters
_ Represents a single character
[] Represents any single character within the brackets *
^ Represents any character not in the brackets *
- Represents any single character within the specified range *
{} Represents any escaped character **
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
SUBSTR()
Syntax SUBSTR(string, start, length)
SUBSTR(string FROM start FOR length)
REVERSE(string)
1) select * from city;
2) SELECT * FROM CITY WHERE POPULATION > 100000 AND COUNTRYCODE = 'USA';
3) SELECT NAME FROM CITY WHERE POPULATION > 120000 AND COUNTRYCODE =
'USA';
4) SELECT * FROM CITY WHERE ID = 1661;
5) SELECT * FROM CITY WHERE COUNTRYCODE = 'JPN';
6) SELECT NAME FROM CITY WHERE COUNTRYCODE = 'JPN';
7) SELECT CITY, STATE FROM STATION ;
8) SELECT DISTINCT CITY FROM STATION WHERE MOD(ID,2) = 0 ;
9) SELECT COUNT(CITY) - COUNT(DISTINCT CITY) FROM STATION ;
10) select city, length(city) from station order by length(city) DESC,city ASC LIMIT 1;
select city, length(city) from station order by length(city) asc ,city asc fetch first row
only;
11) SELECT DISTINCT(CITY) FROM STATION WHERE CITY LIKE 'A%' OR CITY LIKE 'E%' OR
CITY LIKE 'I%' OR CITY LIKE 'O%' or CITY LIKE 'U%';
12) SELECT DISTINCT(CITY) FROM STATION WHERE CITY LIKE '%a' OR CITY LIKE '%e' OR
CITY LIKE '%i' OR CITY LIKE '%o' OR CITY LIKE '%u';
13) SELECT DISTINCT CITY FROM STATION WHERE (CITY LIKE 'A%' OR CITY LIKE 'E%' OR
CITY LIKE 'I%' OR CITY LIKE 'O%' OR CITY LIKE 'U%') AND (CITY LIKE '%a' OR CITY LIKE
'%e' OR CITY LIKE '%i' OR CITY LIKE '%o' OR CITY LIKE '%u') order by city;
14) SELECT DISTINCT CITY FROM STATION WHERE upper(SUBSTR(CITY,1,1)) NOT IN
('A','E','I','O','U') AND lower(SUBSTR(CITY,1,1)) NOT IN ('a','e','i','o','u');
15) SELECT DISTINCT CITY FROM STATION WHERE UPPER(SUBSTR(CITY, LENGTH(CITY), 1))
NOT IN ('A','E','I','O','U') AND LOWER(SUBSTR(CITY, LENGTH(CITY),1)) NOT IN
('a','e','i','o','u');
16) SELECT DISTINCT CITY FROM STATION WHERE LOWER(SUBSTR(CITY,1,1)) NOT IN
('a','e','i','o','u') OR LOWER(SUBSTR(CITY, LENGTH(CITY),1)) NOT IN ('a','e','i','o','u');
17) SELECT DISTINCT CITY FROM STATION WHERE LOWER(SUBSTR(CITY,1,1)) NOT IN
('a','e','i','o','u') AND LOWER(SUBSTR(CITY,LENGTH(CITY),1)) NOT IN ('a','e','i','o','u');
18) SELECT NAME FROM STUDENTS WHERE MARKS > 75 ORDER BY SUBSTR(NAME,
LENGTH(NAME)-2, 3), ID;
19) SELECT NAME FROM EMPLOYEE ORDER BY NAME;
20) SELECT NAME FROM EMPLOYEE WHERE SALARY > 2000 AND MONTHS < 10 ORDER
BY EMPLOYEE_ID;
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
PIVOT rotates a table-valued expression by turning the unique values from one
column in the expression into multiple columns in the output. PIVOT also runs
aggregations where they're required on any remaining column values that are
wanted in the final output.
UNPIVOT carries out the opposite operation to PIVOT, by rotating columns of a table-
valued expression into column values.
ROW_NUMBER ( )
OVER ( [ PARTITION BY value_expression , ... [ n ] ] order_by_clause )
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
The CONCAT() function adds two or more expressions together.
CONCAT(expression1, expression2, expression3,...)
1) SELECT CASE
WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END
FROM TRIANGLES;
2) SELECT (name || '(' || SUBSTR(occupation,1,1) || ')') FROM occupations ORDER BY
name;
SELECT ('There are a total of ' || COUNT(occupation) || ' ' || LOWER(occupation) ||
's' || '.') FROM occupations GROUP BY occupation ORDER BY COUNT(occupation),
occupation ASC;
3) SELECT
MAX(CASE WHEN Occupation = 'Doctor' THEN Name END) AS Doctor,
MAX(CASE WHEN Occupation = 'Professor' THEN Name END) AS Professor,
MAX(CASE WHEN Occupation = 'Singer' THEN Name END) AS Singer,
MAX(CASE WHEN Occupation = 'Actor' THEN Name END) AS Actor
FROM
SELECT
ROW_NUMBER() OVER(PARTITION BY Occupation ORDER BY Name) AS RowNum,
Name,
Occupation
FROM OCCUPATIONS
) AS SOURCE
GROUP BY RowNum;
4) select N,
if(P is null, 'Root', if((select count(*) from BST where P = B.N)> 0, 'Inner', 'Leaf'))
from BST as B
order by N;
5) SELECT c.company_code, c.founder, COUNT(DISTINCT e.lead_manager_code),
COUNT(DISTINCT e.senior_manager_code), COUNT(DISTINCT e.manager_code),
COUNT(DISTINCT e.employee_code) FROM company c
JOIN employee e ON c.company_code = e.company_code GROUP BY
c.company_code, c.founder ORDER BY c.company_code;
The AVG() function returns the average value of an expression.
AVG(expression)
The ROUND() function rounds a number to a specified number of decimal places.
ROUND(number, decimals)
Parameter Values
Parameter Description
Number Required. The number to be rounded
Decimals Optional. The number of decimal places to
round number to. If omitted, it returns the
integer (no decimals)
The CEIL() function returns the smallest integer value that is bigger than or equal to a
number.
The TRUNCATE() function truncates a number to the specified number of decimal
places. Syntax TRUNCATE(number, decimals)
Parameter
number Required. The number to be truncated decimals
decimals Required. The number of decimal places to truncate to
The FLOOR() function returns the largest integer value that is smaller than or equal to
a number.
1) select count(name) from city where population > 100000;
2) select sum(population) from city where district = 'California';
3) select round(avg(population)) from city;
4) select sum(population) from city where countrycode = 'JPN';
5) SELECT MAX(POPULATION) - MIN(POPULATION) FROM CITY;
6) SELECT CEIL(AVG(salary) - AVG(REPLACE(salary, '0', ''))) FROM employees;
7) SELECT months*salary, COUNT(*) FROM employee GROUP BY months*salary ORDER
BY months*salary DESC LIMIT 1;
8) SELECT ROUND(SUM(LAT_N),2), ROUND(SUM(LONG_W),2) FROM STATION;
9) SELECT truncate(SUM(LAT_N), 4) FROM STATION WHERE LAT_N > 38.7880 AND
LAT_N < 137.2345 ;
10) SELECT ROUND(MAX(lat_n), 4) FROM station WHERE lat_n < 137.2345;
11) select round(long_w, 4) from station where (select max(lat_n) from station where
lat_n < 137.2345) = lat_n;
12) select round(min(lat_n), 4) from station where lat_n > 38.7780;
13) select round(long_w, 4) from station where (select min(lat_n) from station where
lat_n > 38.7780) = lat_n;
14) select round(max(LAT_N)-min(LAT_N) + max(LONG_W) - min(LONG_W), 4) from
station;
15) select round(sqrt(power(max(LAT_N)-min(LAT_N),2) + power(max(LONG_W) -
min(LONG_W),2)), 4) from station;
16) SELECT ROUND(AVG(lat_n), 4) AS median FROM ( SELECT lat_n, ROW_NUMBER()
OVER (ORDER BY lat_n) AS rn FROM station ) AS subq WHERE rn = (SELECT
CEIL((COUNT(rn)+1)/2) FROM station) OR rn = (SELECT FLOOR((COUNT(rn)+1)/2)
FROM station) ;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with
aggregate functions.
1) select sum(ci.population) from city ci join country co on co.code = ci.countrycode
where co.continent = 'Asia';
2) select (ci.name) from city ci join country co on co.code = ci.countrycode where
co.continent = 'Africa';
3) select (co.Continent), floor(avg(ci.population)) from city ci join country co on co.code
= ci.countrycode group by co.continent;
4) SELECT CASE WHEN Grades.Grade < 8 THEN 'NULL' ELSE Students.Name END,
Grades.Grade, Students.Marks FROM Students, Grades WHERE Students.Marks >=
Grades.Min_mark AND Students.Marks <= Grades.Max_mark ORDER BY
Grades.Grade DESC, Students.Name;
5) SELECT Submissions.hacker_id, Hackers.name from Hackers, Submissions,
Challenges, Difficulty
WHERE Submissions.score = Difficulty.score
AND Hackers.hacker_id = Submissions.hacker_id
AND Submissions.challenge_id = Challenges.challenge_id
AND Challenges.difficulty_level = Difficulty.difficulty_level
GROUP BY Submissions.hacker_id, Hackers.name
HAVING count(*) > 1
ORDER BY count(*) DESC, Submissions.hacker_id ASC;
6) WITH a AS(
SELECT h.hacker_id, name, count(c.challenge_id) AS nums
FROM hackers h join challenges c ON h.hacker_id = c.hacker_id
GROUP BY h.hacker_id,h.name)
SELECT hacker_id, name, nums
FROM a
WHERE nums NOT IN (
SELECT nums FROM a WHERE nums < (
SELECT max(nums) FROM a
)
GROUP BY nums
HAVING count(nums) > 1 )
ORDER BY nums desc, hacker_id;
7) SELECT id, age, coins_needed, power FROM Wands JOIN Wands_Property ON
Wands.code = Wands_Property.code
WHERE (age, coins_needed, power) IN (
SELECT age, MIN(coins_needed), power
FROM Wands JOIN Wands_Property ON Wands.code = Wands_Property.code
WHERE Wands_Property.is_evil = 0
GROUP BY age, power)
ORDER BY power DESC, age DESC;
8) SELECT temp1.hacker_id, temp1.name, SUM(temp1.score) AS total_score
FROM
(SELECT Hackers.hacker_id, Hackers.name, Submissions.challenge_id, MAX(score)
AS score
FROM Hackers INNER JOIN Submissions ON Hackers.hacker_id =
Submissions.hacker_id
GROUP BY Hackers.name, Hackers.hacker_id, Submissions.challenge_id) AS temp1
GROUP BY temp1.hacker_id, temp1.name
having SUM(temp1.score) > 0
ORDER BY total_score DESC, temp1.hacker_id ASC;
The DATEADD() function adds a time/date interval to a date and then returns the
date.
DATEADD(interval, number, date)
Parameter Description
interval Required. The time/date interval to add.
Can be one of the following values:
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear, dy, y = Day of the year
day, dd, d = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
number Required. The number of interval to add to
date. Can be positive (to get dates in the
future) or negative (to get dates in the past)
date Required. The date that will be modified
The DATEDIFF() function returns the difference between two dates, as an integer.
DATEDIFF(interval, date1, date2)
Parameter Description
interval Required. The part to return. Can be one of
the following values:
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
date1, date2 Required. The two dates to calculate the
difference between
DENSE_RANK ( ) OVER ( [ <partition_by_clause> ] < order_by_clause > )
This function returns the rank of each row within a result set partition, with no gaps
in the ranking values. The rank of a specific row is one plus the number of distinct
rank values that come before that specific row.
Returns the rank of each row within the partition of a result set. The rank of a row is
one plus the number of ranks that come before the row in question.
RANK ( ) OVER ( [ partition_by_clause ] order_by_clause )
1) SELECT d.startdate, DATEADD(day, d.days, d.startdate) FROM (SELECT c.startdate AS
startdate, MIN(c.diff) AS days FROM (SELECT a.Start_Date as startdate, b.End_Date as
enddate, DATEDIFF(day, a.Start_Date, b.End_Date) as diff
FROM(SELECT Start_Date FROM Projects WHERE Start_Date NOT IN (SELECT
End_Date FROM Projects)) AS a, (SELECT End_Date FROM Projects WHERE End_Date
NOT IN (SELECT Start_Date FROM Projects)) AS b WHERE Start_Date < End_Date) AS
c GROUP BY c.startdate) AS d ORDER BY d.days ASC, d.startdate;
2) SELECT NAME FROM students S INNER JOIN friends F ON S.id = F.id INNER JOIN
packages P ON S.id = P.id INNER JOIN packages P2 ON F.friend_id = P2.id WHERE
P.salary < P2.salary ORDER BY P2.salary;
3) SELECT x1, y1 FROM ((SELECT F.x AS X1, F.y AS Y1 FROM functions F INNER JOIN
functions F2 ON F.x = F2.y AND F2.x = F.y AND F.x <> F.y) UNION (SELECT F.x AS X1, F.y
AS Y1 FROM functions F INNER JOIN functions F2 ON F.x = F2.y AND F2.x = F.y AND
F.x = F.y GROUP BY F.x, F.y HAVING Count(*) > 1)) AS FUNCT WHERE x1 <= y1 ORDER
BY x1;
4) SELECT CT.contest_id, CT.hacker_id, CT.name, SUM(TS), SUM(TAS), SUM(TV),
SUM(TUV)
FROM Contests AS CT
JOIN Colleges AS CL ON CT.contest_id = CL.contest_id
JOIN Challenges AS CH ON CH.college_id = CL.college_id
left JOIN ( SELECT CHALLENGE_ID, SUM(total_views) AS TV,
SUM(total_unique_views) AS TUV FROM View_Stats GROUP BY CHALLENGE_ID ) VS
ON CH.challenge_id = VS.challenge_id
left JOIN (SELECT CHALLENGE_ID, SUM(TOTAL_SUBMISSIONS) AS TS,
SUM(TOTAL_ACCEPTED_SUBMISSIONS) AS TAS FROM Submission_Stats GROUP BY
CHALLENGE_ID ) AS SS ON CH.challenge_id = SS.challenge_id
GROUP BY CT.contest_id, CT.hacker_id, CT.name
ORDER BY CT.contest_id;
5) with cte as (
select s.submission_date,s.hacker_id, h.name, count(*) as no_of_Submissions,
DENSE_RANK() over (order by s.submission_date) as Day_Number
from Submissions s, hackers h where h.hacker_id = s.hacker_id
group by s.submission_date,s.hacker_id, h.name
),
cte2 as(
select *
,count(*) over(partition by hacker_id order by submission_date) as
till_date_Submisssion,
case when Day_Number = count(*) over(partition by hacker_id order by
submission_date) then 1 else 0 end as Unique_flag
from cte
),
cte3 as (
select * ,SUM(Unique_flag) over (partition by submission_date ) as unique_count,
ROW_NUMBER() over (partition by submission_date order by no_of_Submissions
desc, hacker_id ) as rn
from cte2
)
select submission_date,unique_count,hacker_id, name from cte3
where rn=1
order by submission_date,hacker_id;
DUAL -- This is a special dummy table in Oracle used when you just want to select
something without referencing a real table.
RPAD(string, length, pad_string)
Pads the string on the right with the given characters until the total string length = length.
In Oracle, CONNECT BY is normally used to:
Traverse parent-child relationships (like in an org chart or tree)
Recursively generate rows based on some logic
In hierarchical queries, Oracle auto-generates a pseudo-column called LEVEL, which:
Starts at 1
Increments by 1 each time Oracle goes one step deeper in the hierarchy
https://docs.oracle.com/en/database/oracle/oracle-database/18/sqlrf/Hierarchical-
Queries.html#GUID-0118DF1D-B9A9-41EB-8556-C6E7D6A5A84E
1) SELECT RPAD('*', (21-LEVEL)*2, ' *') FROM DUAL CONNECT BY LEVEL <= 20;
2) SELECT RPAD('*', 2 * LEVEL - 1, ' *') FROM DUAL CONNECT BY LEVEL <= 20;
3) WITH RECURSIVE Numbers AS ( SELECT 2 AS L UNION SELECT L + 1 FROM Numbers
WHERE L < 1000 ) SELECT GROUP_CONCAT(L SEPARATOR '&') AS PrimeNumbers
FROM Numbers WHERE NOT EXISTS ( SELECT 1 FROM Numbers AS N2 WHERE N2.L >
1 AND N2.L < Numbers.L AND Numbers.L % N2.L = 0 ) AND L <= 1000;