💻
notes
  • Initial page
  • sql
    • date-and-time
    • Ordering Columns
    • Replacing Portions of Text
    • count-rows
    • Changing the Case of Strings
    • Create Excerpts with Substring
    • Transactions
    • removing-data
    • Finding Length of Strings
    • add-row-to-a-table
    • limit-and-paginate-results
    • Concatenating Strings
    • SQL JOINs
    • basic-math
    • updating-rows-in-a-table
    • Subqueries
    • Set Operations
    • SQL Basics Cheatsheet
  • ruby
    • gems
      • Auto use Ruby version with gemset
      • Must Have Gems
      • Create Devise user without any validation
    • rails
      • What are the differences between #where and #find?
  • postgresql
    • Export database dump from Heroku and import to local database
  • glossary
  • vim
    • Edit Recorded Macros
    • Sort Multiple Lines
    • Search and Replace
    • Folding
  • iTerm
  • git
    • Git
  • Command Line Utilities
  • How To Use Notes
  • Terminal Cheatsheet for Mac
Powered by GitBook
On this page
  • Counting Results
  • Obtaining Totals
  • Calculating Averages
  • Finding the Maximum and Minimum Values
  • Mathematical Operators

Was this helpful?

  1. sql

basic-math

Counting Results

To count rows you can use the COUNT() function.

SELECT COUNT(*) FROM <table>;

To count unique entries use the DISTINCT keyword too:

SELECT COUNT(DISTINCT <column>) FROM <table>;

To count aggregated rows with common values use the GROUP BY keywords:

SELECT COUNT(<column>) FROM <table> GROUP BY <column with common value>;

Obtaining Totals

To total up numeric columns use the SUM() function.

SELECT SUM(<numeric column) FROM <table>;
SELECT SUM(<numeric column) AS <alias> FROM <table>
                                       GROUP BY <another column>
                                       HAVING <alias> <operator> <value>;

Calculating Averages

To get the average value of a numeric column use the AVG() function.

SELECT AVG(<numeric column>) FROM <table>;
SELECT AVG(<numeric column>) FROM <table> GROUP BY <other column>;

Finding the Maximum and Minimum Values

To get the maximum value of a numeric column use the MAX() function.

SELECT MAX(<numeric column>) FROM <table>;
SELECT MAX(<numeric column>) FROM <table> GROUP BY <other column>;

To get the minimum value of a numeric column use the MIN() function.

SELECT MIN(<numeric column>) FROM <table>;
SELECT MIN(<numeric column>) FROM <table> GROUP BY <other column>;

Mathematical Operators

  • * Multiply

  • / Divide

  • + Add

  • - Subtract

SELECT <numeric column> <mathematical operator> <numeric value> FROM <table>;
PreviousSQL JOINsNextupdating-rows-in-a-table

Last updated 5 years ago

Was this helpful?