You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SELECT country from person GROUP BY country;
SELECT DISTINCT country from person; /* Bothe output will be same */-- To count the countries by grouping, using COUNTSELECT country, COUNT(*) from person GROUP BY country; -- Note field should be the same in SELECT and GROUP BY command.SELECT country, COUNT(*) from person GROUP BY country ORDER BY country ASC; /* Sorting by country */SELECT country, COUNT(*) from person GROUP BY country ORDER BY country DESC;
Filter with GROUP BY using HAVING command.
SELECT country, COUNT(*) from person GROUP BY country HAVINGCOUNT(*) >5ORDER BY country; -- Grouping having country country > 5
Creating new table using Mockaroo for aggregate functions, use price range b/w 10K - 100K
createtablecar (
id BIGSERIALNOT NULLPRIMARY KEY,
make VARCHAR(100) NOT NULL,
model VARCHAR(100) NOT NULL,
price NUMERIC(19, 2) NOT NULL
);
\i /pathToFile.sql
Get max and min using MAX, MIN and AVG aggregate functions
SELECTMIN(price) from car;
SELECTMAX(price) from car;
SELECTAVG(price) from car;
SELECT ROUND(AVG(price)) from car;
-- max and min price for each car make and modelSELECT make, model, MIN(price) from car GROUP BY make, model;
SELECT make, model, MAX(price) from car GROUP BY make, model;
SELECT make, AVG(price) from car GROUP BY make;
Using SUM operator to sum values with GROUP BY
SELECTSUM(price) from car;
-- total sum of each car makeSELECT make, SUM(price) from car GROUP BY make ASC;
Some basic Arithmatic Operators
SELECT10+10;
SELECT10+5;
SELECT10*5;
SELECT10/5;
SELECT10 ^ 2;
SELECT FACTORIAL(5);
SELECT10 % 2; -- modulus-- x% Discount on each car, AS used for alias name for new column we will generate using the query SELECT id, car, make, price, ROUND(price * .10, 2) AS discount, ROUND(price - price * .10, 2) AS finalPrice from car;