📖
Notes
  • 🙌Welcome!
  • CyberSecurity
    • Penetration Testing
      • ELearnSecurity
        • eJPT
          • Footprinting & Scanning
            • Port Scanning
            • Mapping Networks
          • Information Gathering
            • Subdomain Enumeration
          • Network Attacks
            • Arp Poisoning
            • Null Sessions
            • Windows Shares
            • Authentication Cracking
          • Networking
            • Python Server to Receive Exfiltrated Data
            • CLI Tool to interact with HTTP/HTTPS
          • Programming
            • C++ Keylogger
            • C++ Information Stealer
          • System Attacks
            • Pivoting
            • Backdoor
          • Vulnerability Assessment
          • Web Attacks
            • SQL Injection
            • HTTP Verbs
            • Web Server Fingerprinting
      • PortSwigger
        • Cross-origin resource sharing (CORS)
          • Access-Control-Allow-Origin response header
          • Vulnerabilities arising from Misconfigurations
            • Server-generated ACAO header from client-specified Origin header
            • Errors parsing Origin headers
            • Whitelisted null origin value
            • Exploiting XSS via CORS trust relationships
            • Breaking TLS with poorly configured CORS
            • Intranets and CORS without credentials
            • Mitigations
        • Sql Injection
          • Examining the database
          • Retrieving data from other database tables
          • Blind SQL injection
          • Mitigation
      • TryHackMe
        • Main Methodology
          • 1. Reconnaissance
            • Google Dorking
            • Metadata Reader/Writer
            • Steghide - Stegnography
            • OSINT Framework
          • 2. Enumeration/Scanning
            • NFS Enumeration Tools
            • NMAP - Port Scanning
            • Web Enumeration Tools
            • SMB Enumeration Tools
            • SMTP Enumeration Tools
            • Shodan - IOT Search Engine
            • FTP Enumeration Tools
            • Wordpress Enumeration Tools
            • OWASP ZAP - WebApp Testing
            • BurpSuite - WebApp Testing
            • MySQL Enumeration Tools
            • Wordlists
          • 3. Gaining Access / Exploitation
            • Buffer Overflow
              • 1. Immunity Debugger
              • 2. Mona Setup
              • 3. Spiking
              • 4. Fuzzing
              • 5. Crash Replication & Controlling EIP
              • 6. Finding Bad Characters
              • 7. Find a Jump Point
              • 8. Generate Payload
              • 9. Prepend NOPs
              • 10. Final Buffer
            • Cryptography
              • Hash Crack Tools
              • Online Password Cracking Tools
              • Encryption
              • John the Ripper
            • Evasion Techniques
            • Shells
              • Powershell
              • Msfvenom
              • Meterpreter
              • Metasploit -- multi/handler
              • Netcat
              • Socat
            • Web Applications
              • OWASP Top 10
              • File Upload Vulnerabilities
              • Authentication Vulnerability
              • XML External Entity (XXE)
              • Cross-Site Scripting (XSS)
              • ZTH: Obscure Web Vulns
              • Server Side Request Forgery (SSRF)
              • Insecure Direct Object Reference (IDOR)
              • ZTH : Continued
              • File Inclusion Vulnerability
                • Local File Inclusion (LFI)
                • Log Poisoning Attack (LFI to RCE via Log files)
            • Windows Applications
              • Jenkins
              • Windows Active Directory
                • Impacket's secretsdump.py
                • Kerberos
                  • Enumerating Users with Kerbrute
                  • Enumerating SPN Accounts with Powershell
                  • Get SPN Account Ticket with Invoke-Kerberoast
                  • Kerberoasting with Rubeus & Impacket
                  • AS-REP Roasting with Rubeus/GetNPUsers.py
                  • Pass the Ticket with mimikatz
                  • Golden/Silver Ticket Attacks with mimikatz
                  • Kerberos Backdoors with mimikatz
                  • Harvesting and Brute-Forcing with Rubeus
                  • Conclusion and Resources
          • 4. Post Exploitation
            • Privilege Escalation
              • Linux
                • 1. Introduction
                • 2. Scripts
                • 3. Kernel Exploits
                • 4. Service Exploits
                • 5. Weak File Permissions
                • 6. Sudo
                • 7. Cron jobs
                • 8. SUID/SGID Executable
                • 9. CAP_SETUID Capabilities Executable
                • 10. Passwords & Keys
                • 11. NFS
                • PrivEsc CTF Checklists
              • Windows
                • Token Impersonation
                • PrivEsc CTF Checklists
                • Permission
                • Scripts
                • Unquoted Service Path
            • Tools
              • Meterpreter Modules
              • Impacket's Psexec
              • Impacket's mssqlclient.py
              • Firefox Decryptor
              • Socat - Reverse TCP Tunnel
            • Windows Active Directory
              • Enumeration with Powerview
              • Enumeration with Bloodhound (GUI)
              • Dumping Hashes with mimikatz
              • Golden Ticket Attacks with mimikatz
              • Enumeration with Server Manager
              • Maintaining Access
              • Additional Resources
          • 5. Covering Tracks
          • 6. Reporting
        • Networking Concepts
          • SSH Reverse Tunnels
        • Scripting
          • Curl
          • Powershell
            • Basic Powershell Commands
            • Enumeration
        • Web Extensions
          • Shodan
          • Wappalyzer
      • Miscellaneous
        • SMTP Enumeration
        • Nmap Advanced Scanning
        • Persistence via Meterpreter
        • DNS Enumeration
        • NetBIOS & SMB
        • DHCP Starvation
        • Packet Manipulation
        • Hash Cracking
        • MITM
        • Msfvenom Payload in APK (Manual Embedding)
    • Blue Teaming
      • Digital Forensics & Incidence Response
        • Memory Acquisition with LIME
        • Disk Analysis with Autopsy
        • Data and Memory Collection with FireEye Redline
        • Memory Forensice with Volatility
      • Intrusion Detection
        • Intrusion Detection Systems (IDS)
        • Threat Monitoring with Security Information & Event Management (SIEM)
        • Security Event Monitoring
        • Host Based Intrusion Detection System (HIDS) - OSSEC
      • Miscellaneous
        • Docker Image Security Analysis with Trivy
  • DevOps
    • Infrastructure as a Code (IaC)
      • Ansible
        • 1. Playbooks
        • 2. Modules
        • 3. Inventory
        • 4. Roles
        • 5. Ansible Tower
      • Terraform
        • 1. Overview
        • 2. Modify Resources
        • 3. Delete Resources
        • 4. Reference Resources
        • 5. Terraform Files
        • 6. Terraform State Commands
        • 7. Terraform Output
        • 8. Target Resources
        • 9. Terraform Variables
        • 10. Expressions + Functions
        • 11. Meta-Arguments
        • 12. Modules
        • 13. Managing Multiple Environments
        • 14. Testing Terraform Code
        • 15. Final Thoughts
    • Orchestration
      • Kubernetes
        • 1. Main K8s Components
        • 2. K8s Architecture
        • 3. Minikube & Kubectl
        • 4. YAML Configuration File
        • 5. K8s Namespaces
        • 6. K8s Ingress
        • 7. Helm - Package Manager of K8s
        • 8. K8 Volumes
        • 9. K8 StatefulSet
        • 10. K8 Services
  • Development
    • Blockchain
      • FreeCodeCamp Course
        • 1. Introduction
        • 2. Solidity Basics
        • 3. Storage Factory
        • 4. Fund Me
        • 5. Ethers.js
        • 6. Hardhat
        • 7. Hardhat | Fund Me
        • 8. Contract Lottery | Raffle
        • 9. IPFS
        • 10. ERC20s
        • 11. DeFi & Aave
        • 12. NFTs | Encoding
        • 13. Reentrancy Attack
    • Backend
      • NodeJs
        • Introduction
        • Additional Concepts
        • ExpressJs
    • Database
      • SQL
        • Basics
          • 1. Querying Data
          • 2. Filtering Data
          • 3. Joining Multiple Tables
          • 4. Grouping Data
          • 5. Set Operations
          • 6. Grouping Sets, Cube, and Rollup
          • 7. Subquery
          • 8. Common Table Expressions
          • 9. Modifying Data
          • 10. Transactions
          • 11. Import & Export Data
          • 12. Managing Tables
    • Testing
      • Test Driven Development (TDD)
      • Jest js
      • Cypress js
