sql

Group by full example SQL query

Full example of 'group by' statement in SQL that we are using to find the sum of quantity for stock_company table based on price

-- create a table
CREATE TABLE stock_company (
  id INTEGER PRIMARY KEY,
  company VARCHAR(200) NOT NULL,
  price INT NOT NULL,
  quantity INT NOT NULL
);
-- insert some values
INSERT INTO stock_company VALUES (1, 'Microsoft', 100, 10);
INSERT INTO stock_company VALUES (2, 'Google', 99, 5);
INSERT INTO stock_company VALUES (3, 'Google', 99, 20);
INSERT INTO stock_company VALUES (4, 'Google', 99, 10);
INSERT INTO stock_company VALUES (5, 'Google', 101, 15);

-- fetch values - GROUP BY price
select company, price, sum(quantity) as total_quantity
from stock_company 
group by price;

--  OUTPUT TABLE
--  +----+-------------+--------+-----------------+
--  | Id | company     | price  | total_quantity  |
--  +----+-------------+--------+-----------------+
--  | 1  | Google      | 99     | 99              |
--  | 2  | Microsoft   | 100    | 100             |
--  | 3  | Google      | 101    | 101             |
--  +----+-------------+--------+-----------------+
Was this helpful?