Explain Codes LogoExplain Codes Logo

Sqlplus statement from the command line

sql
sqlplus
security
complex-queries
Alex KataevbyAlex Kataev·Aug 5, 2024
TLDR

Silently run a SQLPlus query from your command line with echo and pipe (|):

echo "SELECT SYSDATE FROM dual;" | sqlplus -s user/pass@db # "Don't be late, get the date!"

In this line, replace user, pass, and db with your credentials and target database. This concise one-liner fetches the current date from Oracle's dummy table dual.

Protect your credentials

Security should be your top priority when dealing with database queries. Hardcoding your credentials in your command is not only poor practice, but also a highly risky one. Look into secure storage options, like environment variables or Oracle's wallet feature, to keep sensitive data safe.

# DO NOT do this at home (or at work)! echo "SELECT SYSDATE FROM dual;" | sqlplus scott/tiger@ORCL

Complex queries and here documents

Here documents are your best friend for handling multi-line or intricate SQL queries:

sqlplus -s user/pass@db <<EOF # "Dear SQLPlus, here's a letter..." SELECT department_id, department_name FROM departments WHERE location_id = 1700; EXIT; # "...and that's all folks!" EOF

Using <<EOF and EOF to encase commands is a powerful way to run complex SQLPlus queries right from the command line.

Connect effectively with SQLPlus

Your connection details must be accurate. The connection string username/password@host:port/service should be tweaked to match your actual settings:

sqlplus -s user/pass@localhost:1521/ORCL # "Knock, knock! It's SQLPlus at port!"

For a more seamless experience, use the -s option. This little switch suppresses unnecessary messages, keeping your output clean and your sanity intact.

Better queries with less junk

Why create temporary files if you have a one-liner that gives direct output in the terminal?

echo "SELECT SYSDATE FROM dual;" | sqlplus -s user/pass@db # "Just keeping it simple!"

This straightforward approach lets you execute queries and pull out results right in your terminal.

Making complex SQL queries work

For complex SQL queries, echo -e is super helpful for line breaks and improving readability:

echo -e "SELECT \\n department_id, \\n department_name \\nFROM departments;" | sqlplus -s user/pass

So make your SQL complex but sexy!

Secure your scripts

Ensure you're handling usernames and passwords properly when scripting SQLPlus commands. An essential trick is to use parameter substitution or encryption, particularly critical in an automated setup.

# In bash script, security is not a joke! (Unless you're a hacker.)