Powered by GitBook
On this page
  • Insert
  • Insert multiple rows
  • Update
  • Update join
  • Delete
  • Upsert
  1. Development
  2. Database
  3. SQL
  4. Basics

9. Modifying Data

Insert

(guide you on how to insert a single row into a table.)

  • allows you to insert a new row into a table.

  • Its syntax is

INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …);
  • Its return format is

INSERT oid count
  • OID is an object identifier. PostgreSQL used the OID internally as a primary key for its system tables. Typically, the INSERT statement returns OID with value 0

  • The count is the number of rows that the INSERT statement inserted successfully

Returning Clause

  • The INSERT statement also has an optional RETURNING clause that returns the information of the inserted row.

Example 1 (return the entire inserted row)

INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …)
RETURNING *;

Example 2 (returns the id of the inserted row)

INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …)
RETURNING id;

Example 3 (rename the returned value)

INSERT INTO table_name(column1, column2, …)
VALUES (value1, value2, …)
RETURNING output_expression AS output_name;

Examples

1. Inserting a single row into a table

INSERT INTO links (url, name)
VALUES('https://google.com', 'Google');

It returns

INSERT 0 1

2. Inserting character string that contains a single quote

you have to use an additional single quote (') to escape it.

INSERT INTO links (url, name)
VALUES('http://www.oreilly.com','O''Reilly Media');

3. Inserting a date value

To insert a date value into a column with the DATE type, you use the date in the format 'YYYY-MM-DD'.

INSERT INTO links (url, name, last_update)
VALUES ('https://google.com', 'Google', '2013-06-01')

Insert multiple rows

(show you how to insert multiple rows into a table.)

  • To insert multiple rows into a table using a single INSERT statement, you use the following syntax:

INSERT INTO table_name (column_list)
VALUES
    (value_list_1),
    (value_list_2),
    ...
    (value_list_n);

Example (Inserting multiple rows and returning inserted rows)

INSERT INTO
    links(url,name, description)
VALUES
    ('https://duckduckgo.com/','DuckDuckGo','Privacy & Simplified Search Engine'),
    ('https://swisscows.com/','Swisscows','Privacy safe WEB-search')
RETURNING *;

Update

(update existing data in a table.)

  • The PostgreSQL UPDATE statement allows you to modify data in a table.

  • Its syntax is

UPDATE table_name
SET column1 = value1,
    column2 = value2,
    ...
WHERE condition;
  • it returns the following command tag

UPDATE count
  • where count is the number of rows updated including rows whose values did not change.

Returning updated rows

It also have optional RETURNING clause like INSERT statement that returns the updated rows

UPDATE table_name
SET column1 = value1,
    column2 = value2,
    ...
WHERE condition
RETURNING * | output_expression AS output_name;

Example (updating a row and returning the updated row)

UPDATE courses
SET published_date = '2020-07-01'
WHERE course_id = 2
RETURNING *;

Update join

(update values in a table based on values in another table.)

  • Sometimes, you need to update data in a table based on values in another table. In this case, you can use the PostgreSQL UPDATE join syntax as follows:

UPDATE t1
SET t1.c1 = new_value
FROM t2
WHERE t1.c2 = t2.c2;

Example

Calculate the net price of every product based on the discount of the product segment

UPDATE
	product p
SET
	net_price = price - price * discount
FROM
	product_segment s
WHERE
	p.segment_id = s.id;

Delete

(delete data in a table.)

  • It allows us to delete one or more rows from a table

  • Its syntax is

DELETE FROM table_name
WHERE condition;
  • The DELETE statement returns the number of rows deleted.

  • To return the deleted row(s) to the client, you use the RETURNING clause as follows:

DELETE FROM table_name
WHERE condition
RETURNING (select_list | *)

Example

Deletes the rows with ids 6 and 7 and returns the deleted row to the client

DELETE FROM links
WHERE id IN (6, 7)
RETURNING *;

Upsert

(insert or update data if the new row already exists in the table.)

  • The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).

  • We can use the INSERT ON CONFLICT statement as follows

INSERT INTO table_name(column_list)
VALUES(value_list)
ON CONFLICT target action;
  • target can be

    • (column_name) – a column name.

    • ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint.

    • WHERE predicate – a WHERE clause with a predicate.

  • action can be

    • DO NOTHING – means do nothing if the row already exists in the table.

    • DO UPDATE SET column_1 = value_1, .. WHERE condition – update some fields in the table.

Example

Concatenate the new email with old email when inserting a customer that already exists

INSERT INTO customers (name, email)
VALUES('Microsoft', 'hotline@microsoft.com')
ON CONFLICT (name)
DO
	UPDATE SET email = EXCLUDED.email || ';' || customers.email;
Previous8. Common Table ExpressionsNext10. Transactions

Last updated 1 year ago